From 24a2de7389e42070e428f825d0c8aedb276e6d6d Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 17 Jun 2015 16:00:16 +0800 Subject: [PATCH 01/62] Sort parameters to move required ones in front of optional ones --- .../main/java/io/swagger/codegen/DefaultCodegen.java | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 71b6295c9bee..59e7078be2d7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -49,6 +49,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; +import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; @@ -850,6 +851,17 @@ public class DefaultCodegen { } op.bodyParam = bodyParam; op.httpMethod = httpMethod.toUpperCase(); + // move "required" parameters in front of "optional" parameters + Collections.sort(allParams, new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + boolean oneRequired = one.required == null ? false : one.required; + boolean anotherRequired = another.required == null ? false : another.required; + if (oneRequired == anotherRequired) return 0; + else if (oneRequired) return -1; + else return 1; + } + }); op.allParams = addHasMore(allParams); op.bodyParams = addHasMore(bodyParams); op.pathParams = addHasMore(pathParams); From 7f4586a47f871e7119bf4c2a9c242ba0ff8b3fa9 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 17 Jun 2015 16:00:59 +0800 Subject: [PATCH 02/62] Fix comment regarding required parameter in PHP generator --- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 12d2eb807449..5166889fc3fd 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -60,7 +60,7 @@ class {{classname}} { * * {{{summary}}} * -{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} +{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}}{{#required}} (required){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { From 9c4e5ed5965e65815bca7d835591cec26a6d4ca9 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 17 Jun 2015 16:15:37 +0800 Subject: [PATCH 03/62] Rebuild Petstare sample for Java, Android, PHP, etc. --- .../scala/io/swagger/client/api/PetApi.scala | 4 ++-- .../java/io/swagger/client/api/PetApi.java | 4 ++-- .../java/io/swagger/client/model/Pet.java | 2 +- .../io/swagger/petstore/test/PetApiTest.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 6 ++--- .../java/io/swagger/client/model/Pet.java | 2 +- .../io/swagger/petstore/test/PetApiTest.java | 2 +- .../php/SwaggerClient-php/lib/PetApi.php | 22 +++++++++---------- .../php/SwaggerClient-php/lib/StoreApi.php | 2 +- .../php/SwaggerClient-php/lib/UserApi.php | 12 +++++----- .../petstore/ruby/lib/swagger_client.rb | 2 +- .../ruby/lib/swagger_client/api/pet_api.rb | 2 +- 12 files changed, 31 insertions(+), 31 deletions(-) diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala index d5ae6fd65f05..591d055dad6b 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -108,10 +108,10 @@ object PetApi { * Expected answers: * code 400 : (Invalid pet value) * - * @param apiKey * @param petId Pet id to delete + * @param apiKey */ - def deletePet(apiKey: Option[String] = None, petId: Long): ApiRequest[Unit] = + def deletePet(petId: Long, apiKey: Option[String] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") .withPathParam("petId", petId) .withHeaderParam("api_key", apiKey) 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 ebf600d787e1..68121b9376a1 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 @@ -391,11 +391,11 @@ public class PetApi { /** * Deletes a pet * - * @param apiKey * @param petId Pet id to delete + * @param apiKey * @return void */ - public void deletePet (String apiKey, Long petId) throws ApiException { + public void deletePet (Long petId, String apiKey) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 26219b16a458..90a840e6e422 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; 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 a4900a92b9b8..ca868d2ea22a 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 @@ -118,7 +118,7 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - api.deletePet(null, fetched.getId()); + api.deletePet(fetched.getId(), null); try { fetched = api.getPetById(fetched.getId()); 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 c102cf00b514..28608fd0d389 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 @@ -322,7 +322,7 @@ public class PetApi { } try { - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); if(response != null){ return (Pet) apiClient.deserialize(response, "", Pet.class); @@ -417,11 +417,11 @@ public class PetApi { /** * Deletes a pet * - * @param apiKey * @param petId Pet id to delete + * @param apiKey * @return void */ - public void deletePet (String apiKey, Long petId) throws ApiException { + public void deletePet (Long petId, String apiKey) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index ddd0e1038c08..cf7ace02309c 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 7178049d644f..b6ad5fb05275 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -151,7 +151,7 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - api.deletePet(null, fetched.getId()); + api.deletePet(fetched.getId(), null); try { fetched = api.getPetById(fetched.getId()); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 2e1b2aa262ed..03883d01bfd7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -59,7 +59,7 @@ class PetApi { * * Update an existing pet * - * @param Pet $body Pet object that needs to be added to the store (required) + * @param Pet $body Pet object that needs to be added to the store * @return void */ public function updatePet($body) { @@ -113,7 +113,7 @@ class PetApi { * * Add a new pet to the store * - * @param Pet $body Pet object that needs to be added to the store (required) + * @param Pet $body Pet object that needs to be added to the store * @return void */ public function addPet($body) { @@ -167,7 +167,7 @@ class PetApi { * * Finds Pets by status * - * @param array[string] $status Status values that need to be considered for filter (required) + * @param array[string] $status Status values that need to be considered for filter * @return array[Pet] */ public function findPetsByStatus($status) { @@ -225,7 +225,7 @@ class PetApi { * * Finds Pets by tags * - * @param array[string] $tags Tags to filter by (required) + * @param array[string] $tags Tags to filter by * @return array[Pet] */ public function findPetsByTags($tags) { @@ -327,7 +327,7 @@ class PetApi { } // authentication setting, if any - $authSettings = array('petstore_auth', 'api_key'); + $authSettings = array('api_key', 'petstore_auth'); // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, @@ -348,8 +348,8 @@ class PetApi { * 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) + * @param string $name Updated name of the pet + * @param string $status Updated status of the pet * @return void */ public function updatePetWithForm($pet_id, $name, $status) { @@ -414,11 +414,11 @@ class PetApi { * * Deletes a pet * - * @param string $api_key (required) * @param int $pet_id Pet id to delete (required) + * @param string $api_key * @return void */ - public function deletePet($api_key, $pet_id) { + public function deletePet($pet_id, $api_key) { // verify the required parameter 'pet_id' is set if ($pet_id === null) { @@ -478,8 +478,8 @@ class PetApi { * 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 string $file file to upload (required) + * @param string $additional_metadata Additional data to pass to server + * @param string $file file to upload * @return void */ public function uploadFile($pet_id, $additional_metadata, $file) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 87937a60283f..eb15f2d97cd5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -113,7 +113,7 @@ class StoreApi { * * Place an order for a pet * - * @param Order $body order placed for purchasing the pet (required) + * @param Order $body order placed for purchasing the pet * @return Order */ public function placeOrder($body) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index 2e16022f25a5..387c093dcea6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -59,7 +59,7 @@ class UserApi { * * Create user * - * @param User $body Created user object (required) + * @param User $body Created user object * @return void */ public function createUser($body) { @@ -113,7 +113,7 @@ class UserApi { * * 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 * @return void */ public function createUsersWithArrayInput($body) { @@ -167,7 +167,7 @@ class UserApi { * * 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 * @return void */ public function createUsersWithListInput($body) { @@ -221,8 +221,8 @@ class UserApi { * * 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) + * @param string $username The user name for login + * @param string $password The password for login in clear text * @return string */ public function loginUser($username, $password) { @@ -397,7 +397,7 @@ class UserApi { * Updated user * * @param string $username name that need to be deleted (required) - * @param User $body Updated user object (required) + * @param User $body Updated user object * @return void */ public function updateUser($username, $body) { diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb index 998658c8b6e4..6d239185005c 100644 --- a/samples/client/petstore/ruby/lib/swagger_client.rb +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -16,8 +16,8 @@ require 'swagger_client/models/order' # APIs require 'swagger_client/api/user_api' -require 'swagger_client/api/store_api' require 'swagger_client/api/pet_api' +require 'swagger_client/api/store_api' module SwaggerClient # Initialize the default configuration 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 2ce4fb04ecd6..7bed9b47780c 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 @@ -190,7 +190,7 @@ module SwaggerClient post_body = nil - auth_names = ['petstore_auth', 'api_key'] + auth_names = ['api_key', 'petstore_auth'] response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body obj = Pet.new() and obj.build_from_hash(response) end From b39d44db0356c020be24cd5676af65cf3d7e275e Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 17 Jun 2015 16:16:44 +0800 Subject: [PATCH 04/62] Add missing petstore scripts to bin/all-petstore.sh --- bin/all-petstore.sh | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 8937200c77f7..1ae311848a0c 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -18,19 +18,25 @@ if [ ! -d "${APP_DIR}" ]; then fi cd $APP_DIR +./bin/akka-scala-petstore.sh ./bin/android-java-petstore.sh ./bin/csharp-petstore.sh ./bin/dynamic-html.sh ./bin/html-petstore.sh -./bin/jaxrs-petstore-server.sh ./bin/java-petstore.sh -./bin/qt5-petstore.sh +./bin/jaxrs-petstore-server.sh +./bin/nodejs-petstore-server.sh +./bin/objc-petstore.sh ./bin/perl-petstore.sh ./bin/php-petstore.sh ./bin/python-petstore.sh +./bin/python3-petstore.sh +./bin/qt5-petstore.sh ./bin/retrofit-petstore.sh ./bin/ruby-petstore.sh -./bin/objc-petstore.sh +./bin/scala-async-petstore.sh ./bin/scala-petstore.sh +./bin/scalatra-petstore-server.sh ./bin/spring-mvc-petstore-server.sh +./bin/swift-petstore.sh ./bin/tizen-petstore.sh From 7a9a41fe01d4c7d1f7bfc53c2c36440913c43e84 Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Fri, 19 Jun 2015 14:06:25 -0700 Subject: [PATCH 05/62] Java and Android template changes to accommodate query params defined by the collection-format. --- .../languages/AndroidClientCodegen.java | 2 + .../codegen/languages/JavaClientCodegen.java | 1 + .../main/resources/Java/ApiClient.mustache | 79 ++++++++++++++++--- .../main/resources/Java/QueryParam.mustache | 38 +++++++++ .../src/main/resources/Java/api.mustache | 9 ++- .../resources/Java/auth/ApiKeyAuth.mustache | 7 +- .../Java/auth/Authentication.mustache | 5 +- .../Java/auth/HttpBasicAuth.mustache | 5 +- .../main/resources/Java/auth/OAuth.mustache | 5 +- .../android-java/QueryParam.mustache | 38 +++++++++ .../main/resources/android-java/api.mustache | 10 ++- .../android-java/apiInvoker.mustache | 78 +++++++++++++++--- .../java/io/swagger/client/ApiInvoker.java | 78 +++++++++++++++--- .../java/io/swagger/client/QueryParam.java | 38 +++++++++ .../java/io/swagger/client/api/PetApi.java | 26 +++--- .../java/io/swagger/client/api/StoreApi.java | 9 ++- .../java/io/swagger/client/api/UserApi.java | 25 +++--- .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/ApiClient.java | 79 ++++++++++++++++--- .../java/io/swagger/client/QueryParam.java | 38 +++++++++ .../java/io/swagger/client/api/PetApi.java | 29 +++---- .../java/io/swagger/client/api/StoreApi.java | 9 ++- .../java/io/swagger/client/api/UserApi.java | 25 +++--- .../io/swagger/client/auth/ApiKeyAuth.java | 7 +- .../swagger/client/auth/Authentication.java | 5 +- .../io/swagger/client/auth/HttpBasicAuth.java | 5 +- .../java/io/swagger/client/auth/OAuth.java | 5 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../swagger/client/auth/ApiKeyAuthTest.java | 12 ++- .../client/auth/HttpBasicAuthTest.java | 5 +- 30 files changed, 556 insertions(+), 120 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache create mode 100644 modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache create mode 100644 samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 9a3237d92cad..2d0af4c6c0bb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -232,6 +232,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); supportingFiles.add(new SupportingFile("apiException.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("QueryParam.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "QueryParam.java")); } public Boolean getUseAndroidMavenGradlePlugin() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index fcec455e9b39..0f4e8c212ac5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -116,6 +116,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); + supportingFiles.add(new SupportingFile("QueryParam.mustache", invokerFolder, "QueryParam.java")); final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 352401ba0d8e..59a0ee732818 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -22,6 +22,8 @@ import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; +import java.util.Set; +import java.util.HashSet; import java.util.Date; import java.util.TimeZone; @@ -238,6 +240,61 @@ public class ApiClient { } } + /* + Format to {@code QueryParam} objects. + */ + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } + + if (valueCollection == null) { + params.add(new QueryParam(name, String.valueOf(value))); + return params; + } else if (valueCollection.isEmpty()) { + return params; + } + + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + if (collectionFormat.equals("csv")) { + params.add(new QueryParam(name, parameterToString(value))); + } else if (collectionFormat.equals("multi")) { + for (String item : valueCollection) { + params.add(new QueryParam(name, item)); + } + } else if (collectionFormat.equals("ssv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append(" "); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("tsv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("\t"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("pipes")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("|"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } + + return params; + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -341,23 +398,25 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); StringBuilder b = new StringBuilder(); - for(String key : queryParams.keySet()) { - String value = queryParams.get(key); - if (value != null){ - if(b.toString().length() == 0) - b.append("?"); - else + b.append("?"); + if (queryParams != null){ + for (QueryParam queryParam : queryParams){ + if (!queryParam.getName().isEmpty()) { + b.append(escapeString(queryParam.getName())); + b.append("="); + b.append(escapeString(queryParam.getValue())); b.append("&"); - b.append(escapeString(key)).append("=").append(escapeString(value)); + } } } - String querystring = b.toString(); + + String querystring = b.substring(0, b.length() - 1); Builder builder; if (accept == null) @@ -457,7 +516,7 @@ public class ApiClient { * * @param authNames The authentications to apply */ - private void updateParamsForAuth(String[] authNames, Map queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); diff --git a/modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache b/modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache new file mode 100644 index 000000000000..23b1b26f55cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache @@ -0,0 +1,38 @@ +package {{invokerPackage}}; + +public class QueryParam { + private String name = ""; + private String value = ""; + + public QueryParam(String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 63357afd896c..66dc25d66bf3 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -3,6 +3,7 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.QueryParam; import {{modelPackage}}.*; @@ -61,16 +62,16 @@ public class {{classname}} { .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); - {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + {{#queryParams}} + queryParams.addAll(apiClient.parameterToQueryParams("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{/queryParams}} {{#headerParams}}if ({{paramName}} != null) - headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); + headerParams.put("{{baseName}}", apiClient.parameterToString({{paramName}})); {{/headerParams}} final String[] accepts = { diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index 65720b958cb1..46fa51087b6b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -1,6 +1,9 @@ package {{invokerPackage}}.auth; +import {{invokerPackage}}.QueryParam; + import java.util.Map; +import java.util.Set; public class ApiKeyAuth implements Authentication { private final String location; @@ -39,7 +42,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void applyToParams(Map queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; @@ -47,7 +50,7 @@ public class ApiKeyAuth implements Authentication { value = apiKey; } if (location == "query") { - queryParams.put(paramName, value); + queryParams.add(new QueryParam(paramName, value)); } else if (location == "header") { headerParams.put(paramName, value); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 1b2e2bc2fbec..1f39a402b2c5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -1,8 +1,11 @@ package {{invokerPackage}}.auth; +import {{invokerPackage}}.QueryParam; + import java.util.Map; +import java.util.Set; public interface Authentication { /** Apply authentication settings to header and query params. */ - void applyToParams(Map queryParams, Map headerParams); + void applyToParams(Set queryParams, Map headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index 22a64b1a24e6..b5bc993f7c4e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -1,6 +1,9 @@ package {{invokerPackage}}.auth; +import {{invokerPackage}}.QueryParam; + import java.util.Map; +import java.util.Set; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; @@ -26,7 +29,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void applyToParams(Map queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index ef84b8cc05e7..ab634489edae 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -1,10 +1,13 @@ package {{invokerPackage}}.auth; +import {{invokerPackage}}.QueryParam; + import java.util.Map; +import java.util.Set; public class OAuth implements Authentication { @Override - public void applyToParams(Map queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache b/modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache new file mode 100644 index 000000000000..23b1b26f55cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache @@ -0,0 +1,38 @@ +package {{invokerPackage}}; + +public class QueryParam { + private String name = ""; + private String value = ""; + + public QueryParam(String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} 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 ed9538c15941..6e34a898ad01 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -2,6 +2,7 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiInvoker; +import {{invokerPackage}}.QueryParam; import {{modelPackage}}.*; @@ -58,17 +59,18 @@ public class {{classname}} { String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params Map formParams = new HashMap(); - {{#queryParams}}if ({{paramName}} != null) - queryParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{#queryParams}} + queryParams.addAll(ApiInvoker.parameterToQueryParams("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); + {{#headerParams}} + headerParams.put("{{baseName}}", ApiInvoker.parameterToString({{paramName}})); {{/headerParams}} String[] contentTypes = { diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index e759f8264a47..d7a9d8b357ca 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -23,6 +23,8 @@ import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.List; +import java.util.Set; +import java.util.HashSet; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -132,6 +134,61 @@ public class ApiInvoker { } } + /* + Format to {@code QueryParam} objects. + */ + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } + + if (valueCollection == null) { + params.add(new QueryParam(name, String.valueOf(value))); + return params; + } else if (valueCollection.isEmpty()) { + return params; + } + + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + if (collectionFormat.equals("csv")) { + params.add(new QueryParam(name, parameterToString(value))); + } else if (collectionFormat.equals("multi")) { + for (String item : valueCollection) { + params.add(new QueryParam(name, item)); + } + } else if (collectionFormat.equals("ssv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append(" "); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("tsv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("\t"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("pipes")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("|"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } + + return params; + } + public ApiInvoker() { initConnectionManager(); } @@ -184,21 +241,24 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { HttpClient client = getClient(host); StringBuilder b = new StringBuilder(); - for(String key : queryParams.keySet()) { - String value = queryParams.get(key); - if (value != null){ - if(b.toString().length() == 0) - b.append("?"); - else + b.append("?"); + if (queryParams != null){ + for (QueryParam queryParam : queryParams){ + if (!queryParam.getName().isEmpty()) { + b.append(escapeString(queryParam.getName())); + b.append("="); + b.append(escapeString(queryParam.getValue())); b.append("&"); - b.append(escapeString(key)).append("=").append(escapeString(value)); + } } } - String url = host + path + b.toString(); + + String querystring = b.substring(0, b.length() - 1); + String url = host + path + querystring; HashMap headers = new HashMap(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index ec6218e602c4..58ecbde38c6a 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -23,6 +23,8 @@ import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.List; +import java.util.Set; +import java.util.HashSet; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -132,6 +134,61 @@ public class ApiInvoker { } } + /* + Format to {@code QueryParam} objects. + */ + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } + + if (valueCollection == null) { + params.add(new QueryParam(name, String.valueOf(value))); + return params; + } else if (valueCollection.isEmpty()) { + return params; + } + + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + if (collectionFormat.equals("csv")) { + params.add(new QueryParam(name, parameterToString(value))); + } else if (collectionFormat.equals("multi")) { + for (String item : valueCollection) { + params.add(new QueryParam(name, item)); + } + } else if (collectionFormat.equals("ssv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append(" "); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("tsv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("\t"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("pipes")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("|"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } + + return params; + } + public ApiInvoker() { initConnectionManager(); } @@ -184,21 +241,24 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { HttpClient client = getClient(host); StringBuilder b = new StringBuilder(); - for(String key : queryParams.keySet()) { - String value = queryParams.get(key); - if (value != null){ - if(b.toString().length() == 0) - b.append("?"); - else + b.append("?"); + if (queryParams != null){ + for (QueryParam queryParam : queryParams){ + if (!queryParam.getName().isEmpty()) { + b.append(escapeString(queryParam.getName())); + b.append("="); + b.append(escapeString(queryParam.getValue())); b.append("&"); - b.append(escapeString(key)).append("=").append(escapeString(value)); + } } } - String url = host + path + b.toString(); + + String querystring = b.substring(0, b.length() - 1); + String url = host + path + querystring; HashMap headers = new HashMap(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java new file mode 100644 index 000000000000..240352e890f6 --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java @@ -0,0 +1,38 @@ +package io.swagger.client; + +public class QueryParam { + private String name = ""; + private String value = ""; + + public QueryParam(String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} 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 ebf600d787e1..db10c57f1121 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 @@ -2,6 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiInvoker; +import io.swagger.client.QueryParam; import io.swagger.client.model.*; @@ -52,7 +53,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -106,7 +107,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -160,14 +161,14 @@ public class PetApi { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params Map formParams = new HashMap(); - if (status != null) - queryParams.put("status", ApiInvoker.parameterToString(status)); + + queryParams.addAll(ApiInvoker.parameterToQueryParams("multi", "status", status)); @@ -216,14 +217,14 @@ public class PetApi { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params Map formParams = new HashMap(); - if (tags != null) - queryParams.put("tags", ApiInvoker.parameterToString(tags)); + + queryParams.addAll(ApiInvoker.parameterToQueryParams("multi", "tags", tags)); @@ -277,7 +278,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -338,7 +339,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -408,7 +409,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -416,6 +417,7 @@ public class PetApi { + headerParams.put("api_key", ApiInvoker.parameterToString(apiKey)); @@ -470,7 +472,7 @@ public class PetApi { String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params 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 ecd8e8330490..e8d50c30df74 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 @@ -2,6 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiInvoker; +import io.swagger.client.QueryParam; import io.swagger.client.model.*; @@ -51,7 +52,7 @@ public class StoreApi { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -105,7 +106,7 @@ public class StoreApi { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -164,7 +165,7 @@ public class StoreApi { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -223,7 +224,7 @@ public class StoreApi { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params 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 e1df3fd4f128..d75058749403 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 @@ -2,6 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiInvoker; +import io.swagger.client.QueryParam; import io.swagger.client.model.*; @@ -52,7 +53,7 @@ public class UserApi { String path = "/user".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -106,7 +107,7 @@ public class UserApi { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -160,7 +161,7 @@ public class UserApi { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -215,16 +216,16 @@ public class UserApi { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params Map formParams = new HashMap(); - if (username != null) - queryParams.put("username", ApiInvoker.parameterToString(username)); - if (password != null) - queryParams.put("password", ApiInvoker.parameterToString(password)); + + queryParams.addAll(ApiInvoker.parameterToQueryParams("", "username", username)); + + queryParams.addAll(ApiInvoker.parameterToQueryParams("", "password", password)); @@ -272,7 +273,7 @@ public class UserApi { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -331,7 +332,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -391,7 +392,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -450,7 +451,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 26219b16a458..90a840e6e422 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 0adcbe7031d9..dd14a1c24543 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -22,6 +22,8 @@ import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; +import java.util.Set; +import java.util.HashSet; import java.util.Date; import java.util.TimeZone; @@ -237,6 +239,61 @@ public class ApiClient { } } + /* + Format to {@code QueryParam} objects. + */ + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } + + if (valueCollection == null) { + params.add(new QueryParam(name, String.valueOf(value))); + return params; + } else if (valueCollection.isEmpty()) { + return params; + } + + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + if (collectionFormat.equals("csv")) { + params.add(new QueryParam(name, parameterToString(value))); + } else if (collectionFormat.equals("multi")) { + for (String item : valueCollection) { + params.add(new QueryParam(name, item)); + } + } else if (collectionFormat.equals("ssv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append(" "); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("tsv")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("\t"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } else if (collectionFormat.equals("pipes")) { + StringBuilder sb = new StringBuilder() ; + for (String item : valueCollection) { + sb.append("|"); + sb.append(item); + } + params.add(new QueryParam(name, sb.substring(1))); + } + + return params; + } + /** * Select the Accept header's value from the given accepts array: * if JSON exists in the given array, use it; @@ -340,23 +397,25 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); StringBuilder b = new StringBuilder(); - for(String key : queryParams.keySet()) { - String value = queryParams.get(key); - if (value != null){ - if(b.toString().length() == 0) - b.append("?"); - else + b.append("?"); + if (queryParams != null){ + for (QueryParam queryParam : queryParams){ + if (!queryParam.getName().isEmpty()) { + b.append(escapeString(queryParam.getName())); + b.append("="); + b.append(escapeString(queryParam.getValue())); b.append("&"); - b.append(escapeString(key)).append("=").append(escapeString(value)); + } } } - String querystring = b.toString(); + + String querystring = b.substring(0, b.length() - 1); Builder builder; if (accept == null) @@ -456,7 +515,7 @@ public class ApiClient { * * @param authNames The authentications to apply */ - private void updateParamsForAuth(String[] authNames, Map queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java b/samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java new file mode 100644 index 000000000000..240352e890f6 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java @@ -0,0 +1,38 @@ +package io.swagger.client; + +public class QueryParam { + private String name = ""; + private String value = ""; + + public QueryParam(String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} 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 c102cf00b514..3fc9bd267e4b 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 @@ -3,6 +3,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.QueryParam; import io.swagger.client.model.*; @@ -54,7 +55,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -111,7 +112,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -168,12 +169,12 @@ public class PetApi { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); - if (status != null) - queryParams.put("status", apiClient.parameterToString(status)); + + queryParams.addAll(apiClient.parameterToQueryParams("multi", "status", status)); @@ -227,12 +228,12 @@ public class PetApi { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); - if (tags != null) - queryParams.put("tags", apiClient.parameterToString(tags)); + + queryParams.addAll(apiClient.parameterToQueryParams("multi", "tags", tags)); @@ -292,7 +293,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -322,7 +323,7 @@ public class PetApi { } try { - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); if(response != null){ return (Pet) apiClient.deserialize(response, "", Pet.class); @@ -357,7 +358,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -435,14 +436,14 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); if (apiKey != null) - headerParams.put("api_key", apiClient.parameterToString(apiKey)); + headerParams.put("api_key", apiClient.parameterToString(apiKey)); final String[] accepts = { @@ -502,7 +503,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); 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 727e791c6037..f15b7140a5c0 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 @@ -3,6 +3,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.QueryParam; import io.swagger.client.model.*; @@ -53,7 +54,7 @@ public class StoreApi { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -110,7 +111,7 @@ public class StoreApi { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -173,7 +174,7 @@ public class StoreApi { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -236,7 +237,7 @@ public class StoreApi { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); 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 9e55bbed5909..a0c977c72568 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 @@ -3,6 +3,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; +import io.swagger.client.QueryParam; import io.swagger.client.model.*; @@ -54,7 +55,7 @@ public class UserApi { String path = "/user".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -111,7 +112,7 @@ public class UserApi { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -168,7 +169,7 @@ public class UserApi { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -226,14 +227,14 @@ public class UserApi { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); - if (username != null) - queryParams.put("username", apiClient.parameterToString(username)); - if (password != null) - queryParams.put("password", apiClient.parameterToString(password)); + + queryParams.addAll(apiClient.parameterToQueryParams("", "username", username)); + + queryParams.addAll(apiClient.parameterToQueryParams("", "password", password)); @@ -286,7 +287,7 @@ public class UserApi { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -349,7 +350,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -413,7 +414,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -476,7 +477,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index ce55babb51df..d72432ce2e96 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,9 @@ package io.swagger.client.auth; +import io.swagger.client.QueryParam; + import java.util.Map; +import java.util.Set; public class ApiKeyAuth implements Authentication { private final String location; @@ -39,7 +42,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void applyToParams(Map queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; @@ -47,7 +50,7 @@ public class ApiKeyAuth implements Authentication { value = apiKey; } if (location == "query") { - queryParams.put(paramName, value); + queryParams.add(new QueryParam(paramName, value)); } else if (location == "header") { headerParams.put(paramName, value); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java index 3f372404c8d6..4f661852f343 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,8 +1,11 @@ package io.swagger.client.auth; +import io.swagger.client.QueryParam; + import java.util.Map; +import java.util.Set; public interface Authentication { /** Apply authentication settings to header and query params. */ - void applyToParams(Map queryParams, Map headerParams); + void applyToParams(Set queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 24bff8c2266a..4beaee8b6751 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,9 @@ package io.swagger.client.auth; +import io.swagger.client.QueryParam; + import java.util.Map; +import java.util.Set; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; @@ -26,7 +29,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void applyToParams(Map queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java index d834f4580c25..b754567564fc 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,10 +1,13 @@ package io.swagger.client.auth; +import io.swagger.client.QueryParam; + import java.util.Map; +import java.util.Set; public class OAuth implements Authentication { @Override - public void applyToParams(Map queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index ddd0e1038c08..cf7ace02309c 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java index 0a0bf57da616..e99f310f94ff 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -1,8 +1,11 @@ package io.swagger.client.auth; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; +import io.swagger.client.QueryParam; import org.junit.*; import static org.junit.Assert.*; @@ -10,7 +13,7 @@ import static org.junit.Assert.*; public class ApiKeyAuthTest { @Test public void testApplyToParamsInQuery() { - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); @@ -18,14 +21,17 @@ public class ApiKeyAuthTest { auth.applyToParams(queryParams, headerParams); assertEquals(1, queryParams.size()); - assertEquals("my-api-key", queryParams.get("api_key")); + for (QueryParam queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + // no changes to header parameters assertEquals(0, headerParams.size()); } @Test public void testApplyToParamsInHeaderWithPrefix() { - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java index a621cb60e484..5125abce49bc 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -1,8 +1,11 @@ package io.swagger.client.auth; import java.util.HashMap; +import java.util.HashSet; import java.util.Map; +import java.util.Set; +import io.swagger.client.QueryParam; import org.junit.*; import static org.junit.Assert.*; @@ -17,7 +20,7 @@ public class HttpBasicAuthTest { @Test public void testApplyToParams() { - Map queryParams = new HashMap(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); auth.setUsername("my-username"); From ecddfb7ccf4376b2986c65cab6eca8d7eca206e7 Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Mon, 22 Jun 2015 15:16:45 -0700 Subject: [PATCH 06/62] Renamed QueryParam to Pair class in Java templates. --- .../codegen/languages/JavaClientCodegen.java | 2 +- .../main/resources/Java/ApiClient.mustache | 24 +++++++++---------- .../{QueryParam.mustache => Pair.mustache} | 4 ++-- .../src/main/resources/Java/api.mustache | 4 ++-- .../resources/Java/auth/ApiKeyAuth.mustache | 6 ++--- .../Java/auth/Authentication.mustache | 4 ++-- .../Java/auth/HttpBasicAuth.mustache | 4 ++-- .../main/resources/Java/auth/OAuth.mustache | 4 ++-- .../java/io/swagger/client/ApiClient.java | 24 +++++++++---------- .../client/{QueryParam.java => Pair.java} | 4 ++-- .../java/io/swagger/client/api/PetApi.java | 18 +++++++------- .../java/io/swagger/client/api/StoreApi.java | 10 ++++---- .../java/io/swagger/client/api/UserApi.java | 18 +++++++------- .../io/swagger/client/auth/ApiKeyAuth.java | 6 ++--- .../swagger/client/auth/Authentication.java | 4 ++-- .../io/swagger/client/auth/HttpBasicAuth.java | 4 ++-- .../java/io/swagger/client/auth/OAuth.java | 4 ++-- .../swagger/client/auth/ApiKeyAuthTest.java | 8 +++---- .../client/auth/HttpBasicAuthTest.java | 4 ++-- 19 files changed, 78 insertions(+), 78 deletions(-) rename modules/swagger-codegen/src/main/resources/Java/{QueryParam.mustache => Pair.mustache} (89%) rename samples/client/petstore/java/src/main/java/io/swagger/client/{QueryParam.java => Pair.java} (89%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java index 0f4e8c212ac5..2f31cddec6f2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaClientCodegen.java @@ -116,7 +116,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - supportingFiles.add(new SupportingFile("QueryParam.mustache", invokerFolder, "QueryParam.java")); + supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 59a0ee732818..888f407a4126 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -241,10 +241,10 @@ public class ApiClient { } /* - Format to {@code QueryParam} objects. + Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); // preconditions if (name == null || name.isEmpty() || value == null) return params; @@ -255,7 +255,7 @@ public class ApiClient { } if (valueCollection == null) { - params.add(new QueryParam(name, String.valueOf(value))); + params.add(new Pair(name, String.valueOf(value))); return params; } else if (valueCollection.isEmpty()) { return params; @@ -264,10 +264,10 @@ public class ApiClient { collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv if (collectionFormat.equals("csv")) { - params.add(new QueryParam(name, parameterToString(value))); + params.add(new Pair(name, parameterToString(value))); } else if (collectionFormat.equals("multi")) { for (String item : valueCollection) { - params.add(new QueryParam(name, item)); + params.add(new Pair(name, item)); } } else if (collectionFormat.equals("ssv")) { StringBuilder sb = new StringBuilder() ; @@ -275,21 +275,21 @@ public class ApiClient { sb.append(" "); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("tsv")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("\t"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("pipes")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("|"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } return params; @@ -398,7 +398,7 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -406,7 +406,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ - for (QueryParam queryParam : queryParams){ + for (Pair queryParam : queryParams){ if (!queryParam.getName().isEmpty()) { b.append(escapeString(queryParam.getName())); b.append("="); @@ -516,7 +516,7 @@ public class ApiClient { * * @param authNames The authentications to apply */ - private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); diff --git a/modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache similarity index 89% rename from modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache rename to modules/swagger-codegen/src/main/resources/Java/Pair.mustache index 23b1b26f55cb..9805c74903b2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/QueryParam.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Pair.mustache @@ -1,10 +1,10 @@ package {{invokerPackage}}; -public class QueryParam { +public class Pair { private String name = ""; private String value = ""; - public QueryParam(String name, String value) { + public Pair (String name, String value) { setName(name); setValue(value); } diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 66dc25d66bf3..8d8709da1865 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -3,7 +3,7 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiClient; import {{invokerPackage}}.Configuration; -import {{invokerPackage}}.QueryParam; +import {{invokerPackage}}.Pair; import {{modelPackage}}.*; @@ -62,7 +62,7 @@ public class {{classname}} { .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index 46fa51087b6b..aefbe453efdd 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -1,6 +1,6 @@ package {{invokerPackage}}.auth; -import {{invokerPackage}}.QueryParam; +import {{invokerPackage}}.Pair; import java.util.Map; import java.util.Set; @@ -42,7 +42,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; @@ -50,7 +50,7 @@ public class ApiKeyAuth implements Authentication { value = apiKey; } if (location == "query") { - queryParams.add(new QueryParam(paramName, value)); + queryParams.add(new Pair(paramName, value)); } else if (location == "header") { headerParams.put(paramName, value); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 1f39a402b2c5..9e0b328915c6 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -1,11 +1,11 @@ package {{invokerPackage}}.auth; -import {{invokerPackage}}.QueryParam; +import {{invokerPackage}}.Pair; import java.util.Map; import java.util.Set; public interface Authentication { /** Apply authentication settings to header and query params. */ - void applyToParams(Set queryParams, Map headerParams); + void applyToParams(Set queryParams, Map headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index b5bc993f7c4e..73c52d96ff14 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -1,6 +1,6 @@ package {{invokerPackage}}.auth; -import {{invokerPackage}}.QueryParam; +import {{invokerPackage}}.Pair; import java.util.Map; import java.util.Set; @@ -29,7 +29,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index ab634489edae..4de2fbed9050 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -1,13 +1,13 @@ package {{invokerPackage}}.auth; -import {{invokerPackage}}.QueryParam; +import {{invokerPackage}}.Pair; import java.util.Map; import java.util.Set; public class OAuth implements Authentication { @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index dd14a1c24543..441e5cc1f3c0 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -240,10 +240,10 @@ public class ApiClient { } /* - Format to {@code QueryParam} objects. + Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); // preconditions if (name == null || name.isEmpty() || value == null) return params; @@ -254,7 +254,7 @@ public class ApiClient { } if (valueCollection == null) { - params.add(new QueryParam(name, String.valueOf(value))); + params.add(new Pair(name, String.valueOf(value))); return params; } else if (valueCollection.isEmpty()) { return params; @@ -263,10 +263,10 @@ public class ApiClient { collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv if (collectionFormat.equals("csv")) { - params.add(new QueryParam(name, parameterToString(value))); + params.add(new Pair(name, parameterToString(value))); } else if (collectionFormat.equals("multi")) { for (String item : valueCollection) { - params.add(new QueryParam(name, item)); + params.add(new Pair(name, item)); } } else if (collectionFormat.equals("ssv")) { StringBuilder sb = new StringBuilder() ; @@ -274,21 +274,21 @@ public class ApiClient { sb.append(" "); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("tsv")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("\t"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("pipes")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("|"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } return params; @@ -397,7 +397,7 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -405,7 +405,7 @@ public class ApiClient { StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ - for (QueryParam queryParam : queryParams){ + for (Pair queryParam : queryParams){ if (!queryParam.getName().isEmpty()) { b.append(escapeString(queryParam.getName())); b.append("="); @@ -515,7 +515,7 @@ public class ApiClient { * * @param authNames The authentications to apply */ - private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java similarity index 89% rename from samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java rename to samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java index 240352e890f6..4b7112f6db65 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/QueryParam.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Pair.java @@ -1,10 +1,10 @@ package io.swagger.client; -public class QueryParam { +public class Pair { private String name = ""; private String value = ""; - public QueryParam(String name, String value) { + public Pair (String name, String value) { setName(name); setValue(value); } 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 3fc9bd267e4b..85d87534175e 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 @@ -3,7 +3,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import io.swagger.client.model.*; @@ -55,7 +55,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -112,7 +112,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -169,7 +169,7 @@ public class PetApi { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -228,7 +228,7 @@ public class PetApi { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -293,7 +293,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -358,7 +358,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -436,7 +436,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -503,7 +503,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); 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 f15b7140a5c0..a94a57990c3d 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 @@ -3,7 +3,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import io.swagger.client.model.*; @@ -54,7 +54,7 @@ public class StoreApi { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -111,7 +111,7 @@ public class StoreApi { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -174,7 +174,7 @@ public class StoreApi { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -237,7 +237,7 @@ public class StoreApi { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); 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 a0c977c72568..4a3a69fe3e43 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 @@ -3,7 +3,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiClient; import io.swagger.client.Configuration; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import io.swagger.client.model.*; @@ -55,7 +55,7 @@ public class UserApi { String path = "/user".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -112,7 +112,7 @@ public class UserApi { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -169,7 +169,7 @@ public class UserApi { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -227,7 +227,7 @@ public class UserApi { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -287,7 +287,7 @@ public class UserApi { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -350,7 +350,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -414,7 +414,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -477,7 +477,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index d72432ce2e96..edd98a164141 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -1,6 +1,6 @@ package io.swagger.client.auth; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import java.util.Map; import java.util.Set; @@ -42,7 +42,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; @@ -50,7 +50,7 @@ public class ApiKeyAuth implements Authentication { value = apiKey; } if (location == "query") { - queryParams.add(new QueryParam(paramName, value)); + queryParams.add(new Pair(paramName, value)); } else if (location == "header") { headerParams.put(paramName, value); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java index 4f661852f343..32e61103cd7a 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java @@ -1,11 +1,11 @@ package io.swagger.client.auth; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import java.util.Map; import java.util.Set; public interface Authentication { /** Apply authentication settings to header and query params. */ - void applyToParams(Set queryParams, Map headerParams); + void applyToParams(Set queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 4beaee8b6751..0f2428222acb 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -1,6 +1,6 @@ package io.swagger.client.auth; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import java.util.Map; import java.util.Set; @@ -29,7 +29,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java index b754567564fc..e0b8f942b39c 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,13 +1,13 @@ package io.swagger.client.auth; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import java.util.Map; import java.util.Set; public class OAuth implements Authentication { @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(Set queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java index e99f310f94ff..1f0c150cabbe 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -5,7 +5,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import org.junit.*; import static org.junit.Assert.*; @@ -13,7 +13,7 @@ import static org.junit.Assert.*; public class ApiKeyAuthTest { @Test public void testApplyToParamsInQuery() { - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); @@ -21,7 +21,7 @@ public class ApiKeyAuthTest { auth.applyToParams(queryParams, headerParams); assertEquals(1, queryParams.size()); - for (QueryParam queryParam : queryParams) { + for (Pair queryParam : queryParams) { assertEquals("my-api-key", queryParam.getValue()); } @@ -31,7 +31,7 @@ public class ApiKeyAuthTest { @Test public void testApplyToParamsInHeaderWithPrefix() { - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java index 5125abce49bc..562daa5ba897 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -5,7 +5,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import org.junit.*; import static org.junit.Assert.*; @@ -20,7 +20,7 @@ public class HttpBasicAuthTest { @Test public void testApplyToParams() { - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); Map headerParams = new HashMap(); auth.setUsername("my-username"); From a1b56c9b83757b61db0fbf5b7d824e34b94550cf Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Mon, 22 Jun 2015 15:28:29 -0700 Subject: [PATCH 07/62] Renamed QueryParam to Pair class in Android templates. --- .../languages/AndroidClientCodegen.java | 4 ++-- .../{QueryParam.mustache => Pair.mustache} | 4 ++-- .../main/resources/android-java/api.mustache | 4 ++-- .../android-java/apiInvoker.mustache | 22 +++++++++---------- .../java/io/swagger/client/ApiInvoker.java | 22 +++++++++---------- .../client/{QueryParam.java => Pair.java} | 4 ++-- .../java/io/swagger/client/api/PetApi.java | 18 +++++++-------- .../java/io/swagger/client/api/StoreApi.java | 10 ++++----- .../java/io/swagger/client/api/UserApi.java | 18 +++++++-------- 9 files changed, 53 insertions(+), 53 deletions(-) rename modules/swagger-codegen/src/main/resources/android-java/{QueryParam.mustache => Pair.mustache} (89%) rename samples/client/petstore/android-java/src/main/java/io/swagger/client/{QueryParam.java => Pair.java} (89%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 2d0af4c6c0bb..e65736a63f04 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -232,8 +232,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); supportingFiles.add(new SupportingFile("apiException.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); - supportingFiles.add(new SupportingFile("QueryParam.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "QueryParam.java")); + supportingFiles.add(new SupportingFile("Pair.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "Pair.java")); } public Boolean getUseAndroidMavenGradlePlugin() { diff --git a/modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache b/modules/swagger-codegen/src/main/resources/android-java/Pair.mustache similarity index 89% rename from modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache rename to modules/swagger-codegen/src/main/resources/android-java/Pair.mustache index 23b1b26f55cb..5456028a1a08 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/QueryParam.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/Pair.mustache @@ -1,10 +1,10 @@ package {{invokerPackage}}; -public class QueryParam { +public class Pair { private String name = ""; private String value = ""; - public QueryParam(String name, String value) { + public Pair(String name, String value) { setName(name); setValue(value); } 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 6e34a898ad01..326f4fbac2c6 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -2,7 +2,7 @@ package {{package}}; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.ApiInvoker; -import {{invokerPackage}}.QueryParam; +import {{invokerPackage}}.Pair; import {{modelPackage}}.*; @@ -59,7 +59,7 @@ public class {{classname}} { String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index d7a9d8b357ca..55d85018500e 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -135,10 +135,10 @@ public class ApiInvoker { } /* - Format to {@code QueryParam} objects. + Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); // preconditions if (name == null || name.isEmpty() || value == null) return params; @@ -149,7 +149,7 @@ public class ApiInvoker { } if (valueCollection == null) { - params.add(new QueryParam(name, String.valueOf(value))); + params.add(new Pair(name, String.valueOf(value))); return params; } else if (valueCollection.isEmpty()) { return params; @@ -158,10 +158,10 @@ public class ApiInvoker { collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv if (collectionFormat.equals("csv")) { - params.add(new QueryParam(name, parameterToString(value))); + params.add(new Pair(name, parameterToString(value))); } else if (collectionFormat.equals("multi")) { for (String item : valueCollection) { - params.add(new QueryParam(name, item)); + params.add(new Pair(name, item)); } } else if (collectionFormat.equals("ssv")) { StringBuilder sb = new StringBuilder() ; @@ -169,21 +169,21 @@ public class ApiInvoker { sb.append(" "); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("tsv")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("\t"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("pipes")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("|"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } return params; @@ -241,13 +241,13 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { HttpClient client = getClient(host); StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ - for (QueryParam queryParam : queryParams){ + for (Pair queryParam : queryParams){ if (!queryParam.getName().isEmpty()) { b.append(escapeString(queryParam.getName())); b.append("="); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index 58ecbde38c6a..f148a6fcbb7e 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -135,10 +135,10 @@ public class ApiInvoker { } /* - Format to {@code QueryParam} objects. + Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + Set params = new HashSet(); // preconditions if (name == null || name.isEmpty() || value == null) return params; @@ -149,7 +149,7 @@ public class ApiInvoker { } if (valueCollection == null) { - params.add(new QueryParam(name, String.valueOf(value))); + params.add(new Pair(name, String.valueOf(value))); return params; } else if (valueCollection.isEmpty()) { return params; @@ -158,10 +158,10 @@ public class ApiInvoker { collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv if (collectionFormat.equals("csv")) { - params.add(new QueryParam(name, parameterToString(value))); + params.add(new Pair(name, parameterToString(value))); } else if (collectionFormat.equals("multi")) { for (String item : valueCollection) { - params.add(new QueryParam(name, item)); + params.add(new Pair(name, item)); } } else if (collectionFormat.equals("ssv")) { StringBuilder sb = new StringBuilder() ; @@ -169,21 +169,21 @@ public class ApiInvoker { sb.append(" "); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("tsv")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("\t"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } else if (collectionFormat.equals("pipes")) { StringBuilder sb = new StringBuilder() ; for (String item : valueCollection) { sb.append("|"); sb.append(item); } - params.add(new QueryParam(name, sb.substring(1))); + params.add(new Pair(name, sb.substring(1))); } return params; @@ -241,13 +241,13 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { HttpClient client = getClient(host); StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ - for (QueryParam queryParam : queryParams){ + for (Pair queryParam : queryParams){ if (!queryParam.getName().isEmpty()) { b.append(escapeString(queryParam.getName())); b.append("="); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/Pair.java similarity index 89% rename from samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java rename to samples/client/petstore/android-java/src/main/java/io/swagger/client/Pair.java index 240352e890f6..2710fb5a99be 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/QueryParam.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/Pair.java @@ -1,10 +1,10 @@ package io.swagger.client; -public class QueryParam { +public class Pair { private String name = ""; private String value = ""; - public QueryParam(String name, String value) { + public Pair(String name, String value) { setName(name); setValue(value); } 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 db10c57f1121..7b7929965355 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 @@ -2,7 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiInvoker; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import io.swagger.client.model.*; @@ -53,7 +53,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -107,7 +107,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -161,7 +161,7 @@ public class PetApi { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -217,7 +217,7 @@ public class PetApi { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -278,7 +278,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -339,7 +339,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -409,7 +409,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -472,7 +472,7 @@ public class PetApi { String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params 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 e8d50c30df74..e038962ac6ee 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 @@ -2,7 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiInvoker; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import io.swagger.client.model.*; @@ -52,7 +52,7 @@ public class StoreApi { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -106,7 +106,7 @@ public class StoreApi { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -165,7 +165,7 @@ public class StoreApi { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -224,7 +224,7 @@ public class StoreApi { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params 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 d75058749403..3b74f343299d 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 @@ -2,7 +2,7 @@ package io.swagger.client.api; import io.swagger.client.ApiException; import io.swagger.client.ApiInvoker; -import io.swagger.client.QueryParam; +import io.swagger.client.Pair; import io.swagger.client.model.*; @@ -53,7 +53,7 @@ public class UserApi { String path = "/user".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -107,7 +107,7 @@ public class UserApi { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -161,7 +161,7 @@ public class UserApi { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -216,7 +216,7 @@ public class UserApi { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -273,7 +273,7 @@ public class UserApi { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -332,7 +332,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -392,7 +392,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params @@ -451,7 +451,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + Set queryParams = new HashSet(); // header params Map headerParams = new HashMap(); // form params From 79a5614be9a8fb7928feca37bc8960e6f6dc60dd Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Mon, 22 Jun 2015 15:55:29 -0700 Subject: [PATCH 08/62] Invalid strings will be passed as blank query param. --- .../src/main/resources/Java/ApiClient.mustache | 7 ++++++- .../src/main/resources/android-java/apiInvoker.mustache | 7 ++++++- .../src/main/java/io/swagger/client/ApiInvoker.java | 7 ++++++- .../java/src/main/java/io/swagger/client/ApiClient.java | 7 ++++++- 4 files changed, 24 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 888f407a4126..9392277b52ce 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -247,7 +247,12 @@ public class ApiClient { Set params = new HashSet(); // preconditions - if (name == null || name.isEmpty() || value == null) return params; + if (name == null || name.isEmpty()) return params; + + if (value == null) { + params.add(new Pair(name, value)); + return params; + } Collection valueCollection = null; if (value instanceof Collection) { diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index 55d85018500e..61baf88e8ea9 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -141,7 +141,12 @@ public class ApiInvoker { Set params = new HashSet(); // preconditions - if (name == null || name.isEmpty() || value == null) return params; + if (name == null || name.isEmpty()) return params; + + if (value == null) { + params.add(new Pair(name, value)); + return params; + } Collection valueCollection = null; if (value instanceof Collection) { diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index f148a6fcbb7e..73dc1ddc65b6 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -141,7 +141,12 @@ public class ApiInvoker { Set params = new HashSet(); // preconditions - if (name == null || name.isEmpty() || value == null) return params; + if (name == null || name.isEmpty()) return params; + + if (value == null) { + params.add(new Pair(name, value)); + return params; + } Collection valueCollection = null; if (value instanceof Collection) { diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 441e5cc1f3c0..cd801e0d763d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -246,7 +246,12 @@ public class ApiClient { Set params = new HashSet(); // preconditions - if (name == null || name.isEmpty() || value == null) return params; + if (name == null || name.isEmpty()) return params; + + if (value == null) { + params.add(new Pair(name, value)); + return params; + } Collection valueCollection = null; if (value instanceof Collection) { From 32b50e7c8e0202f9dbefadcee3fdd01ec8fdf516 Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Mon, 22 Jun 2015 17:02:00 -0700 Subject: [PATCH 09/62] Refactored parameterToPairs --- .../main/resources/Java/ApiClient.mustache | 73 ++++++++++--------- .../src/main/resources/Java/api.mustache | 2 +- .../main/resources/android-java/api.mustache | 2 +- .../android-java/apiInvoker.mustache | 73 ++++++++++--------- .../java/io/swagger/client/ApiInvoker.java | 73 ++++++++++--------- .../java/io/swagger/client/api/PetApi.java | 4 +- .../java/io/swagger/client/api/UserApi.java | 4 +- .../java/io/swagger/client/ApiClient.java | 73 ++++++++++--------- .../java/io/swagger/client/api/PetApi.java | 4 +- .../java/io/swagger/client/api/UserApi.java | 4 +- 10 files changed, 158 insertions(+), 154 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 9392277b52ce..bfa33ac07643 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -243,60 +243,61 @@ public class ApiClient { /* Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + public Set parameterToPairs(String collectionFormat, String name, Object value){ Set params = new HashSet(); // preconditions if (name == null || name.isEmpty()) return params; if (value == null) { - params.add(new Pair(name, value)); + params.add(new Pair(name, "")); return params; } - Collection valueCollection = null; + Collection valueCollection = null; if (value instanceof Collection) { - valueCollection = (Collection) value; - } - - if (valueCollection == null) { - params.add(new Pair(name, String.valueOf(value))); - return params; - } else if (valueCollection.isEmpty()) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); return params; } + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - if (collectionFormat.equals("csv")) { - params.add(new Pair(name, parameterToString(value))); - } else if (collectionFormat.equals("multi")) { - for (String item : valueCollection) { - params.add(new Pair(name, item)); + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); } - } else if (collectionFormat.equals("ssv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append(" "); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("tsv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("\t"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("pipes")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("|"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); + + return params; } + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + return params; } diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 8d8709da1865..c279e4d223e8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -67,7 +67,7 @@ public class {{classname}} { Map formParams = new HashMap(); {{#queryParams}} - queryParams.addAll(apiClient.parameterToQueryParams("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + queryParams.addAll(apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{/queryParams}} {{#headerParams}}if ({{paramName}} != null) 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 326f4fbac2c6..5113116deb84 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -66,7 +66,7 @@ public class {{classname}} { Map formParams = new HashMap(); {{#queryParams}} - queryParams.addAll(ApiInvoker.parameterToQueryParams("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + queryParams.addAll(ApiInvoker.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); {{/queryParams}} {{#headerParams}} diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index 61baf88e8ea9..c3bc2cd39c9d 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -137,60 +137,61 @@ public class ApiInvoker { /* Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + public static Set parameterToPairs(String collectionFormat, String name, Object value){ Set params = new HashSet(); // preconditions if (name == null || name.isEmpty()) return params; if (value == null) { - params.add(new Pair(name, value)); + params.add(new Pair(name, "")); return params; } - Collection valueCollection = null; + Collection valueCollection = null; if (value instanceof Collection) { - valueCollection = (Collection) value; - } - - if (valueCollection == null) { - params.add(new Pair(name, String.valueOf(value))); - return params; - } else if (valueCollection.isEmpty()) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); return params; } + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - if (collectionFormat.equals("csv")) { - params.add(new Pair(name, parameterToString(value))); - } else if (collectionFormat.equals("multi")) { - for (String item : valueCollection) { - params.add(new Pair(name, item)); + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); } - } else if (collectionFormat.equals("ssv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append(" "); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("tsv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("\t"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("pipes")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("|"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); + + return params; } + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + return params; } diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index 73dc1ddc65b6..f831a54c14bc 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -137,60 +137,61 @@ public class ApiInvoker { /* Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + public static Set parameterToPairs(String collectionFormat, String name, Object value){ Set params = new HashSet(); // preconditions if (name == null || name.isEmpty()) return params; if (value == null) { - params.add(new Pair(name, value)); + params.add(new Pair(name, "")); return params; } - Collection valueCollection = null; + Collection valueCollection = null; if (value instanceof Collection) { - valueCollection = (Collection) value; - } - - if (valueCollection == null) { - params.add(new Pair(name, String.valueOf(value))); - return params; - } else if (valueCollection.isEmpty()) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); return params; } + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - if (collectionFormat.equals("csv")) { - params.add(new Pair(name, parameterToString(value))); - } else if (collectionFormat.equals("multi")) { - for (String item : valueCollection) { - params.add(new Pair(name, item)); + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); } - } else if (collectionFormat.equals("ssv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append(" "); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("tsv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("\t"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("pipes")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("|"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); + + return params; } + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + return params; } 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 7b7929965355..8580512c7426 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 @@ -168,7 +168,7 @@ public class PetApi { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToQueryParams("multi", "status", status)); + queryParams.addAll(ApiInvoker.parameterToPairs("multi", "status", status)); @@ -224,7 +224,7 @@ public class PetApi { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToQueryParams("multi", "tags", tags)); + queryParams.addAll(ApiInvoker.parameterToPairs("multi", "tags", tags)); 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 3b74f343299d..f8096cb2a87c 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 @@ -223,9 +223,9 @@ public class UserApi { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToQueryParams("", "username", username)); + queryParams.addAll(ApiInvoker.parameterToPairs("", "username", username)); - queryParams.addAll(ApiInvoker.parameterToQueryParams("", "password", password)); + queryParams.addAll(ApiInvoker.parameterToPairs("", "password", password)); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index cd801e0d763d..b0258026896b 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -242,60 +242,61 @@ public class ApiClient { /* Format to {@code Pair} objects. */ - public Set parameterToQueryParams(String collectionFormat, String name, Object value){ + public Set parameterToPairs(String collectionFormat, String name, Object value){ Set params = new HashSet(); // preconditions if (name == null || name.isEmpty()) return params; if (value == null) { - params.add(new Pair(name, value)); + params.add(new Pair(name, "")); return params; } - Collection valueCollection = null; + Collection valueCollection = null; if (value instanceof Collection) { - valueCollection = (Collection) value; - } - - if (valueCollection == null) { - params.add(new Pair(name, String.valueOf(value))); - return params; - } else if (valueCollection.isEmpty()) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); return params; } + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv - if (collectionFormat.equals("csv")) { - params.add(new Pair(name, parameterToString(value))); - } else if (collectionFormat.equals("multi")) { - for (String item : valueCollection) { - params.add(new Pair(name, item)); + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); } - } else if (collectionFormat.equals("ssv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append(" "); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("tsv")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("\t"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); - } else if (collectionFormat.equals("pipes")) { - StringBuilder sb = new StringBuilder() ; - for (String item : valueCollection) { - sb.append("|"); - sb.append(item); - } - params.add(new Pair(name, sb.substring(1))); + + return params; } + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + return params; } 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 85d87534175e..922084ec48f8 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 @@ -174,7 +174,7 @@ public class PetApi { Map formParams = new HashMap(); - queryParams.addAll(apiClient.parameterToQueryParams("multi", "status", status)); + queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -233,7 +233,7 @@ public class PetApi { Map formParams = new HashMap(); - queryParams.addAll(apiClient.parameterToQueryParams("multi", "tags", tags)); + queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); 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 4a3a69fe3e43..a8e2fa37a85a 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 @@ -232,9 +232,9 @@ public class UserApi { Map formParams = new HashMap(); - queryParams.addAll(apiClient.parameterToQueryParams("", "username", username)); + queryParams.addAll(apiClient.parameterToPairs("", "username", username)); - queryParams.addAll(apiClient.parameterToQueryParams("", "password", password)); + queryParams.addAll(apiClient.parameterToPairs("", "password", password)); From 6958db3d3de9fa905be72f3193631ba31e1d74e9 Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Mon, 22 Jun 2015 17:14:18 -0700 Subject: [PATCH 10/62] Refactored Pairs to use List instead of Set. --- .../src/main/resources/Java/ApiClient.mustache | 11 +++++------ .../src/main/resources/Java/api.mustache | 2 +- .../main/resources/Java/auth/ApiKeyAuth.mustache | 4 ++-- .../resources/Java/auth/Authentication.mustache | 4 ++-- .../resources/Java/auth/HttpBasicAuth.mustache | 4 ++-- .../src/main/resources/Java/auth/OAuth.mustache | 4 ++-- .../src/main/resources/android-java/api.mustache | 2 +- .../resources/android-java/apiInvoker.mustache | 9 ++++----- .../main/java/io/swagger/client/ApiInvoker.java | 9 ++++----- .../main/java/io/swagger/client/api/PetApi.java | 16 ++++++++-------- .../java/io/swagger/client/api/StoreApi.java | 8 ++++---- .../main/java/io/swagger/client/api/UserApi.java | 16 ++++++++-------- .../main/java/io/swagger/client/ApiClient.java | 11 +++++------ .../main/java/io/swagger/client/api/PetApi.java | 16 ++++++++-------- .../java/io/swagger/client/api/StoreApi.java | 8 ++++---- .../main/java/io/swagger/client/api/UserApi.java | 16 ++++++++-------- .../java/io/swagger/client/auth/ApiKeyAuth.java | 4 ++-- .../io/swagger/client/auth/Authentication.java | 4 ++-- .../io/swagger/client/auth/HttpBasicAuth.java | 4 ++-- .../main/java/io/swagger/client/auth/OAuth.java | 4 ++-- .../io/swagger/client/auth/ApiKeyAuthTest.java | 8 ++++---- .../swagger/client/auth/HttpBasicAuthTest.java | 6 +++--- 22 files changed, 83 insertions(+), 87 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index bfa33ac07643..d8c48e93b10e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -22,8 +22,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; -import java.util.Set; -import java.util.HashSet; +import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; @@ -243,8 +242,8 @@ public class ApiClient { /* Format to {@code Pair} objects. */ - public Set parameterToPairs(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); // preconditions if (name == null || name.isEmpty()) return params; @@ -404,7 +403,7 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -522,7 +521,7 @@ public class ApiClient { * * @param authNames The authentications to apply */ - private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index c279e4d223e8..afb28293cad7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -62,7 +62,7 @@ public class {{classname}} { .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index aefbe453efdd..a1824b551ca9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -3,7 +3,7 @@ package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; public class ApiKeyAuth implements Authentication { private final String location; @@ -42,7 +42,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 9e0b328915c6..265c74cb76f9 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -3,9 +3,9 @@ package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; public interface Authentication { /** Apply authentication settings to header and query params. */ - void applyToParams(Set queryParams, Map headerParams); + void applyToParams(List queryParams, Map headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index 73c52d96ff14..032ea57d4e89 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -3,7 +3,7 @@ package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; @@ -29,7 +29,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index 4de2fbed9050..66cf2ac8f0f8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -3,11 +3,11 @@ package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; public class OAuth implements Authentication { @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } 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 5113116deb84..9f341301cf00 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -59,7 +59,7 @@ public class {{classname}} { String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index c3bc2cd39c9d..3aeb9b8505de 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -23,8 +23,7 @@ import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.List; -import java.util.Set; -import java.util.HashSet; +import java.util.ArrayList; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -137,8 +136,8 @@ public class ApiInvoker { /* Format to {@code Pair} objects. */ - public static Set parameterToPairs(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public static List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); // preconditions if (name == null || name.isEmpty()) return params; @@ -247,7 +246,7 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { HttpClient client = getClient(host); StringBuilder b = new StringBuilder(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index f831a54c14bc..c55e127cddff 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -23,8 +23,7 @@ import java.util.Collection; import java.util.Map; import java.util.HashMap; import java.util.List; -import java.util.Set; -import java.util.HashSet; +import java.util.ArrayList; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -137,8 +136,8 @@ public class ApiInvoker { /* Format to {@code Pair} objects. */ - public static Set parameterToPairs(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public static List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); // preconditions if (name == null || name.isEmpty()) return params; @@ -247,7 +246,7 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { HttpClient client = getClient(host); StringBuilder b = new StringBuilder(); 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 8580512c7426..21ee69d089be 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 @@ -53,7 +53,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -107,7 +107,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -161,7 +161,7 @@ public class PetApi { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -217,7 +217,7 @@ public class PetApi { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -278,7 +278,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -339,7 +339,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -409,7 +409,7 @@ public class PetApi { String path = "/pet/{petId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -472,7 +472,7 @@ public class PetApi { String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json").replaceAll("\\{" + "petId" + "\\}", apiInvoker.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params 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 e038962ac6ee..49a3ac4aa9a1 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 @@ -52,7 +52,7 @@ public class StoreApi { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -106,7 +106,7 @@ public class StoreApi { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -165,7 +165,7 @@ public class StoreApi { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -224,7 +224,7 @@ public class StoreApi { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "orderId" + "\\}", apiInvoker.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params 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 f8096cb2a87c..a16a745c7f8a 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 @@ -53,7 +53,7 @@ public class UserApi { String path = "/user".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -107,7 +107,7 @@ public class UserApi { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -161,7 +161,7 @@ public class UserApi { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -216,7 +216,7 @@ public class UserApi { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -273,7 +273,7 @@ public class UserApi { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -332,7 +332,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -392,7 +392,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params @@ -451,7 +451,7 @@ public class UserApi { String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); // header params Map headerParams = new HashMap(); // form params diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index b0258026896b..4d50ab3ce849 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -22,8 +22,7 @@ import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; import java.util.List; -import java.util.Set; -import java.util.HashSet; +import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; @@ -242,8 +241,8 @@ public class ApiClient { /* Format to {@code Pair} objects. */ - public Set parameterToPairs(String collectionFormat, String name, Object value){ - Set params = new HashSet(); + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); // preconditions if (name == null || name.isEmpty()) return params; @@ -403,7 +402,7 @@ public class ApiClient { * @param authNames The authentications to apply * @return The response body in type of string */ - public String invokeAPI(String path, String method, Set queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + public String invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -521,7 +520,7 @@ public class ApiClient { * * @param authNames The authentications to apply */ - private void updateParamsForAuth(String[] authNames, Set queryParams, Map headerParams) { + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); 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 922084ec48f8..402fc9da953d 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 @@ -55,7 +55,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -112,7 +112,7 @@ public class PetApi { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -169,7 +169,7 @@ public class PetApi { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -228,7 +228,7 @@ public class PetApi { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -293,7 +293,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -358,7 +358,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -436,7 +436,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -503,7 +503,7 @@ public class PetApi { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); 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 a94a57990c3d..498b6d4a6b89 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 @@ -54,7 +54,7 @@ public class StoreApi { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -111,7 +111,7 @@ public class StoreApi { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -174,7 +174,7 @@ public class StoreApi { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -237,7 +237,7 @@ public class StoreApi { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); 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 a8e2fa37a85a..3bff204ac02b 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 @@ -55,7 +55,7 @@ public class UserApi { String path = "/user".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -112,7 +112,7 @@ public class UserApi { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -169,7 +169,7 @@ public class UserApi { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -227,7 +227,7 @@ public class UserApi { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -287,7 +287,7 @@ public class UserApi { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -350,7 +350,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -414,7 +414,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); @@ -477,7 +477,7 @@ public class UserApi { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index edd98a164141..0e5ca9c7c538 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -3,7 +3,7 @@ package io.swagger.client.auth; import io.swagger.client.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; public class ApiKeyAuth implements Authentication { private final String location; @@ -42,7 +42,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(List queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java index 32e61103cd7a..98b1a6900b93 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java @@ -3,9 +3,9 @@ package io.swagger.client.auth; import io.swagger.client.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; public interface Authentication { /** Apply authentication settings to header and query params. */ - void applyToParams(Set queryParams, Map headerParams); + void applyToParams(List queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 0f2428222acb..980b24311bea 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -3,7 +3,7 @@ package io.swagger.client.auth; import io.swagger.client.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; @@ -29,7 +29,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java index e0b8f942b39c..39fba5498c0e 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java @@ -3,11 +3,11 @@ package io.swagger.client.auth; import io.swagger.client.Pair; import java.util.Map; -import java.util.Set; +import java.util.List; public class OAuth implements Authentication { @Override - public void applyToParams(Set queryParams, Map headerParams) { + public void applyToParams(List queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java index 1f0c150cabbe..5bdb4fb78fba 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -1,9 +1,9 @@ package io.swagger.client.auth; import java.util.HashMap; -import java.util.HashSet; +import java.util.ArrayList; import java.util.Map; -import java.util.Set; +import java.util.List; import io.swagger.client.Pair; import org.junit.*; @@ -13,7 +13,7 @@ import static org.junit.Assert.*; public class ApiKeyAuthTest { @Test public void testApplyToParamsInQuery() { - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); @@ -31,7 +31,7 @@ public class ApiKeyAuthTest { @Test public void testApplyToParamsInHeaderWithPrefix() { - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java index 562daa5ba897..52c5497ba83e 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -1,9 +1,9 @@ package io.swagger.client.auth; import java.util.HashMap; -import java.util.HashSet; +import java.util.ArrayList; import java.util.Map; -import java.util.Set; +import java.util.List; import io.swagger.client.Pair; import org.junit.*; @@ -20,7 +20,7 @@ public class HttpBasicAuthTest { @Test public void testApplyToParams() { - Set queryParams = new HashSet(); + List queryParams = new ArrayList(); Map headerParams = new HashMap(); auth.setUsername("my-username"); From b4d6fd3ba39d02b72d6d5cccc010108bb9bb1f22 Mon Sep 17 00:00:00 2001 From: Raghav sidhanti Date: Mon, 22 Jun 2015 20:16:35 -0700 Subject: [PATCH 11/62] Returning when query param value is null. --- .../src/main/resources/Java/ApiClient.mustache | 7 +------ .../src/main/resources/android-java/apiInvoker.mustache | 7 +------ .../src/main/java/io/swagger/client/ApiInvoker.java | 7 +------ .../src/main/java/io/swagger/client/model/Pet.java | 2 +- .../java/src/main/java/io/swagger/client/ApiClient.java | 7 +------ .../java/src/main/java/io/swagger/client/api/PetApi.java | 2 +- .../java/src/main/java/io/swagger/client/model/Pet.java | 2 +- 7 files changed, 7 insertions(+), 27 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index d8c48e93b10e..e87819e69440 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -246,12 +246,7 @@ public class ApiClient { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty()) return params; - - if (value == null) { - params.add(new Pair(name, "")); - return params; - } + if (name == null || name.isEmpty() || value == null) return params; Collection valueCollection = null; if (value instanceof Collection) { diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index 3aeb9b8505de..5aabd2458e89 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -140,12 +140,7 @@ public class ApiInvoker { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty()) return params; - - if (value == null) { - params.add(new Pair(name, "")); - return params; - } + if (name == null || name.isEmpty() || value == null) return params; Collection valueCollection = null; if (value instanceof Collection) { diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index c55e127cddff..0ccc3713958b 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -140,12 +140,7 @@ public class ApiInvoker { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty()) return params; - - if (value == null) { - params.add(new Pair(name, "")); - return params; - } + if (name == null || name.isEmpty() || value == null) return params; Collection valueCollection = null; if (value instanceof Collection) { diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 90a840e6e422..26219b16a458 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index 4d50ab3ce849..9659ce3ba5fd 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -245,12 +245,7 @@ public class ApiClient { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty()) return params; - - if (value == null) { - params.add(new Pair(name, "")); - return params; - } + if (name == null || name.isEmpty() || value == null) return params; Collection valueCollection = null; if (value instanceof Collection) { 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 402fc9da953d..609fb66af2bc 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 @@ -323,7 +323,7 @@ public class PetApi { } try { - String[] authNames = new String[] { "api_key", "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth", "api_key" }; String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); if(response != null){ return (Pet) apiClient.deserialize(response, "", Pet.class); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java index cf7ace02309c..ddd0e1038c08 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; From 7be35bb02eecb73d8488dc4d16871cd8bbba2707 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Tue, 26 May 2015 10:59:55 +0900 Subject: [PATCH 12/62] Change method name to avoid name collision --- .../src/main/resources/swift/APIs.mustache | 2 +- .../main/resources/swift/Extensions.mustache | 29 ++++++++++++++----- .../src/main/resources/swift/Models.mustache | 2 +- .../src/main/resources/swift/api.mustache | 2 +- .../src/main/resources/swift/model.mustache | 6 ++-- 5 files changed, 27 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index aa39ccfcbdd0..d9fcb84c1254 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -15,7 +15,7 @@ class {{projectName}}API { class APIBase { func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { - let encoded: AnyObject? = encodable?.encode() + let encoded: AnyObject? = encodable?.encodeToJSON() if encoded! is [AnyObject] { var dictionary = [String:AnyObject]() diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index c937db23fe36..a06ebae7026c 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -8,41 +8,41 @@ import Alamofire import PromiseKit extension Bool: JSONEncodable { - func encode() -> AnyObject { return self } + func encodeToJSON() -> AnyObject { return self } } extension Float: JSONEncodable { - func encode() -> AnyObject { return self } + func encodeToJSON() -> AnyObject { return self } } extension Int: JSONEncodable { - func encode() -> AnyObject { return self } + func encodeToJSON() -> AnyObject { return self } } extension Double: JSONEncodable { - func encode() -> AnyObject { return self } + func encodeToJSON() -> AnyObject { return self } } extension String: JSONEncodable { - func encode() -> AnyObject { return self } + func encodeToJSON() -> AnyObject { return self } } private func encodeIfPossible(object: T) -> AnyObject { if object is JSONEncodable { - return (object as! JSONEncodable).encode() + return (object as! JSONEncodable).encodeToJSON() } else { return object as! AnyObject } } extension Array: JSONEncodable { - func encode() -> AnyObject { + func encodeToJSON() -> AnyObject { return self.map(encodeIfPossible) } } extension Dictionary: JSONEncodable { - func encode() -> AnyObject { + func encodeToJSON() -> AnyObject { var dictionary = [NSObject:AnyObject]() for (key, value) in self { dictionary[key as! NSObject] = encodeIfPossible(value) @@ -50,3 +50,16 @@ extension Dictionary: JSONEncodable { return dictionary } } + + +private let dateFormatter: NSDateFormatter = { + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 37c497ddcb9b..587b710326b1 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -7,7 +7,7 @@ import Foundation protocol JSONEncodable { - func encode() -> AnyObject + func encodeToJSON() -> AnyObject } class Response { diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index e24bdae6773c..8c40c3f5be7d 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -35,7 +35,7 @@ extension {{projectName}}API { path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} let url = {{projectName}}API.basePath + path {{#bodyParam}} - let parameters = {{paramName}}{{^required}}?{{/required}}.encode() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} + let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}[:]{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index a964882c97cd..06f10146cf62 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -22,12 +22,12 @@ class {{classname}}: JSONEncodable { {{/vars}} // MARK: JSONEncodable - func encode() -> AnyObject { + func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} nillableDictionary["{{name}}"] = self.{{name}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.rawValue{{/isEnum}}{{^isPrimitiveType}} - nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encode(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} - nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encode(){{/isContainer}}{{/vars}} + nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} + nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encodeToJSON(){{/isContainer}}{{/vars}} let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } From d08acf72984669cd9adfd70ae0e620a9439ec327 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 12:25:46 +0900 Subject: [PATCH 13/62] Add a dateTime formatter candidate --- .../src/main/resources/swift/Models.mustache | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 587b710326b1..31c055b54dc4 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -97,17 +97,24 @@ class Decoders { static private func initialize() { dispatch_once(&once) { - let dateTimeFormatter = NSDateFormatter() - dateTimeFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'" - let dateFormatter = NSDateFormatter() - dateFormatter.dateFormat = "yyyy-MM-dd" + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } // Decoder for NSDate Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in let sourceString = source as! String - if count(sourceString) == 10 { - return dateFormatter.dateFromString(sourceString)! + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } } - return dateTimeFormatter.dateFromString(sourceString)! + fatalError("formatter failed to parse \(sourceString)") } {{#models}}{{#model}} // Decoder for {{{classname}}} From a7c91d610f60c1554edde152b76073c3dc07d251 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 12:26:01 +0900 Subject: [PATCH 14/62] Add error response body to NSError --- .../src/main/resources/swift/AlamofireImplementations.mustache | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 244d816332cd..37edceea13c7 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -45,7 +45,8 @@ class AlamofireRequestBuilder: RequestBuilder { } if res!.statusCode >= 400 { //TODO: Add error entity - let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: [:]) + let userInfo: [NSObject : AnyObject] = (json != nil) ? ["data": json!] : [:] + let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: userInfo) defer.reject(error) return } From 495e528eecd6df3e1cce3322cbc3f4cb0b46e43c Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 12:30:58 +0900 Subject: [PATCH 15/62] Add generated code --- samples/client/petstore/swift/Cartfile | 2 + .../Classes/Swaggers/APIHelper.swift | 21 ++ .../Classes/Swaggers/APIs.swift | 66 +++++ .../Classes/Swaggers/APIs/PetAPI.swift | 225 ++++++++++++++++++ .../Classes/Swaggers/APIs/StoreAPI.swift | 114 +++++++++ .../Classes/Swaggers/APIs/UserAPI.swift | 206 ++++++++++++++++ .../Swaggers/AlamofireImplementations.swift | 80 +++++++ .../Classes/Swaggers/Extensions.swift | 65 +++++ .../Classes/Swaggers/Models.swift | 185 ++++++++++++++ .../Classes/Swaggers/Models/Category.swift | 25 ++ .../Classes/Swaggers/Models/Order.swift | 40 ++++ .../Classes/Swaggers/Models/Pet.swift | 40 ++++ .../Classes/Swaggers/Models/Tag.swift | 25 ++ .../Classes/Swaggers/Models/User.swift | 38 +++ 14 files changed, 1132 insertions(+) create mode 100644 samples/client/petstore/swift/Cartfile create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift create mode 100644 samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift diff --git a/samples/client/petstore/swift/Cartfile b/samples/client/petstore/swift/Cartfile new file mode 100644 index 000000000000..af74617bcf20 --- /dev/null +++ b/samples/client/petstore/swift/Cartfile @@ -0,0 +1,2 @@ +github "Alamofire/Alamofire" >= 1.2 +github "mxcl/PromiseKit" >=1.5.3 diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift new file mode 100644 index 000000000000..418f1c8512b2 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIHelper.swift @@ -0,0 +1,21 @@ +// APIHelper.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +class APIHelper { + static func rejectNil(source: [String:AnyObject?]) -> [String:AnyObject]? { + var destination = [String:AnyObject]() + for (key, nillableValue) in source { + if let value: AnyObject = nillableValue { + destination[key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift new file mode 100644 index 000000000000..75138ff689a0 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -0,0 +1,66 @@ +// APIs.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation +import PromiseKit + +class PetstoreClientAPI { + static let basePath = "http://petstore.swagger.io/v2" + static var credential: NSURLCredential? + static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() +} + +class APIBase { + func toParameters(encodable: JSONEncodable?) -> [String: AnyObject]? { + let encoded: AnyObject? = encodable?.encodeToJSON() + + if encoded! is [AnyObject] { + var dictionary = [String:AnyObject]() + for (index, item) in enumerate(encoded as! [AnyObject]) { + dictionary["\(index)"] = item + } + return dictionary + } else { + return encoded as? [String:AnyObject] + } + } +} + +class RequestBuilder { + var credential: NSURLCredential? + var headers: [String:String] = [:] + let parameters: [String:AnyObject]? + let isBody: Bool + let method: String + let URLString: String + + required init(method: String, URLString: String, parameters: [String:AnyObject]?, isBody: Bool) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.isBody = isBody + } + + func execute() -> Promise> { fatalError("Not implemented") } + + func addHeader(#name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + func addCredential() -> Self { + self.credential = PetstoreClientAPI.credential + return self + } +} + +protocol RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type +} + + diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift new file mode 100644 index 000000000000..48e5f4391594 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -0,0 +1,225 @@ +// +// PetAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +extension PetstoreClientAPI { + + class PetAPI: APIBase { + + /** + + Update an existing pet + + - PUT /pet + - + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@5fd7e9cb] + + :param: body (body) Pet object that needs to be added to the store + + :returns: Promise> + */ + func updatePet(#body: Pet?) -> RequestBuilder { + let path = "/pet" + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "PUT", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Add a new pet to the store + + - POST /pet + - + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@58363f95] + + :param: body (body) Pet object that needs to be added to the store + + :returns: Promise> + */ + func addPet(#body: Pet?) -> RequestBuilder { + let path = "/pet" + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Finds Pets by status + + - GET /pet/findByStatus + - Multiple status values can be provided with comma seperated strings + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@51887c71] + - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + + :param: status (query) Status values that need to be considered for filter + + :returns: Promise> + */ + func findPetsByStatus(#status: [String]?) -> RequestBuilder<[Pet]> { + let path = "/pet/findByStatus" + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "status": status + ] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: false) + } + + /** + + Finds Pets by tags + + - GET /pet/findByTags + - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@4ede45aa] + - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + + :param: tags (query) Tags to filter by + + :returns: Promise> + */ + func findPetsByTags(#tags: [String]?) -> RequestBuilder<[Pet]> { + let path = "/pet/findByTags" + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "tags": tags + ] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: false) + } + + /** + + Find pet by ID + + - GET /pet/{petId} + - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@62afc459, com.wordnik.swagger.codegen.CodegenSecurity@183e1ad] + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@62afc459, com.wordnik.swagger.codegen.CodegenSecurity@183e1ad] + - examples: [{example={\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}, contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + - examples: [{example={\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}, contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + + :param: petId (path) ID of pet that needs to be fetched + + :returns: Promise> + */ + func getPetById(#petId: Int) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Updates a pet in the store with form data + + - POST /pet/{petId} + - + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@795525a1] + + :param: petId (path) ID of pet that needs to be updated + :param: name (form) Updated name of the pet + :param: status (form) Updated status of the pet + + :returns: Promise> + */ + func updatePetWithForm(#petId: String, name: String?, status: String?) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Deletes a pet + + - DELETE /pet/{petId} + - + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@4519ab42] + + :param: petId (path) Pet id to delete + + :returns: Promise> + */ + func deletePet(#petId: Int) -> RequestBuilder { + var path = "/pet/{petId}" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "DELETE", URLString: url, parameters: parameters, isBody: true) + } + + /** + + uploads an image + + - POST /pet/{petId}/uploadImage + - + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@183a9d7f] + + :param: petId (path) ID of pet to update + :param: additionalMetadata (form) Additional data to pass to server + :param: file (form) file to upload + + :returns: Promise> + */ + func uploadFile(#petId: Int, additionalMetadata: String?, file: NSData?) -> RequestBuilder { + var path = "/pet/{petId}/uploadImage" + path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift new file mode 100644 index 000000000000..8ffedbdb39ba --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -0,0 +1,114 @@ +// +// StoreAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +extension PetstoreClientAPI { + + class StoreAPI: APIBase { + + /** + + Returns pet inventories by status + + - GET /store/inventory + - Returns a map of status codes to quantities + - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@303a0946] + - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@2e030ea9, contentType=application/xml}] + - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@2e030ea9, contentType=application/xml}] + + :returns: Promise> + */ + func getInventory() -> RequestBuilder<[String:Int]> { + let path = "/store/inventory" + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder<[String:Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Place an order for a pet + + - POST /store/order + - + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.397+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.400Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.397+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.400Z\n string\n true\n, contentType=application/xml}] + + :param: body (body) order placed for purchasing the pet + + :returns: Promise> + */ + func placeOrder(#body: Order?) -> RequestBuilder { + let path = "/store/order" + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Find purchase order by ID + + - GET /store/order/{orderId} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.402+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.402Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.402+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.402Z\n string\n true\n, contentType=application/xml}] + + :param: orderId (path) ID of pet that needs to be fetched + + :returns: Promise> + */ + func getOrderById(#orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Delete purchase order by ID + + - DELETE /store/order/{orderId} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + :param: orderId (path) ID of the order that needs to be deleted + + :returns: Promise> + */ + func deleteOrder(#orderId: String) -> RequestBuilder { + var path = "/store/order/{orderId}" + path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "DELETE", URLString: url, parameters: parameters, isBody: true) + } + + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift new file mode 100644 index 000000000000..aed405c7bb0a --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -0,0 +1,206 @@ +// +// UserAPI.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +extension PetstoreClientAPI { + + class UserAPI: APIBase { + + /** + + Create user + + - POST /user + - This can only be done by the logged in user. + + :param: body (body) Created user object + + :returns: Promise> + */ + func createUser(#body: User?) -> RequestBuilder { + let path = "/user" + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Creates list of users with given input array + + - POST /user/createWithArray + - + + :param: body (body) List of user object + + :returns: Promise> + */ + func createUsersWithArrayInput(#body: [User]?) -> RequestBuilder { + let path = "/user/createWithArray" + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Creates list of users with given input array + + - POST /user/createWithList + - + + :param: body (body) List of user object + + :returns: Promise> + */ + func createUsersWithListInput(#body: [User]?) -> RequestBuilder { + let path = "/user/createWithList" + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "POST", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Logs user into the system + + - GET /user/login + - + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + - examples: [{example="aeiou", contentType=application/json}, {example=string, contentType=application/xml}] + + :param: username (query) The user name for login + :param: password (query) The password for login in clear text + + :returns: Promise> + */ + func loginUser(#username: String?, password: String?) -> RequestBuilder { + let path = "/user/login" + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [ + "username": username, + "password": password + ] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: false) + } + + /** + + Logs out current logged in user session + + - GET /user/logout + - + + :returns: Promise> + */ + func logoutUser() -> RequestBuilder { + let path = "/user/logout" + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Get user by user name + + - GET /user/{username} + - + - examples: [{example={\n "id" : 123456789,\n "lastName" : "aeiou",\n "phone" : "aeiou",\n "username" : "aeiou",\n "email" : "aeiou",\n "userStatus" : 123,\n "firstName" : "aeiou",\n "password" : "aeiou"\n}, contentType=application/json}, {example=\n 123456\n string\n string\n string\n string\n string\n string\n 0\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "lastName" : "aeiou",\n "phone" : "aeiou",\n "username" : "aeiou",\n "email" : "aeiou",\n "userStatus" : 123,\n "firstName" : "aeiou",\n "password" : "aeiou"\n}, contentType=application/json}, {example=\n 123456\n string\n string\n string\n string\n string\n string\n 0\n, contentType=application/xml}] + + :param: username (path) The name that needs to be fetched. Use user1 for testing. + + :returns: Promise> + */ + func getUserByName(#username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "GET", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Updated user + + - PUT /user/{username} + - This can only be done by the logged in user. + + :param: username (path) name that need to be deleted + :param: body (body) Updated user object + + :returns: Promise> + */ + func updateUser(#username: String, body: User?) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let parameters = body?.encodeToJSON() as? [String:AnyObject] + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "PUT", URLString: url, parameters: parameters, isBody: true) + } + + /** + + Delete user + + - DELETE /user/{username} + - This can only be done by the logged in user. + + :param: username (path) The name that needs to be deleted + + :returns: Promise> + */ + func deleteUser(#username: String) -> RequestBuilder { + var path = "/user/{username}" + path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) + let url = PetstoreClientAPI.basePath + path + + let nillableParameters: [String:AnyObject?] = [:] + let parameters = APIHelper.rejectNil(nillableParameters) + + let requestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return requestBuilder(method: "DELETE", URLString: url, parameters: parameters, isBody: true) + } + + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift new file mode 100644 index 000000000000..37edceea13c7 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -0,0 +1,80 @@ +// AlamofireImplementations.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +class AlamofireRequestBuilderFactory: RequestBuilderFactory { + func getBuilder() -> RequestBuilder.Type { + return AlamofireRequestBuilder.self + } +} + +// Store manager to retain its reference +private var managerStore: [String: Alamofire.Manager] = [:] + +class AlamofireRequestBuilder: RequestBuilder { + required init(method: String, URLString: String, parameters: [String : AnyObject]?, isBody: Bool) { + super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) + } + + override func execute() -> Promise> { + let managerId = NSUUID().UUIDString + // Create a new manager for each request to customize its request header + let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() + configuration.HTTPAdditionalHeaders = buildHeaders() + let manager = Alamofire.Manager(configuration: configuration) + managerStore[managerId] = manager + + let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL + let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + if let credential = self.credential { + request.authenticate(usingCredential: credential) + } + + let defer = Promise>.defer() + request.responseJSON(options: .AllowFragments) { (req, res, json, error) in + managerStore.removeValueForKey(managerId) + + if let error = error { + defer.reject(error) + return + } + if res!.statusCode >= 400 { + //TODO: Add error entity + let userInfo: [NSObject : AnyObject] = (json != nil) ? ["data": json!] : [:] + let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: userInfo) + defer.reject(error) + return + } + + if () is T { + let response = Response(response: res!, body: () as! T) + defer.fulfill(response) + return + } + if let json: AnyObject = json { + let body = Decoders.decode(clazz: T.self, source: json) + let response = Response(response: res!, body: body) + defer.fulfill(response) + return + } + + defer.reject(NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + } + return defer.promise + } + + private func buildHeaders() -> [String: AnyObject] { + var httpHeaders = Manager.defaultHTTPHeaders + for (key, value) in self.headers { + httpHeaders[key] = value + } + return httpHeaders + } +} + + diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift new file mode 100644 index 000000000000..a06ebae7026c --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -0,0 +1,65 @@ +// Extensions.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Alamofire +import PromiseKit + +extension Bool: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Float: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Int: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension Double: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +extension String: JSONEncodable { + func encodeToJSON() -> AnyObject { return self } +} + +private func encodeIfPossible(object: T) -> AnyObject { + if object is JSONEncodable { + return (object as! JSONEncodable).encodeToJSON() + } else { + return object as! AnyObject + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> AnyObject { + return self.map(encodeIfPossible) + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> AnyObject { + var dictionary = [NSObject:AnyObject]() + for (key, value) in self { + dictionary[key as! NSObject] = encodeIfPossible(value) + } + return dictionary + } +} + + +private let dateFormatter: NSDateFormatter = { + let dateFormatter = NSDateFormatter() + dateFormatter.dateFormat = "yyyy-MM-dd" + return dateFormatter +}() + +extension NSDate: JSONEncodable { + func encodeToJSON() -> AnyObject { + return dateFormatter.stringFromDate(self) + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift new file mode 100644 index 000000000000..54e38e75bfe2 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -0,0 +1,185 @@ +// Models.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> AnyObject +} + +class Response { + let statusCode: Int + let header: [String: String] + let body: T + + init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + convenience init(response: NSHTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String:String]() + for (key, value) in rawHeader { + header[key as! String] = value as? String + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} + +private var once = dispatch_once_t() +class Decoders { + static private var decoders = Dictionary AnyObject)>() + + static func addDecoder(#clazz: T.Type, decoder: ((AnyObject) -> T)) { + let key = "\(T.self)" + decoders[key] = { decoder($0) as! AnyObject } + } + + static func decode(#clazz: [T].Type, source: AnyObject) -> [T] { + let array = source as! [AnyObject] + return array.map { Decoders.decode(clazz: T.self, source: $0) } + } + + static func decode(#clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + let sourceDictinoary = source as! [Key: AnyObject] + var dictionary = [Key:T]() + for (key, value) in sourceDictinoary { + dictionary[key] = Decoders.decode(clazz: T.self, source: value) + } + return dictionary + } + + static func decode(#clazz: T.Type, source: AnyObject) -> T { + initialize() + if source is T { + return source as! T + } + + let key = "\(T.self)" + if let decoder = decoders[key] { + return decoder(source) as! T + } else { + fatalError("Source \(source) is not convertible to type \(clazz): Maybe swagger file is insufficient") + } + } + + static func decodeOptional(#clazz: T.Type, source: AnyObject?) -> T? { + if source is NSNull { + return nil + } + return source.map { (source: AnyObject) -> T in + Decoders.decode(clazz: clazz, source: source) + } + } + + static func decodeOptional(#clazz: [T].Type, source: AnyObject?) -> [T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static func decodeOptional(#clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + if source is NSNull { + return nil + } + return source.map { (someSource: AnyObject) -> [Key:T] in + Decoders.decode(clazz: clazz, source: someSource) + } + } + + static private func initialize() { + dispatch_once(&once) { + let formatters = [ + "yyyy-MM-dd", + "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss'Z'" + ].map { (format: String) -> NSDateFormatter in + let formatter = NSDateFormatter() + formatter.dateFormat = format + return formatter + } + // Decoder for NSDate + Decoders.addDecoder(clazz: NSDate.self) { (source: AnyObject) -> NSDate in + let sourceString = source as! String + for formatter in formatters { + if let date = formatter.dateFromString(sourceString) { + return date + } + } + fatalError("formatter failed to parse \(sourceString)") + } + + // Decoder for User + Decoders.addDecoder(clazz: User.self) { (source: AnyObject) -> User in + let sourceDictionary = source as! [NSObject:AnyObject] + var instance = User() + instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) + instance.username = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["username"]) + instance.firstName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["firstName"]) + instance.lastName = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["lastName"]) + instance.email = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["email"]) + instance.password = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["password"]) + instance.phone = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["phone"]) + instance.userStatus = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["userStatus"]) + return instance + } + + + // Decoder for Category + Decoders.addDecoder(clazz: Category.self) { (source: AnyObject) -> Category in + let sourceDictionary = source as! [NSObject:AnyObject] + var instance = Category() + instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for Pet + Decoders.addDecoder(clazz: Pet.self) { (source: AnyObject) -> Pet in + let sourceDictionary = source as! [NSObject:AnyObject] + var instance = Pet() + instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) + instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"]) + instance.name = Decoders.decode(clazz: String.self, source: sourceDictionary["name"]!) + instance.photoUrls = Decoders.decode(clazz: Array.self, source: sourceDictionary["photoUrls"]!) + instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) + instance.status = (sourceDictionary["status"] as? String).map { Pet.Status(rawValue: $0)! } + return instance + } + + + // Decoder for Tag + Decoders.addDecoder(clazz: Tag.self) { (source: AnyObject) -> Tag in + let sourceDictionary = source as! [NSObject:AnyObject] + var instance = Tag() + instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + return instance + } + + + // Decoder for Order + Decoders.addDecoder(clazz: Order.self) { (source: AnyObject) -> Order in + let sourceDictionary = source as! [NSObject:AnyObject] + var instance = Order() + instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) + instance.petId = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["petId"]) + instance.quantity = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["quantity"]) + instance.shipDate = Decoders.decodeOptional(clazz: NSDate.self, source: sourceDictionary["shipDate"]) + instance.status = (sourceDictionary["status"] as? String).map { Order.Status(rawValue: $0)! } + instance.complete = Decoders.decodeOptional(clazz: Bool.self, source: sourceDictionary["complete"]) + return instance + } + + } + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift new file mode 100644 index 000000000000..eab3e7b9e012 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Category.swift @@ -0,0 +1,25 @@ +// +// Category.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +class Category: JSONEncodable { + + var id: Int? + var name: String? + + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift new file mode 100644 index 000000000000..11884502bc1f --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Order.swift @@ -0,0 +1,40 @@ +// +// Order.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +class Order: JSONEncodable { + + enum Status: String { + case Placed = "placed" + case Approved = "approved" + case Delivered = "delivered" + } + + var id: Int? + var petId: Int? + var quantity: Int? + var shipDate: NSDate? + /** Order Status */ + var status: Status? + var complete: Bool? + + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id + nillableDictionary["petId"] = self.petId + nillableDictionary["quantity"] = self.quantity + nillableDictionary["shipDate"] = self.shipDate?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + nillableDictionary["complete"] = self.complete + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift new file mode 100644 index 000000000000..ff66ea2ea433 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -0,0 +1,40 @@ +// +// Pet.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +class Pet: JSONEncodable { + + enum Status: String { + case Available = "available" + case Pending = "pending" + case Sold = "sold" + } + + var id: Int? + var category: Category? + var name: String! + var photoUrls: [String]! + var tags: [Tag]? + /** pet status in the store */ + var status: Status? + + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id + nillableDictionary["category"] = self.category?.encodeToJSON() + nillableDictionary["name"] = self.name + nillableDictionary["photoUrls"] = self.photoUrls.encodeToJSON() + nillableDictionary["tags"] = self.tags?.encodeToJSON() + nillableDictionary["status"] = self.status?.rawValue + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift new file mode 100644 index 000000000000..2951506a0dc6 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Tag.swift @@ -0,0 +1,25 @@ +// +// Tag.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +class Tag: JSONEncodable { + + var id: Int? + var name: String? + + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id + nillableDictionary["name"] = self.name + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift new file mode 100644 index 000000000000..f2461238dc70 --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/User.swift @@ -0,0 +1,38 @@ +// +// User.swift +// +// Generated by swagger-codegen +// https://github.com/swagger-api/swagger-codegen +// + +import Foundation + + +class User: JSONEncodable { + + var id: Int? + var username: String? + var firstName: String? + var lastName: String? + var email: String? + var password: String? + var phone: String? + /** User Status */ + var userStatus: Int? + + + // MARK: JSONEncodable + func encodeToJSON() -> AnyObject { + var nillableDictionary = [String:AnyObject?]() + nillableDictionary["id"] = self.id + nillableDictionary["username"] = self.username + nillableDictionary["firstName"] = self.firstName + nillableDictionary["lastName"] = self.lastName + nillableDictionary["email"] = self.email + nillableDictionary["password"] = self.password + nillableDictionary["phone"] = self.phone + nillableDictionary["userStatus"] = self.userStatus + let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] + return dictionary + } +} From db01ec801f73a5c2caf6f85b6e79ef45f4c26baf Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 13:01:57 +0900 Subject: [PATCH 16/62] Add suppressRequired functionality --- .../codegen/languages/SwiftGenerator.java | 256 ++++++++++++++++++ .../src/main/resources/swift/Models.mustache | 4 +- .../src/main/resources/swift/api.mustache | 4 +- .../src/main/resources/swift/model.mustache | 10 +- 4 files changed, 265 insertions(+), 9 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java new file mode 100644 index 000000000000..697bdefef8fc --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java @@ -0,0 +1,256 @@ +package com.wordnik.swagger.codegen.languages; + +import com.google.common.base.Predicate; +import com.google.common.collect.Iterators; +import com.google.common.collect.Lists; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.Operation; +import com.wordnik.swagger.models.parameters.HeaderParameter; +import com.wordnik.swagger.models.parameters.Parameter; +import com.wordnik.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; + +import javax.annotation.Nullable; +import java.util.*; +import java.io.File; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { + private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + protected String sourceFolder = "Classes/Swaggers"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "swift"; + } + + public String getHelp() { + return "Generates a swift client library."; + } + + public SwiftGenerator() { + super(); + outputFolder = "generated-code/swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + templateDir = "swift"; + apiPackage = "/APIs"; + modelPackage = "/Models"; + + // Inject application name + String appName = System.getProperty("appName"); + if (appName == null) { + appName = "SwaggerClient"; + } + additionalProperties.put("projectName", appName); + + // Inject base url override + String basePathOverride = System.getProperty("basePathOverride"); + if (basePathOverride != null) { + additionalProperties.put("basePathOverride", basePathOverride); + } + + // Make all the variable optional + String suppressRequired = System.getProperty("suppressRequired"); + if (suppressRequired != null) { + additionalProperties.put("suppressRequired", suppressRequired); + } + + sourceFolder = appName + "/" + sourceFolder; + + supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); + supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Int", + "Float", + "Double", + "Bool", + "Void", + "String", + "Character") + ); + defaultIncludes = new HashSet( + Arrays.asList( + "NSDate", + "Array", + "Dictionary", + "Set", + "Any", + "Empty", + "AnyObject") + ); + reservedWords = new HashSet( + Arrays.asList( + "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak") + ); + + typeMapping = new HashMap(); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("date", "NSDate"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); + typeMapping.put("boolean", "Bool"); + typeMapping.put("string", "String"); + typeMapping.put("char", "Character"); + typeMapping.put("short", "Int"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("Integer", "Int"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "Double"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "AnyObject"); + typeMapping.put("file", "NSData"); + + importMapping = new HashMap(); + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; // add an underscore to the name + } + + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "[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 toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toDefaultValue(Property p) { + // nil + return null; + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "[String:" + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "[" + inner + "]"; + } + return null; + } + + @Override + public CodegenProperty fromProperty(String name, Property p) { + CodegenProperty codegenProperty = super.fromProperty(name, p); + if (codegenProperty.isEnum) { + List> swiftEnums = new ArrayList>(); + List values = (List) codegenProperty.allowableValues.get("values"); + for (String value : values) { + Map map = new HashMap(); + map.put("enum", StringUtils.capitalize(value)); + map.put("raw", value); + swiftEnums.add(map); + } + codegenProperty.allowableValues.put("values", swiftEnums); + codegenProperty.datatypeWithEnum = + StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); + } + return codegenProperty; + } + + @Override + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultAPI"; + return initialCaps(name) + "API"; + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + path = normalizePath(path); + List parameters = operation.getParameters(); + parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { + @Override + public boolean apply(@Nullable Parameter parameter) { + return !(parameter instanceof HeaderParameter); + } + })); + operation.setParameters(parameters); + return super.fromOperation(path, httpMethod, operation, definitions); + } + + private static String normalizePath(String path) { + StringBuilder builder = new StringBuilder(); + + int cursor = 0; + Matcher matcher = PATH_PARAM_PATTERN.matcher(path); + boolean found = matcher.find(); + while (found) { + String stringBeforeMatch = path.substring(cursor, matcher.start()); + builder.append(stringBeforeMatch); + + String group = matcher.group().substring(1, matcher.group().length() - 1); + group = camelize(group, true); + builder + .append("{") + .append(group) + .append("}"); + + cursor = matcher.end(); + found = matcher.find(); + } + + String stringAfterMatch = path.substring(cursor); + builder.append(stringAfterMatch); + + return builder.toString(); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 31c055b54dc4..a62c2f2c9b83 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -121,8 +121,8 @@ class Decoders { Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] var instance = {{classname}}(){{#vars}}{{#isEnum}} - instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#required}}!{{/required}} {{/isEnum}}{{^isEnum}} - instance.{{name}} = Decoders.decode{{^required}}Optional{{/required}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#required}}!{{/required}}){{/isEnum}}{{/vars}} + instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{^supressRequired}}{{#required}}!{{/required}}{{/supressRequired}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{#suppressRequired}}Optional{{/suppressRequired}}{{^suppressRequired}}{{^required}}Optional{{/required}}{{/suppressRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{^supressRequired}}{{#required}}!{{/required}}{{/supressRequired}}){{/isEnum}}{{/vars}} return instance }{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 8c40c3f5be7d..abfea5e10fbc 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -30,12 +30,12 @@ extension {{projectName}}API { :returns: Promise> {{description}} */ - func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} let url = {{projectName}}API.basePath + path {{#bodyParam}} - let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} + let parameters = {{paramName}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}[:]{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index 06f10146cf62..6de26a5a1a99 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -17,17 +17,17 @@ class {{classname}}: JSONEncodable { } {{/isEnum}}{{/vars}} {{#vars}}{{#isEnum}}{{#description}}/** {{description}} */ - {{/description}}var {{name}}: {{{datatypeWithEnum}}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ - {{/description}}var {{name}}: {{{datatype}}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} + {{/description}}var {{name}}: {{{datatypeWithEnum}}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/suppressRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ + {{/description}}var {{name}}: {{{datatype}}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/suppressRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} {{/vars}} // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} nillableDictionary["{{name}}"] = self.{{name}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} - nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.rawValue{{/isEnum}}{{^isPrimitiveType}} - nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} - nillableDictionary["{{name}}"] = self.{{name}}{{^required}}?{{/required}}.encodeToJSON(){{/isContainer}}{{/vars}} + nillableDictionary["{{name}}"] = self.{{name}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} + nillableDictionary["{{name}}"] = self.{{name}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} + nillableDictionary["{{name}}"] = self.{{name}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } From c9a9b0ad2b5d3aeb597e37f9d0d020fd306973fb Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 13:02:29 +0900 Subject: [PATCH 17/62] Refine authMethods description --- modules/swagger-codegen/src/main/resources/swift/api.mustache | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index abfea5e10fbc..e458e6d7bca5 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -21,7 +21,9 @@ extension {{projectName}}API { - {{{notes}}}{{/notes}}{{#subresourceOperation}} - subresourceOperation: {{subresourceOperation}}{{/subresourceOperation}}{{#defaultResponse}} - defaultResponse: {{defaultResponse}}{{/defaultResponse}}{{#authMethods}} - - authMethods: {{authMethods}}{{/authMethods}}{{#responseHeaders}} + - {{#isBasic}}BASIC{{/isBasic}}{{#isOAuth}}OAuth{{/isOAuth}}{{#isApiKey}}API Key{{/isApiKey}}: + - type: {{type}}{{#keyParamName}} {{keyParamName}} {{#isKeyInQuery}}(QUERY){{/isKeyInQuery}}{{#isKeyInHeaer}}(HEADER){{/isKeyInHeaer}}{{/keyParamName}} + - name: {{name}}{{/authMethods}}{{#responseHeaders}} - responseHeaders: {{responseHeaders}}{{/responseHeaders}}{{#examples}} - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} From ff88f7175d9cad4f45719dac9670bf8a055f6e43 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 13:08:08 +0900 Subject: [PATCH 18/62] Update models --- .../Classes/Swaggers/APIs/PetAPI.swift | 36 ++++++++++++++----- .../Classes/Swaggers/APIs/StoreAPI.swift | 16 +++++---- 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index 48e5f4391594..efd14dfaaeae 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -18,7 +18,9 @@ extension PetstoreClientAPI { - PUT /pet - - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@5fd7e9cb] + - OAuth: + - type: oauth2 + - name: petstore_auth :param: body (body) Pet object that needs to be added to the store @@ -41,7 +43,9 @@ extension PetstoreClientAPI { - POST /pet - - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@58363f95] + - OAuth: + - type: oauth2 + - name: petstore_auth :param: body (body) Pet object that needs to be added to the store @@ -64,7 +68,9 @@ extension PetstoreClientAPI { - GET /pet/findByStatus - Multiple status values can be provided with comma seperated strings - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@51887c71] + - OAuth: + - type: oauth2 + - name: petstore_auth - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] @@ -92,7 +98,9 @@ extension PetstoreClientAPI { - GET /pet/findByTags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@4ede45aa] + - OAuth: + - type: oauth2 + - name: petstore_auth - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] @@ -120,8 +128,12 @@ extension PetstoreClientAPI { - GET /pet/{petId} - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@62afc459, com.wordnik.swagger.codegen.CodegenSecurity@183e1ad] - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@62afc459, com.wordnik.swagger.codegen.CodegenSecurity@183e1ad] + - API Key: + - type: apiKey api_key + - name: api_key + - OAuth: + - type: oauth2 + - name: petstore_auth - examples: [{example={\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}, contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] - examples: [{example={\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}, contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] @@ -148,7 +160,9 @@ extension PetstoreClientAPI { - POST /pet/{petId} - - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@795525a1] + - OAuth: + - type: oauth2 + - name: petstore_auth :param: petId (path) ID of pet that needs to be updated :param: name (form) Updated name of the pet @@ -175,7 +189,9 @@ extension PetstoreClientAPI { - DELETE /pet/{petId} - - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@4519ab42] + - OAuth: + - type: oauth2 + - name: petstore_auth :param: petId (path) Pet id to delete @@ -200,7 +216,9 @@ extension PetstoreClientAPI { - POST /pet/{petId}/uploadImage - - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@183a9d7f] + - OAuth: + - type: oauth2 + - name: petstore_auth :param: petId (path) ID of pet to update :param: additionalMetadata (form) Additional data to pass to server diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 8ffedbdb39ba..033fe10abeac 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -18,9 +18,11 @@ extension PetstoreClientAPI { - GET /store/inventory - Returns a map of status codes to quantities - - authMethods: [com.wordnik.swagger.codegen.CodegenSecurity@303a0946] - - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@2e030ea9, contentType=application/xml}] - - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@2e030ea9, contentType=application/xml}] + - API Key: + - type: apiKey api_key + - name: api_key + - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@710b8fa2, contentType=application/xml}] + - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@710b8fa2, contentType=application/xml}] :returns: Promise> */ @@ -42,8 +44,8 @@ extension PetstoreClientAPI { - POST /store/order - - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.397+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.400Z\n string\n true\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.397+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.400Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.188+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.190Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.188+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.190Z\n string\n true\n, contentType=application/xml}] :param: body (body) order placed for purchasing the pet @@ -66,8 +68,8 @@ extension PetstoreClientAPI { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.402+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.402Z\n string\n true\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T03:28:27.402+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T12:28:27.402Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.191+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.192Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.191+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.192Z\n string\n true\n, contentType=application/xml}] :param: orderId (path) ID of pet that needs to be fetched From e0109afc60aae68995a21d071191828ce73c59c7 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 13:23:54 +0900 Subject: [PATCH 19/62] Fix typo --- .../src/main/resources/swift/Models.mustache | 4 ++-- .../swagger-codegen/src/main/resources/swift/api.mustache | 4 ++-- .../swagger-codegen/src/main/resources/swift/model.mustache | 6 +++--- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index a62c2f2c9b83..b2f72e483add 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -121,8 +121,8 @@ class Decoders { Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] var instance = {{classname}}(){{#vars}}{{#isEnum}} - instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{^supressRequired}}{{#required}}!{{/required}}{{/supressRequired}} {{/isEnum}}{{^isEnum}} - instance.{{name}} = Decoders.decode{{#suppressRequired}}Optional{{/suppressRequired}}{{^suppressRequired}}{{^required}}Optional{{/required}}{{/suppressRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{^supressRequired}}{{#required}}!{{/required}}{{/supressRequired}}){{/isEnum}}{{/vars}} + instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{^suppressRequired}}{{#required}}!{{/required}}{{/suppressRequired}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{#suppressRequired}}Optional{{/suppressRequired}}{{^suppressRequired}}{{^required}}Optional{{/required}}{{/suppressRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{^suppressRequired}}{{#required}}!{{/required}}{{/suppressRequired}}){{/isEnum}}{{/vars}} return instance }{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index e458e6d7bca5..fc009c63f2af 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -32,12 +32,12 @@ extension {{projectName}}API { :returns: Promise> {{description}} */ - func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} let url = {{projectName}}API.basePath + path {{#bodyParam}} - let parameters = {{paramName}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} + let parameters = {{paramName}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}[:]{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index 6de26a5a1a99..2302a6f44a51 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -25,9 +25,9 @@ class {{classname}}: JSONEncodable { func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} nillableDictionary["{{name}}"] = self.{{name}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} - nillableDictionary["{{name}}"] = self.{{name}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} - nillableDictionary["{{name}}"] = self.{{name}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} - nillableDictionary["{{name}}"] = self.{{name}}{{#supressRequired}}?{{/supressRequired}}{{^supressRequired}}{{^required}}?{{/required}}{{/supressRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} + nillableDictionary["{{name}}"] = self.{{name}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} + nillableDictionary["{{name}}"] = self.{{name}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} + nillableDictionary["{{name}}"] = self.{{name}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } From 9e47042122eab0e3c39cedf3c1800091109c3c44 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Wed, 27 May 2015 13:24:08 +0900 Subject: [PATCH 20/62] Update models --- .../Classes/Swaggers/APIs/PetAPI.swift | 8 ++++---- .../Classes/Swaggers/APIs/StoreAPI.swift | 16 ++++++++-------- .../Classes/Swaggers/APIs/UserAPI.swift | 6 +++--- .../PetstoreClient/Classes/Swaggers/Models.swift | 4 ++-- .../Classes/Swaggers/Models/Pet.swift | 6 +++--- 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index efd14dfaaeae..b136a04f8d2d 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -141,7 +141,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func getPetById(#petId: Int) -> RequestBuilder { + func getPetById(#petId: Int?) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -170,7 +170,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func updatePetWithForm(#petId: String, name: String?, status: String?) -> RequestBuilder { + func updatePetWithForm(#petId: String?, name: String?, status: String?) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -197,7 +197,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func deletePet(#petId: Int) -> RequestBuilder { + func deletePet(#petId: Int?) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -226,7 +226,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func uploadFile(#petId: Int, additionalMetadata: String?, file: NSData?) -> RequestBuilder { + func uploadFile(#petId: Int?, additionalMetadata: String?, file: NSData?) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index 033fe10abeac..ed0c5a87889c 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -21,8 +21,8 @@ extension PetstoreClientAPI { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@710b8fa2, contentType=application/xml}] - - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@710b8fa2, contentType=application/xml}] + - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@5c7e707e, contentType=application/xml}] + - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@5c7e707e, contentType=application/xml}] :returns: Promise> */ @@ -44,8 +44,8 @@ extension PetstoreClientAPI { - POST /store/order - - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.188+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.190Z\n string\n true\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.188+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.190Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.814+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.817Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.814+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.817Z\n string\n true\n, contentType=application/xml}] :param: body (body) order placed for purchasing the pet @@ -68,14 +68,14 @@ extension PetstoreClientAPI { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.191+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.192Z\n string\n true\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:07:45.191+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:07:45.192Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.818+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.818Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.818+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.818Z\n string\n true\n, contentType=application/xml}] :param: orderId (path) ID of pet that needs to be fetched :returns: Promise> */ - func getOrderById(#orderId: String) -> RequestBuilder { + func getOrderById(#orderId: String?) -> RequestBuilder { var path = "/store/order/{orderId}" path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -99,7 +99,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func deleteOrder(#orderId: String) -> RequestBuilder { + func deleteOrder(#orderId: String?) -> RequestBuilder { var path = "/store/order/{orderId}" path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index aed405c7bb0a..812d823459d6 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -141,7 +141,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func getUserByName(#username: String) -> RequestBuilder { + func getUserByName(#username: String?) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -166,7 +166,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func updateUser(#username: String, body: User?) -> RequestBuilder { + func updateUser(#username: String?, body: User?) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -189,7 +189,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func deleteUser(#username: String) -> RequestBuilder { + func deleteUser(#username: String?) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift index 54e38e75bfe2..d8ef5b109c22 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models.swift @@ -149,8 +149,8 @@ class Decoders { var instance = Pet() instance.id = Decoders.decodeOptional(clazz: Int.self, source: sourceDictionary["id"]) instance.category = Decoders.decodeOptional(clazz: Category.self, source: sourceDictionary["category"]) - instance.name = Decoders.decode(clazz: String.self, source: sourceDictionary["name"]!) - instance.photoUrls = Decoders.decode(clazz: Array.self, source: sourceDictionary["photoUrls"]!) + instance.name = Decoders.decodeOptional(clazz: String.self, source: sourceDictionary["name"]) + instance.photoUrls = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["photoUrls"]) instance.tags = Decoders.decodeOptional(clazz: Array.self, source: sourceDictionary["tags"]) instance.status = (sourceDictionary["status"] as? String).map { Pet.Status(rawValue: $0)! } return instance diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift index ff66ea2ea433..0baac38a285e 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Models/Pet.swift @@ -18,8 +18,8 @@ class Pet: JSONEncodable { var id: Int? var category: Category? - var name: String! - var photoUrls: [String]! + var name: String? + var photoUrls: [String]? var tags: [Tag]? /** pet status in the store */ var status: Status? @@ -31,7 +31,7 @@ class Pet: JSONEncodable { nillableDictionary["id"] = self.id nillableDictionary["category"] = self.category?.encodeToJSON() nillableDictionary["name"] = self.name - nillableDictionary["photoUrls"] = self.photoUrls.encodeToJSON() + nillableDictionary["photoUrls"] = self.photoUrls?.encodeToJSON() nillableDictionary["tags"] = self.tags?.encodeToJSON() nillableDictionary["status"] = self.status?.rawValue let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] From 8540ac71c8562959ab1b2cb71d1d50f0e97a2104 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Mon, 22 Jun 2015 19:04:22 +0900 Subject: [PATCH 21/62] Update swift code generation script --- bin/swift-petstore.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh index ce6a7e702f00..4436ed8774d9 100755 --- a/bin/swift-petstore.sh +++ b/bin/swift-petstore.sh @@ -28,4 +28,4 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -o samples/client/petstore/swift" -java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags +java -DsuppressRequired=true -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags From 24465d2df493b501845e191f1b0dca74449b9a94 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Mon, 22 Jun 2015 19:04:45 +0900 Subject: [PATCH 22/62] Change model naming --- .../wordnik/swagger/codegen/languages/SwiftGenerator.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java index 697bdefef8fc..f67834c5540f 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java @@ -127,7 +127,7 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { @Override public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name + return "Swagger" + name; // add an underscore to the name } @Override @@ -202,6 +202,9 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { codegenProperty.allowableValues.put("values", swiftEnums); codegenProperty.datatypeWithEnum = StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); + if (reservedWords.contains(codegenProperty.datatypeWithEnum)) { + codegenProperty.datatypeWithEnum = escapeReservedWord(codegenProperty.datatypeWithEnum); + } } return codegenProperty; } From bcab55e3efc07feeaafb301d681937b873ea07a0 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Mon, 22 Jun 2015 19:05:02 +0900 Subject: [PATCH 23/62] Tighten parameter requirement --- modules/swagger-codegen/src/main/resources/swift/api.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index fc009c63f2af..3caec6018794 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -32,12 +32,12 @@ extension {{projectName}}API { :returns: Promise> {{description}} */ - func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} let url = {{projectName}}API.basePath + path {{#bodyParam}} - let parameters = {{paramName}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} + let parameters = {{paramName}}{{^required}}?{{/required}}.encodeToJSON() as? [String:AnyObject]{{/bodyParam}}{{^bodyParam}} let nillableParameters: [String:AnyObject?] = {{^queryParams}}[:]{{/queryParams}}{{#queryParams}}{{^secondaryParam}}[{{/secondaryParam}} "{{paramName}}": {{paramName}}{{#hasMore}},{{/hasMore}}{{^hasMore}} ]{{/hasMore}}{{/queryParams}} From febaa340e3cadea6f5689589dd7c207cef8bdbd9 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Mon, 22 Jun 2015 19:05:32 +0900 Subject: [PATCH 24/62] Treat object as String (temporary measure) --- .../com/wordnik/swagger/codegen/languages/SwiftGenerator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java index f67834c5540f..4f2bb6fa24b3 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java @@ -119,7 +119,7 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { typeMapping.put("float", "Float"); typeMapping.put("number", "Double"); typeMapping.put("double", "Double"); - typeMapping.put("object", "AnyObject"); + typeMapping.put("object", "String"); typeMapping.put("file", "NSData"); importMapping = new HashMap(); From fa3a9a9d61a880a9dbf8589edf1dd40b81093c69 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Tue, 23 Jun 2015 10:22:05 +0900 Subject: [PATCH 25/62] Change class package --- .../codegen/languages/SwiftGenerator.java | 259 ---------- .../codegen/languages/SwiftGenerator.java | 442 +++++++++--------- 2 files changed, 219 insertions(+), 482 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java deleted file mode 100644 index 4f2bb6fa24b3..000000000000 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/SwiftGenerator.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.wordnik.swagger.codegen.languages; - -import com.google.common.base.Predicate; -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.models.Model; -import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.parameters.HeaderParameter; -import com.wordnik.swagger.models.parameters.Parameter; -import com.wordnik.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; - -import javax.annotation.Nullable; -import java.util.*; -import java.io.File; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { - private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); - protected String sourceFolder = "Classes/Swaggers"; - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "swift"; - } - - public String getHelp() { - return "Generates a swift client library."; - } - - public SwiftGenerator() { - super(); - outputFolder = "generated-code/swift"; - modelTemplateFiles.put("model.mustache", ".swift"); - apiTemplateFiles.put("api.mustache", ".swift"); - templateDir = "swift"; - apiPackage = "/APIs"; - modelPackage = "/Models"; - - // Inject application name - String appName = System.getProperty("appName"); - if (appName == null) { - appName = "SwaggerClient"; - } - additionalProperties.put("projectName", appName); - - // Inject base url override - String basePathOverride = System.getProperty("basePathOverride"); - if (basePathOverride != null) { - additionalProperties.put("basePathOverride", basePathOverride); - } - - // Make all the variable optional - String suppressRequired = System.getProperty("suppressRequired"); - if (suppressRequired != null) { - additionalProperties.put("suppressRequired", suppressRequired); - } - - sourceFolder = appName + "/" + sourceFolder; - - supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); - supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); - supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); - supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); - supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Int", - "Float", - "Double", - "Bool", - "Void", - "String", - "Character") - ); - defaultIncludes = new HashSet( - Arrays.asList( - "NSDate", - "Array", - "Dictionary", - "Set", - "Any", - "Empty", - "AnyObject") - ); - reservedWords = new HashSet( - Arrays.asList( - "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak") - ); - - typeMapping = new HashMap(); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("map", "Dictionary"); - typeMapping.put("date", "NSDate"); - typeMapping.put("Date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); - typeMapping.put("boolean", "Bool"); - typeMapping.put("string", "String"); - typeMapping.put("char", "Character"); - typeMapping.put("short", "Int"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Int"); - typeMapping.put("integer", "Int"); - typeMapping.put("Integer", "Int"); - typeMapping.put("float", "Float"); - typeMapping.put("number", "Double"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "String"); - typeMapping.put("file", "NSData"); - - importMapping = new HashMap(); - } - - @Override - public String escapeReservedWord(String name) { - return "Swagger" + name; // add an underscore to the name - } - - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return "[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 toModelName(type); - } else - type = swaggerType; - return toModelName(type); - } - - @Override - public String toDefaultValue(Property p) { - // nil - return null; - } - - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "[String:" + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "[" + inner + "]"; - } - return null; - } - - @Override - public CodegenProperty fromProperty(String name, Property p) { - CodegenProperty codegenProperty = super.fromProperty(name, p); - if (codegenProperty.isEnum) { - List> swiftEnums = new ArrayList>(); - List values = (List) codegenProperty.allowableValues.get("values"); - for (String value : values) { - Map map = new HashMap(); - map.put("enum", StringUtils.capitalize(value)); - map.put("raw", value); - swiftEnums.add(map); - } - codegenProperty.allowableValues.put("values", swiftEnums); - codegenProperty.datatypeWithEnum = - StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); - if (reservedWords.contains(codegenProperty.datatypeWithEnum)) { - codegenProperty.datatypeWithEnum = escapeReservedWord(codegenProperty.datatypeWithEnum); - } - } - return codegenProperty; - } - - @Override - public String toApiName(String name) { - if(name.length() == 0) - return "DefaultAPI"; - return initialCaps(name) + "API"; - } - - @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - path = normalizePath(path); - List parameters = operation.getParameters(); - parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { - @Override - public boolean apply(@Nullable Parameter parameter) { - return !(parameter instanceof HeaderParameter); - } - })); - operation.setParameters(parameters); - return super.fromOperation(path, httpMethod, operation, definitions); - } - - private static String normalizePath(String path) { - StringBuilder builder = new StringBuilder(); - - int cursor = 0; - Matcher matcher = PATH_PARAM_PATTERN.matcher(path); - boolean found = matcher.find(); - while (found) { - String stringBeforeMatch = path.substring(cursor, matcher.start()); - builder.append(stringBeforeMatch); - - String group = matcher.group().substring(1, matcher.group().length() - 1); - group = camelize(group, true); - builder - .append("{") - .append(group) - .append("}"); - - cursor = matcher.end(); - found = matcher.find(); - } - - String stringAfterMatch = path.substring(cursor); - builder.append(stringAfterMatch); - - return builder.toString(); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java index 2b384f36a7d4..15ca6dc1556f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java @@ -3,12 +3,7 @@ package io.swagger.codegen.languages; import com.google.common.base.Predicate; import com.google.common.collect.Iterators; import com.google.common.collect.Lists; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenProperty; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; +import io.swagger.codegen.*; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.parameters.HeaderParameter; @@ -19,247 +14,248 @@ import io.swagger.models.properties.Property; import org.apache.commons.lang.StringUtils; import javax.annotation.Nullable; +import java.util.*; import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { - private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); - protected String sourceFolder = "Classes/Swaggers"; + private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + protected String sourceFolder = "Classes/Swaggers"; - public SwiftGenerator() { - super(); - outputFolder = "generated-code/swift"; - modelTemplateFiles.put("model.mustache", ".swift"); - apiTemplateFiles.put("api.mustache", ".swift"); - templateDir = "swift"; - apiPackage = "/APIs"; - modelPackage = "/Models"; + public CodegenType getTag() { + return CodegenType.CLIENT; + } - // Inject application name - String appName = System.getProperty("appName"); - if (appName == null) { - appName = "SwaggerClient"; - } - additionalProperties.put("projectName", appName); + public String getName() { + return "swift"; + } - // Inject base url override - String basePathOverride = System.getProperty("basePathOverride"); - if (basePathOverride != null) { - additionalProperties.put("basePathOverride", basePathOverride); - } + public String getHelp() { + return "Generates a swift client library."; + } - sourceFolder = appName + "/" + sourceFolder; + public SwiftGenerator() { + super(); + outputFolder = "generated-code/swift"; + modelTemplateFiles.put("model.mustache", ".swift"); + apiTemplateFiles.put("api.mustache", ".swift"); + templateDir = "swift"; + apiPackage = "/APIs"; + modelPackage = "/Models"; - supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); - supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); - supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); - supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); - supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); + // Inject application name + String appName = System.getProperty("appName"); + if (appName == null) { + appName = "SwaggerClient"; + } + additionalProperties.put("projectName", appName); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "Int", - "Float", - "Double", - "Bool", - "Void", - "String", - "Character") - ); - defaultIncludes = new HashSet( - Arrays.asList( - "NSDate", - "Array", - "Dictionary", - "Set", - "Any", - "Empty", - "AnyObject") - ); - reservedWords = new HashSet( - Arrays.asList( - "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", - "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", - "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", - "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", - "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", - "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", - "required", "right", "set", "Type", "unowned", "weak") - ); - - typeMapping = new HashMap(); - typeMapping.put("array", "Array"); - typeMapping.put("List", "Array"); - typeMapping.put("map", "Dictionary"); - typeMapping.put("date", "NSDate"); - typeMapping.put("Date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); - typeMapping.put("boolean", "Bool"); - typeMapping.put("string", "String"); - typeMapping.put("char", "Character"); - typeMapping.put("short", "Int"); - typeMapping.put("int", "Int"); - typeMapping.put("long", "Int"); - typeMapping.put("integer", "Int"); - typeMapping.put("Integer", "Int"); - typeMapping.put("float", "Float"); - typeMapping.put("number", "Double"); - typeMapping.put("double", "Double"); - typeMapping.put("object", "AnyObject"); - typeMapping.put("file", "NSData"); - - importMapping = new HashMap(); + // Inject base url override + String basePathOverride = System.getProperty("basePathOverride"); + if (basePathOverride != null) { + additionalProperties.put("basePathOverride", basePathOverride); } - private static String normalizePath(String path) { - StringBuilder builder = new StringBuilder(); - - int cursor = 0; - Matcher matcher = PATH_PARAM_PATTERN.matcher(path); - boolean found = matcher.find(); - while (found) { - String stringBeforeMatch = path.substring(cursor, matcher.start()); - builder.append(stringBeforeMatch); - - String group = matcher.group().substring(1, matcher.group().length() - 1); - group = camelize(group, true); - builder - .append("{") - .append(group) - .append("}"); - - cursor = matcher.end(); - found = matcher.find(); - } - - String stringAfterMatch = path.substring(cursor); - builder.append(stringAfterMatch); - - return builder.toString(); + // Make all the variable optional + String suppressRequired = System.getProperty("suppressRequired"); + if (suppressRequired != null) { + additionalProperties.put("suppressRequired", suppressRequired); } - public CodegenType getTag() { - return CodegenType.CLIENT; - } + sourceFolder = appName + "/" + sourceFolder; - public String getName() { - return "swift"; - } + supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); + supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); - public String getHelp() { - return "Generates a swift client library."; - } + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Int", + "Float", + "Double", + "Bool", + "Void", + "String", + "Character") + ); + defaultIncludes = new HashSet( + Arrays.asList( + "NSDate", + "Array", + "Dictionary", + "Set", + "Any", + "Empty", + "AnyObject") + ); + reservedWords = new HashSet( + Arrays.asList( + "class", "break", "as", "associativity", "deinit", "case", "dynamicType", "convenience", "enum", "continue", + "false", "dynamic", "extension", "default", "is", "didSet", "func", "do", "nil", "final", "import", "else", + "self", "get", "init", "fallthrough", "Self", "infix", "internal", "for", "super", "inout", "let", "if", + "true", "lazy", "operator", "in", "COLUMN", "left", "private", "return", "FILE", "mutating", "protocol", + "switch", "FUNCTION", "none", "public", "where", "LINE", "nonmutating", "static", "while", "optional", + "struct", "override", "subscript", "postfix", "typealias", "precedence", "var", "prefix", "Protocol", + "required", "right", "set", "Type", "unowned", "weak") + ); - @Override - public String escapeReservedWord(String name) { - return "_" + name; // add an underscore to the name - } + typeMapping = new HashMap(); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("date", "NSDate"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); + typeMapping.put("boolean", "Bool"); + typeMapping.put("string", "String"); + typeMapping.put("char", "Character"); + typeMapping.put("short", "Int"); + typeMapping.put("int", "Int"); + typeMapping.put("long", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("Integer", "Int"); + typeMapping.put("float", "Float"); + typeMapping.put("number", "Double"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "String"); + typeMapping.put("file", "NSData"); - @Override - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); - } + importMapping = new HashMap(); + } - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); - } + @Override + public String escapeReservedWord(String name) { + return "Swagger" + name; // add an underscore to the name + } - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - return "[String:" + getTypeDeclaration(inner) + "]"; - } - return super.getTypeDeclaration(p); - } + @Override + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); + } - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return "[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 toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toDefaultValue(Property p) { + // nil + return null; + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "[String:" + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "[" + inner + "]"; + } + return null; + } + + @Override + public CodegenProperty fromProperty(String name, Property p) { + CodegenProperty codegenProperty = super.fromProperty(name, p); + if (codegenProperty.isEnum) { + List> swiftEnums = new ArrayList>(); + List values = (List) codegenProperty.allowableValues.get("values"); + for (String value : values) { + Map map = new HashMap(); + map.put("enum", StringUtils.capitalize(value)); + map.put("raw", value); + swiftEnums.add(map); + } + codegenProperty.allowableValues.put("values", swiftEnums); + codegenProperty.datatypeWithEnum = + StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); + if (reservedWords.contains(codegenProperty.datatypeWithEnum)) { + codegenProperty.datatypeWithEnum = escapeReservedWord(codegenProperty.datatypeWithEnum); + } + } + return codegenProperty; + } + + @Override + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultAPI"; + return initialCaps(name) + "API"; + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + path = normalizePath(path); + List parameters = operation.getParameters(); + parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { + @Override + public boolean apply(@Nullable Parameter parameter) { + return !(parameter instanceof HeaderParameter); + } + })); + operation.setParameters(parameters); + return super.fromOperation(path, httpMethod, operation, definitions); + } + + private static String normalizePath(String path) { + StringBuilder builder = new StringBuilder(); + + int cursor = 0; + Matcher matcher = PATH_PARAM_PATTERN.matcher(path); + boolean found = matcher.find(); + while (found) { + String stringBeforeMatch = path.substring(cursor, matcher.start()); + builder.append(stringBeforeMatch); + + String group = matcher.group().substring(1, matcher.group().length() - 1); + group = camelize(group, true); + builder + .append("{") + .append(group) + .append("}"); + + cursor = matcher.end(); + found = matcher.find(); } - @Override - public String toDefaultValue(Property p) { - // nil - return null; - } + String stringAfterMatch = path.substring(cursor); + builder.append(stringAfterMatch); - @Override - public String toInstantiationType(Property p) { - if (p instanceof MapProperty) { - MapProperty ap = (MapProperty) p; - String inner = getSwaggerType(ap.getAdditionalProperties()); - return "[String:" + inner + "]"; - } else if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - String inner = getSwaggerType(ap.getItems()); - return "[" + inner + "]"; - } - return null; - } - - @Override - public CodegenProperty fromProperty(String name, Property p) { - CodegenProperty codegenProperty = super.fromProperty(name, p); - if (codegenProperty.isEnum) { - List> swiftEnums = new ArrayList>(); - List values = (List) codegenProperty.allowableValues.get("values"); - for (String value : values) { - Map map = new HashMap(); - map.put("enum", StringUtils.capitalize(value)); - map.put("raw", value); - swiftEnums.add(map); - } - codegenProperty.allowableValues.put("values", swiftEnums); - codegenProperty.datatypeWithEnum = - StringUtils.left(codegenProperty.datatypeWithEnum, codegenProperty.datatypeWithEnum.length() - "Enum".length()); - } - return codegenProperty; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultAPI"; - } - return initialCaps(name) + "API"; - } - - @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - path = normalizePath(path); - List parameters = operation.getParameters(); - parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { - @Override - public boolean apply(@Nullable Parameter parameter) { - return !(parameter instanceof HeaderParameter); - } - })); - operation.setParameters(parameters); - return super.fromOperation(path, httpMethod, operation, definitions); - } + return builder.toString(); + } } \ No newline at end of file From 79e31a5761860edaa860b2f359340d2032ac35e3 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Tue, 23 Jun 2015 11:59:49 +0900 Subject: [PATCH 26/62] Add a workaround against void forcibly being converted to string --- .../main/resources/swift/AlamofireImplementations.mustache | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 37edceea13c7..edc7a51a1691 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -61,6 +61,12 @@ class AlamofireRequestBuilder: RequestBuilder { let response = Response(response: res!, body: body) defer.fulfill(response) return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + let response = Response(response: res!, body: "" as! T) + defer.fulfill(response) + return } defer.reject(NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) From aec4af1b8824cdb8b63d65760fd5dd87b86f1732 Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Tue, 23 Jun 2015 16:10:21 +0900 Subject: [PATCH 27/62] Replace slash with File.separator --- .../swagger/codegen/languages/SwiftGenerator.java | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java index 15ca6dc1556f..96f0666df52c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java @@ -21,7 +21,7 @@ import java.util.regex.Pattern; public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); - protected String sourceFolder = "Classes/Swaggers"; + protected String sourceFolder = "Classes" + File.separator + "Swaggers"; public CodegenType getTag() { return CodegenType.CLIENT; @@ -37,12 +37,12 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { public SwiftGenerator() { super(); - outputFolder = "generated-code/swift"; + outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); apiTemplateFiles.put("api.mustache", ".swift"); templateDir = "swift"; - apiPackage = "/APIs"; - modelPackage = "/Models"; + apiPackage = File.separator + "APIs"; + modelPackage = File.separator + "Models"; // Inject application name String appName = System.getProperty("appName"); @@ -63,7 +63,7 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { additionalProperties.put("suppressRequired", suppressRequired); } - sourceFolder = appName + "/" + sourceFolder; + sourceFolder = appName + File.separator + sourceFolder; supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); @@ -134,12 +134,12 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { @Override public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + modelPackage().replace('.', File.separatorChar); } @Override public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + apiPackage().replace('.', File.separatorChar); } @Override From 644231b91518e428410f5033cac66a07e3902e5e Mon Sep 17 00:00:00 2001 From: Julian Bez Date: Wed, 24 Jun 2015 16:32:49 +0200 Subject: [PATCH 28/62] Change optional to required --- modules/swagger-codegen/src/main/resources/php/api.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 3ed7f18c5795..394460ce46f9 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -67,10 +67,10 @@ class {{classname}} { * * {{{summary}}} * -{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} +{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - public function {{nickname}}({{#allParams}}${{paramName}}{{#optional}}=null{{/optional}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + public function {{nickname}}({{#allParams}}${{paramName}}{{#required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { From 8ce3823698f3c0fd797983082c0da438c3c8caca Mon Sep 17 00:00:00 2001 From: Julian Bez Date: Wed, 24 Jun 2015 16:34:32 +0200 Subject: [PATCH 29/62] Change to not required --- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 394460ce46f9..0eb1b0cd54ad 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -70,7 +70,7 @@ class {{classname}} { {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - public function {{nickname}}({{#allParams}}${{paramName}}{{#required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + public function {{nickname}}({{#allParams}}${{paramName}}{{^required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { From 1af23fb75124705456c877f617200bd9e656a7d3 Mon Sep 17 00:00:00 2001 From: Raghav Sidhanti Date: Wed, 24 Jun 2015 11:55:03 -0700 Subject: [PATCH 30/62] Unit tests for Android and Java parameterToPairs method --- .../io/swagger/client/ApiInvokerTest.java | 91 +++++++++++++++++++ .../java/io/swagger/client/ApiClientTest.java | 83 ++++++++++++++++- 2 files changed, 173 insertions(+), 1 deletion(-) create mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/client/ApiInvokerTest.java diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/client/ApiInvokerTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/client/ApiInvokerTest.java new file mode 100644 index 000000000000..3e4b114012c0 --- /dev/null +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/client/ApiInvokerTest.java @@ -0,0 +1,91 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + +import java.util.*; + + +public class ApiInvokerTest { + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = ApiInvoker.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = ApiInvoker.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = ApiInvoker.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = ApiInvoker.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = ApiInvoker.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = ApiInvoker.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = ApiInvoker.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = ApiInvoker.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java index 8a560d2d7bcb..802c0cae3b97 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java @@ -2,7 +2,7 @@ package io.swagger.client; import io.swagger.client.auth.*; -import java.util.Map; +import java.util.*; import org.junit.*; import static org.junit.Assert.*; @@ -109,4 +109,85 @@ public class ApiClientTest { auth.setApiKey(null); auth.setApiKeyPrefix(null); } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } } From f3a0f464f792e04694c606c9303f813101471752 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 25 Jun 2015 15:35:48 +0800 Subject: [PATCH 31/62] Support file downloading in Ruby generator --- .../codegen/languages/RubyClientCodegen.java | 1 + .../resources/ruby/swagger/response.mustache | 23 ++++++++++++++++++- .../ruby/lib/swagger_client/api/pet_api.rb | 2 +- .../lib/swagger_client/swagger/response.rb | 23 ++++++++++++++++++- 4 files changed, 46 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java index c3c787106827..3e1929b7485e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RubyClientCodegen.java @@ -61,6 +61,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "Array"); typeMapping.put("map", "Hash"); typeMapping.put("object", "Object"); + typeMapping.put("file", "File"); // remove modelPackage and apiPackage added by default cliOptions.clear(); 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 b621110935a9..14e276ddf5de 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -3,6 +3,7 @@ module {{moduleName}} class Response require 'json' require 'date' + require 'tempfile' attr_accessor :raw @@ -31,8 +32,11 @@ module {{moduleName}} def deserialize(return_type) return nil if body.blank? + # handle file downloading - save response body into a tmp file and return the File instance + return download_file if return_type == 'File' + # ensuring a default content type - content_type = raw.headers_hash['Content-Type'] || 'application/json' + content_type = raw.headers['Content-Type'] || 'application/json' unless content_type.start_with?('application/json') fail "Content-Type is not supported: #{content_type}" @@ -82,6 +86,23 @@ module {{moduleName}} end end + # Save response body into a file in tmp folder, using the filename from the + # "Content-Disposition" header if provided, otherwise a random filename. + def download_file + tmp_file = Tempfile.new '' + content_disposition = raw.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename="([^"]+)"/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + File.open(path, 'w') { |file| file.write(raw.body) } + return File.new(path) + end + # `headers_hash` is a Typhoeus-specific extension of Hash, # so simplify it back into a regular old Hash. def headers 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 4a421faef86a..f20f89bc5847 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 @@ -286,7 +286,7 @@ module SwaggerClient # @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 + # @option opts [File] :file file to upload # @return [nil] def self.upload_file(pet_id, opts = {}) 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 f560006de6d7..e9c8e3805a08 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -3,6 +3,7 @@ module SwaggerClient class Response require 'json' require 'date' + require 'tempfile' attr_accessor :raw @@ -31,8 +32,11 @@ module SwaggerClient def deserialize(return_type) return nil if body.blank? + # handle file downloading - save response body into a tmp file and return the File instance + return download_file if return_type == 'File' + # ensuring a default content type - content_type = raw.headers_hash['Content-Type'] || 'application/json' + content_type = raw.headers['Content-Type'] || 'application/json' unless content_type.start_with?('application/json') fail "Content-Type is not supported: #{content_type}" @@ -82,6 +86,23 @@ module SwaggerClient end end + # Save response body into a file in tmp folder, using the filename from the + # "Content-Disposition" header if provided, otherwise a random filename. + def download_file + tmp_file = Tempfile.new '' + content_disposition = raw.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename="([^"]+)"/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + File.open(path, 'w') { |file| file.write(raw.body) } + return File.new(path) + end + # `headers_hash` is a Typhoeus-specific extension of Hash, # so simplify it back into a regular old Hash. def headers From ceafbcc97f36e31b4986a38ca10aaac4edd0405d Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 25 Jun 2015 16:07:02 +0800 Subject: [PATCH 32/62] Add config option for file downloading folder. Log about file downloading --- .../resources/ruby/swagger/configuration.mustache | 7 +++++++ .../src/main/resources/ruby/swagger/response.mustache | 11 ++++++++--- .../src/main/resources/ruby/swagger_client.mustache | 3 ++- samples/client/petstore/ruby/lib/swagger_client.rb | 3 ++- .../ruby/lib/swagger_client/swagger/configuration.rb | 7 +++++++ .../ruby/lib/swagger_client/swagger/response.rb | 11 ++++++++--- 6 files changed, 34 insertions(+), 8 deletions(-) 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 e9a8af9c1628..9400bdce6b71 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -3,6 +3,13 @@ module {{moduleName}} class Configuration attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + # Defaults go in here.. def initialize @format = 'json' 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 14e276ddf5de..076f93e104f4 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -86,10 +86,13 @@ module {{moduleName}} end end - # Save response body into a file in tmp folder, using the filename from the - # "Content-Disposition" header if provided, otherwise a random filename. + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded def download_file - tmp_file = Tempfile.new '' + tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path content_disposition = raw.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename="([^"]+)"/, 1] @@ -99,7 +102,9 @@ module {{moduleName}} end # close and delete temp file tmp_file.close! + File.open(path, 'w') { |file| file.write(raw.body) } + Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" return File.new(path) end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache index 0be00aaec953..5bf57a642dd1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -22,5 +22,6 @@ require '{{importPath}}' module {{moduleName}} # Initialize the default configuration - Swagger.configuration ||= Swagger::Configuration.new + Swagger.configuration = Swagger::Configuration.new + Swagger.configure { |config| } end diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb index 42380927f824..eff88be2ebdc 100644 --- a/samples/client/petstore/ruby/lib/swagger_client.rb +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -22,5 +22,6 @@ require 'swagger_client/api/store_api' module SwaggerClient # Initialize the default configuration - Swagger.configuration ||= Swagger::Configuration.new + Swagger.configuration = Swagger::Configuration.new + Swagger.configure { |config| } end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb index a2d4fe0e2918..0b7836d989c5 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb @@ -3,6 +3,13 @@ module SwaggerClient class Configuration attr_accessor :format, :api_key, :api_key_prefix, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent, :verify_ssl + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + # Defaults go in here.. def initialize @format = 'json' 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 e9c8e3805a08..adabfa213971 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -86,10 +86,13 @@ module SwaggerClient end end - # Save response body into a file in tmp folder, using the filename from the - # "Content-Disposition" header if provided, otherwise a random filename. + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded def download_file - tmp_file = Tempfile.new '' + tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path content_disposition = raw.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename="([^"]+)"/, 1] @@ -99,7 +102,9 @@ module SwaggerClient end # close and delete temp file tmp_file.close! + File.open(path, 'w') { |file| file.write(raw.body) } + Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" return File.new(path) end From e6e1db206407ee4cba3cd00e3414846d3c771c9c Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 25 Jun 2015 16:26:04 +0800 Subject: [PATCH 33/62] Support looser format when detecting filename --- .../src/main/resources/ruby/swagger/response.mustache | 2 +- .../client/petstore/ruby/lib/swagger_client/swagger/response.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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 076f93e104f4..6e898255b87a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -95,7 +95,7 @@ module {{moduleName}} tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path content_disposition = raw.headers['Content-Disposition'] if content_disposition - filename = content_disposition[/filename="([^"]+)"/, 1] + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] path = File.join File.dirname(tmp_file), filename else path = tmp_file.path 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 adabfa213971..045d200d2053 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -95,7 +95,7 @@ module SwaggerClient tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path content_disposition = raw.headers['Content-Disposition'] if content_disposition - filename = content_disposition[/filename="([^"]+)"/, 1] + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] path = File.join File.dirname(tmp_file), filename else path = tmp_file.path From 8cce7ac053aa6956ffbf75a183189c644bd6430d Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 25 Jun 2015 22:40:14 +0800 Subject: [PATCH 34/62] fix optional for python, python3 --- .../src/main/resources/python/api.mustache | 2 +- .../src/main/resources/python3/api.mustache | 2 +- .../SwaggerPetstore/apis/pet_api.py | 18 +++++++++--------- .../SwaggerPetstore/apis/store_api.py | 2 +- .../SwaggerPetstore/apis/user_api.py | 12 ++++++------ .../client/petstore/python3/client/pet_api.py | 18 +++++++++--------- .../petstore/python3/client/store_api.py | 2 +- .../client/petstore/python3/client/user_api.py | 12 ++++++------ 8 files changed, 34 insertions(+), 34 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 867014d5e128..3fb62cb75eab 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -47,7 +47,7 @@ class {{classname}}(object): {{{summary}}} {{{notes}}} - {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} + {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} """ diff --git a/modules/swagger-codegen/src/main/resources/python3/api.mustache b/modules/swagger-codegen/src/main/resources/python3/api.mustache index 015158bccec7..2ff659b11b50 100644 --- a/modules/swagger-codegen/src/main/resources/python3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/api.mustache @@ -36,7 +36,7 @@ class {{classname}}(object): {{{notes}}} Args: - {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}} Returns: {{returnType}} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index 5f5c2fe81fa3..7f022930869a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -46,7 +46,7 @@ class PetApi(object): Update an existing pet - :param Pet body: Pet object that needs to be added to the store + :param Pet body: Pet object that needs to be added to the store (optional) :return: None """ @@ -97,7 +97,7 @@ class PetApi(object): Add a new pet to the store - :param Pet body: Pet object that needs to be added to the store + :param Pet body: Pet object that needs to be added to the store (optional) :return: None """ @@ -148,7 +148,7 @@ class PetApi(object): Finds Pets by status Multiple status values can be provided with comma seperated strings - :param list[str] status: Status values that need to be considered for filter + :param list[str] status: Status values that need to be considered for filter (optional) :return: list[Pet] """ @@ -201,7 +201,7 @@ class PetApi(object): Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - :param list[str] tags: Tags to filter by + :param list[str] tags: Tags to filter by (optional) :return: list[Pet] """ @@ -312,8 +312,8 @@ class PetApi(object): :param str pet_id: ID of pet that needs to be updated (required) - :param str name: Updated name of the pet - :param str status: Updated status of the pet + :param str name: Updated name of the pet (optional) + :param str status: Updated status of the pet (optional) :return: None """ @@ -374,7 +374,7 @@ class PetApi(object): Deletes a pet - :param str api_key: + :param str api_key: (optional) :param int pet_id: Pet id to delete (required) :return: None @@ -434,8 +434,8 @@ class PetApi(object): :param int pet_id: ID of pet to update (required) - :param str additional_metadata: Additional data to pass to server - :param File file: file to upload + :param str additional_metadata: Additional data to pass to server (optional) + :param File file: file to upload (optional) :return: None """ diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index 1e024cfbb5b8..f017df791d9a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -95,7 +95,7 @@ class StoreApi(object): Place an order for a pet - :param Order body: order placed for purchasing the pet + :param Order body: order placed for purchasing the pet (optional) :return: Order """ diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 84a40b06579e..177c5e3a565f 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -46,7 +46,7 @@ class UserApi(object): Create user This can only be done by the logged in user. - :param User body: Created user object + :param User body: Created user object (optional) :return: None """ @@ -97,7 +97,7 @@ class UserApi(object): Creates list of users with given input array - :param list[User] body: List of user object + :param list[User] body: List of user object (optional) :return: None """ @@ -148,7 +148,7 @@ class UserApi(object): Creates list of users with given input array - :param list[User] body: List of user object + :param list[User] body: List of user object (optional) :return: None """ @@ -199,8 +199,8 @@ class UserApi(object): Logs user into the system - :param str username: The user name for login - :param str password: The password for login in clear text + :param str username: The user name for login (optional) + :param str password: The password for login in clear text (optional) :return: str """ @@ -361,7 +361,7 @@ class UserApi(object): This can only be done by the logged in user. :param str username: name that need to be deleted (required) - :param User body: Updated user object + :param User body: Updated user object (optional) :return: None """ diff --git a/samples/client/petstore/python3/client/pet_api.py b/samples/client/petstore/python3/client/pet_api.py index 9293a89d2b04..cebab131778f 100644 --- a/samples/client/petstore/python3/client/pet_api.py +++ b/samples/client/petstore/python3/client/pet_api.py @@ -35,7 +35,7 @@ class PetApi(object): Args: - body, Pet: Pet object that needs to be added to the store (required) + body, Pet: Pet object that needs to be added to the store (optional) Returns: @@ -77,7 +77,7 @@ class PetApi(object): Args: - body, Pet: Pet object that needs to be added to the store (required) + body, Pet: Pet object that needs to be added to the store (optional) Returns: @@ -119,7 +119,7 @@ class PetApi(object): Multiple status values can be provided with comma seperated strings Args: - status, list[str]: Status values that need to be considered for filter (required) + status, list[str]: Status values that need to be considered for filter (optional) Returns: list[Pet] @@ -170,7 +170,7 @@ class PetApi(object): Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. Args: - tags, list[str]: Tags to filter by (required) + tags, list[str]: Tags to filter by (optional) Returns: list[Pet] @@ -275,8 +275,8 @@ class PetApi(object): Args: pet_id, str: ID of pet that needs to be updated (required) - name, str: Updated name of the pet (required) - status, str: Updated status of the pet (required) + name, str: Updated name of the pet (optional) + status, str: Updated status of the pet (optional) Returns: @@ -323,7 +323,7 @@ class PetApi(object): Args: - api_key, str: (required) + api_key, str: (optional) pet_id, int: Pet id to delete (required) @@ -375,8 +375,8 @@ class PetApi(object): Args: pet_id, int: ID of pet to update (required) - additional_metadata, str: Additional data to pass to server (required) - file, file: file to upload (required) + additional_metadata, str: Additional data to pass to server (optional) + file, file: file to upload (optional) Returns: diff --git a/samples/client/petstore/python3/client/store_api.py b/samples/client/petstore/python3/client/store_api.py index 8002b473f8ae..802e116f1ff1 100644 --- a/samples/client/petstore/python3/client/store_api.py +++ b/samples/client/petstore/python3/client/store_api.py @@ -82,7 +82,7 @@ class StoreApi(object): Args: - body, Order: order placed for purchasing the pet (required) + body, Order: order placed for purchasing the pet (optional) Returns: Order diff --git a/samples/client/petstore/python3/client/user_api.py b/samples/client/petstore/python3/client/user_api.py index c4c3c2ede52a..54813ca2dddd 100644 --- a/samples/client/petstore/python3/client/user_api.py +++ b/samples/client/petstore/python3/client/user_api.py @@ -35,7 +35,7 @@ class UserApi(object): This can only be done by the logged in user. Args: - body, User: Created user object (required) + body, User: Created user object (optional) Returns: @@ -77,7 +77,7 @@ class UserApi(object): Args: - body, list[User]: List of user object (required) + body, list[User]: List of user object (optional) Returns: @@ -119,7 +119,7 @@ class UserApi(object): Args: - body, list[User]: List of user object (required) + body, list[User]: List of user object (optional) Returns: @@ -161,8 +161,8 @@ class UserApi(object): Args: - username, str: The user name for login (required) - password, str: The password for login in clear text (required) + username, str: The user name for login (optional) + password, str: The password for login in clear text (optional) Returns: str @@ -311,7 +311,7 @@ class UserApi(object): Args: username, str: name that need to be deleted (required) - body, User: Updated user object (required) + body, User: Updated user object (optional) Returns: From 18ac6e8aae520aa2ba451a567b29b4ddc9662ab4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 25 Jun 2015 23:10:25 +0800 Subject: [PATCH 35/62] fix perl and asyncscala optional tab --- .../main/resources/asyncscala/api.mustache | 11 +- .../src/main/resources/perl/api.mustache | 2 +- samples/client/petstore/async-scala/build.sbt | 12 +- .../io/swagger/client/SwaggerClient.scala | 28 +- .../scala/io/swagger/client/api/PetApi.scala | 360 +++++++++--------- .../io/swagger/client/api/StoreApi.scala | 171 ++++----- .../scala/io/swagger/client/api/UserApi.scala | 351 ++++++++--------- .../io/swagger/client/model/Category.scala | 12 +- .../scala/io/swagger/client/model/Order.scala | 20 +- .../scala/io/swagger/client/model/Pet.scala | 20 +- .../scala/io/swagger/client/model/Tag.scala | 12 +- .../scala/io/swagger/client/model/User.scala | 24 +- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 18 +- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 2 +- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 12 +- 15 files changed, 526 insertions(+), 529 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache index cd12ae188067..49b7c0897043 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -11,10 +11,9 @@ import collection.mutable class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { {{#operation}} - def {{nickname}}({{#allParams}}{{#optional}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}}, - {{/hasMore}} - {{/optional}}{{^optional}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, - {{/hasMore}}{{/optional}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { + def {{nickname}}({{#allParams}}{{^required}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}},{{/hasMore}} + {{/required}}{{#required}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, + {{/hasMore}}{{/required}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { // create path and map variables val path = (addFmt("{{path}}"){{#pathParams}} replaceAll ("\\{" + "{{baseName}}" + "\\}",{{paramName}}.toString){{/pathParams}}) @@ -27,8 +26,8 @@ class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiC val paramCount = (Set[Any]({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) - null).size if (paramCount != {{requiredParamCount}}) sys.error("missing required params"){{/requiredParamCount}} - {{#queryParams}}{{#optional}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/optional}}{{^optional}} - if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/optional}}{{/queryParams}} + {{#queryParams}}{{^required}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/required}}{{#required}} + if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/required}}{{/queryParams}} {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}}.toString{{/headerParams}} diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 93848cf5af84..e69e4e3066f6 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -54,7 +54,7 @@ sub new { # # {{{summary}}} # -{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} +{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}}# @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} # sub {{nickname}} { diff --git a/samples/client/petstore/async-scala/build.sbt b/samples/client/petstore/async-scala/build.sbt index 1d7306d541d0..b02498c74e87 100644 --- a/samples/client/petstore/async-scala/build.sbt +++ b/samples/client/petstore/async-scala/build.sbt @@ -3,10 +3,10 @@ organization := "" name := "-client" libraryDependencies ++= Seq( -"com.wordnik" %% "swagger-async-httpclient" % "0.3.5", -"joda-time" % "joda-time" % "2.3", -"org.joda" % "joda-convert" % "1.3.1", -"ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", -"org.scalatest" %% "scalatest" % "2.2.1" % "test", -"junit" % "junit" % "4.11" % "test" + "io.swagger" %% "swagger-async-httpclient" % "0.3.5", + "joda-time" % "joda-time" % "2.3", + "org.joda" % "joda-convert" % "1.3.1", + "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", + "org.scalatest" %% "scalatest" % "2.2.1" % "test", + "junit" % "junit" % "4.11" % "test" ) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala index 92262387823d..9d0c05187a9d 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala @@ -7,21 +7,21 @@ import io.swagger.client._ import java.io.Closeable class SwaggerClient(config: SwaggerConfig) extends Closeable { -val locator = config.locator -val name = config.name + val locator = config.locator + val name = config.name -private[this] val client = transportClient + private[this] val client = transportClient -protected def transportClient: TransportClient = new RestClient(config) + protected def transportClient: TransportClient = new RestClient(config) + + val user = new UserApi(client, config) + + val pet = new PetApi(client, config) + + val store = new StoreApi(client, config) + - val user = new UserApi(client, config) - - val pet = new PetApi(client, config) - - val store = new StoreApi(client, config) - - -def close() { -client.close() -} + def close() { + client.close() + } } \ No newline at end of file diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala index 5138049a22a2..4b6a2b155d9a 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -7,187 +7,191 @@ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable - class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { +class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - def updatePet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet")) + + def updatePet(body: Option[Pet] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet")) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def addPet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def findPetsByStatus(status: List[String] = available)(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { - // create path and map variables - val path = (addFmt("/pet/findByStatus")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - if(status != null) queryParams += "status" -> status.toString - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { - // create path and map variables - val path = (addFmt("/pet/findByTags")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - if(tags != null) queryParams += "tags" -> tags.toString - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { - // create path and map variables - val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def updatePetWithForm(petId: String, - name: String, - status: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def deletePet(apiKey: String, - petId: Long)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - headerParams += "api_key" -> apiKey.toString - - val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def uploadFile(petId: Long, - additionalMetadata: String, - file: File)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet/{petId}/uploadImage") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) } + } + + + def addPet(body: Option[Pet] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def findPetsByStatus(status: Option[List[String]] = Some(available) + )(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByStatus")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + if(status != null) status.foreach { v => queryParams += "status" -> v.toString } + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def findPetsByTags(tags: Option[List[String]] = None + )(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByTags")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + if(tags != null) tags.foreach { v => queryParams += "tags" -> v.toString } + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def updatePetWithForm(petId: String, + name: Option[String] = None, + status: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deletePet(apiKey: Option[String] = None, + petId: Long)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + headerParams += "api_key" -> apiKey.toString + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def uploadFile(petId: Long, + additionalMetadata: Option[String] = None, + file: Option[File] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}/uploadImage") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala index c98675739dee..c7a18efbf145 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -6,94 +6,95 @@ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable - class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { +class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { - // create path and map variables - val path = (addFmt("/store/inventory")) + + def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { + // create path and map variables + val path = (addFmt("/store/inventory")) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def placeOrder(body: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { - // create path and map variables - val path = (addFmt("/store/order")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def getOrderById(orderId: String)(implicit reader: ClientResponseReader[Order]): Future[Order] = { - // create path and map variables - val path = (addFmt("/store/order/{orderId}") - replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/store/order/{orderId}") - replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) } + } + + + def placeOrder(body: Option[Order] = None + )(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getOrderById(orderId: String)(implicit reader: ClientResponseReader[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala index 3b8ba3cdc2e3..766e4d22312e 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -6,183 +6,186 @@ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable - class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { +class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - def createUser(body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user")) + + def createUser(body: Option[User] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user")) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def createUsersWithArrayInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/createWithArray")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def createUsersWithListInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/createWithList")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def loginUser(username: String, - password: String)(implicit reader: ClientResponseReader[String]): Future[String] = { - // create path and map variables - val path = (addFmt("/user/login")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - if(username != null) queryParams += "username" -> username.toString - if(password != null) queryParams += "password" -> password.toString - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/logout")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { - // create path and map variables - val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def updateUser(username: String, - body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) } + } + + + def createUsersWithArrayInput(body: Option[List[User]] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithArray")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def createUsersWithListInput(body: Option[List[User]] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithList")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def loginUser(username: Option[String] = None, + password: Option[String] = None + )(implicit reader: ClientResponseReader[String]): Future[String] = { + // create path and map variables + val path = (addFmt("/user/login")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + if(username != null) username.foreach { v => queryParams += "username" -> v.toString }if(password != null) password.foreach { v => queryParams += "password" -> v.toString } + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/logout")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def updateUser(username: String, + body: Option[User] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala index a19b846e8758..1b410e7c59ea 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -3,10 +3,8 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Category ( - id: Long, - name: String - - ) - +case class Category ( + id: Long, + name: String + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala index 4e847e74b277..f7a10a449657 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -3,14 +3,12 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Order ( - id: Long, - petId: Long, - quantity: Integer, - shipDate: DateTime, - status: String, // Order Status - complete: Boolean - - ) - +case class Order ( + id: Long, + petId: Long, + quantity: Integer, + shipDate: DateTime, + status: String, // Order Status + complete: Boolean + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala index d7da69df9ee7..7e76c72914b1 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -3,14 +3,12 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Pet ( - id: Long, - category: Category, - name: String, - photoUrls: List[String], - tags: List[Tag], - status: String // pet status in the store - - ) - +case class Pet ( + id: Long, + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + status: String // pet status in the store + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala index aa2a883063f2..9dfe60d36f8b 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -3,10 +3,8 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Tag ( - id: Long, - name: String - - ) - +case class Tag ( + id: Long, + name: String + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala index 692ec7153472..598adae451ad 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala @@ -3,16 +3,14 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class User ( - id: Long, - username: String, - firstName: String, - lastName: String, - email: String, - password: String, - phone: String, - userStatus: Integer // User Status - - ) - +case class User ( + id: Long, + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + userStatus: Integer // User Status + +) diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 7fe640aaea46..bf085889e79d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -52,7 +52,7 @@ sub new { # # Update an existing pet # -# @param Pet $body Pet object that needs to be added to the store (required) +# @param Pet $body Pet object that needs to be added to the store (optional) # @return void # sub update_pet { @@ -102,7 +102,7 @@ sub update_pet { # # Add a new pet to the store # -# @param Pet $body Pet object that needs to be added to the store (required) +# @param Pet $body Pet object that needs to be added to the store (optional) # @return void # sub add_pet { @@ -152,7 +152,7 @@ sub add_pet { # # Finds Pets by status # -# @param ARRAY[string] $status Status values that need to be considered for filter (required) +# @param ARRAY[string] $status Status values that need to be considered for filter (optional) # @return ARRAY[Pet] # sub find_pets_by_status { @@ -205,7 +205,7 @@ sub find_pets_by_status { # # Finds Pets by tags # -# @param ARRAY[string] $tags Tags to filter by (required) +# @param ARRAY[string] $tags Tags to filter by (optional) # @return ARRAY[Pet] # sub find_pets_by_tags { @@ -319,8 +319,8 @@ sub get_pet_by_id { # 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) +# @param string $name Updated name of the pet (optional) +# @param string $status Updated status of the pet (optional) # @return void # sub update_pet_with_form { @@ -387,7 +387,7 @@ sub update_pet_with_form { # # Deletes a pet # -# @param string $api_key (required) +# @param string $api_key (optional) # @param int $pet_id Pet id to delete (required) # @return void # @@ -449,8 +449,8 @@ sub delete_pet { # 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) +# @param string $additional_metadata Additional data to pass to server (optional) +# @param file $file file to upload (optional) # @return void # sub upload_file { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 6072f61518c5..a2ac9010e779 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -101,7 +101,7 @@ sub get_inventory { # # Place an order for a pet # -# @param Order $body order placed for purchasing the pet (required) +# @param Order $body order placed for purchasing the pet (optional) # @return Order # sub place_order { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index f588f1bb410f..4c6e293aaaa6 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -52,7 +52,7 @@ sub new { # # Create user # -# @param User $body Created user object (required) +# @param User $body Created user object (optional) # @return void # sub create_user { @@ -102,7 +102,7 @@ sub create_user { # # 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 (optional) # @return void # sub create_users_with_array_input { @@ -152,7 +152,7 @@ sub create_users_with_array_input { # # 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 (optional) # @return void # sub create_users_with_list_input { @@ -202,8 +202,8 @@ sub create_users_with_list_input { # # 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) +# @param string $username The user name for login (optional) +# @param string $password The password for login in clear text (optional) # @return string # sub login_user { @@ -366,7 +366,7 @@ sub get_user_by_name { # Updated user # # @param string $username name that need to be deleted (required) -# @param User $body Updated user object (required) +# @param User $body Updated user object (optional) # @return void # sub update_user { From 9d739a44cd8daab709dc68ab4ac6d9837e5f4315 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 25 Jun 2015 21:47:00 +0800 Subject: [PATCH 36/62] update python test case --- .../python/SwaggerPetstore-python/tests/test_store_api.py | 1 - 1 file changed, 1 deletion(-) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_store_api.py index 740e2bdc8ad4..933a44f237d8 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_store_api.py @@ -28,4 +28,3 @@ class StoreApiTests(unittest.TestCase): data = self.store_api.get_inventory() self.assertIsNotNone(data) self.assertTrue(isinstance(data, dict)) - self.assertItemsEqual(data.keys(), ['available', 'string', 'sold', 'pending', 'confused', 'active', 'na']) From 6a24b328e37de0f0d27dcb8d4db636de66993acd Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Jun 2015 10:30:12 +0800 Subject: [PATCH 37/62] fix variable name in path --- .../src/main/resources/Java/api.mustache | 2 +- .../main/resources/android-java/api.mustache | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 416 +++++++++--------- 4 files changed, 211 insertions(+), 211 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 63357afd896c..ae4d1cb431e4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -58,7 +58,7 @@ public class {{classname}} { // create path and map variables String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} - .replaceAll("\\{" + "{{paramName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + .replaceAll("\\{" + "{{baseName}}" + "\\}", apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params Map queryParams = new HashMap(); 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 ed9538c15941..b7c99ebf6beb 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/api.mustache @@ -55,7 +55,7 @@ public class {{classname}} { {{/required}}{{/allParams}} // create path and map variables - String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{paramName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; + String path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}}.replaceAll("\\{" + "{{baseName}}" + "\\}", apiInvoker.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params Map queryParams = new HashMap(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 26219b16a458..90a840e6e422 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; 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 bc793fd41ee0..613803b43529 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 @@ -272,214 +272,6 @@ public class PetApi { } } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return Pet - */ - 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") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "api_key", "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Pet) apiClient.deserialize(response, "", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - * @return void - */ - 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") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - "application/x-www-form-urlencoded" - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if (name != null) { - hasFields = true; - mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if (status != null) { - hasFields = true; - mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if(hasFields) - postBody = mp; - } - else { - if (name != null) - formParams.put("name", apiClient.parameterToString(name)); - if (status != null) - formParams.put("status", apiClient.parameterToString(status)); - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - - /** - * Deletes a pet - * - * @param apiKey - * @param petId Pet id to delete - * @return void - */ - 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") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - if (apiKey != null) - headerParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - /** * uploads an image * @@ -559,4 +351,212 @@ public class PetApi { } } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + 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/{pet_id}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "pet_id" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String[] authNames = new String[] { "api_key", "petstore_auth" }; + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ + return (Pet) apiClient.deserialize(response, "", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return void + */ + 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/{pet_id}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if (name != null) { + hasFields = true; + mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); + } + + if (status != null) { + hasFields = true; + mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); + } + + if(hasFields) + postBody = mp; + } + else { + if (name != null) + formParams.put("name", apiClient.parameterToString(name)); + if (status != null) + formParams.put("status", apiClient.parameterToString(status)); + + } + + try { + String[] authNames = new String[] { "petstore_auth" }; + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Deletes a pet + * + * @param apiKey + * @param petId Pet id to delete + * @return void + */ + 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/{pet_id}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String[] authNames = new String[] { "petstore_auth" }; + String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + } From 091e76703ceb3b7eb52a8e9cfb0f8956c7947aa2 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Jun 2015 10:35:50 +0800 Subject: [PATCH 38/62] update sample --- .../java/io/swagger/client/api/PetApi.java | 416 +++++++++--------- 1 file changed, 208 insertions(+), 208 deletions(-) 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 613803b43529..bc793fd41ee0 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 @@ -272,6 +272,214 @@ public class PetApi { } } + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + 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") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String[] authNames = new String[] { "api_key", "petstore_auth" }; + String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ + return (Pet) apiClient.deserialize(response, "", Pet.class); + } + else { + return null; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @return void + */ + 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") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if (name != null) { + hasFields = true; + mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); + } + + if (status != null) { + hasFields = true; + mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); + } + + if(hasFields) + postBody = mp; + } + else { + if (name != null) + formParams.put("name", apiClient.parameterToString(name)); + if (status != null) + formParams.put("status", apiClient.parameterToString(status)); + + } + + try { + String[] authNames = new String[] { "petstore_auth" }; + String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + + /** + * Deletes a pet + * + * @param apiKey + * @param petId Pet id to delete + * @return void + */ + 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") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); + + + + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + + if(contentType.startsWith("multipart/form-data")) { + boolean hasFields = false; + FormDataMultiPart mp = new FormDataMultiPart(); + + if(hasFields) + postBody = mp; + } + else { + + } + + try { + String[] authNames = new String[] { "petstore_auth" }; + String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + throw ex; + } + } + /** * uploads an image * @@ -351,212 +559,4 @@ public class PetApi { } } - /** - * Find pet by ID - * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - * @param petId ID of pet that needs to be fetched - * @return Pet - */ - 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/{pet_id}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "pet_id" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "api_key", "petstore_auth" }; - String response = apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return (Pet) apiClient.deserialize(response, "", Pet.class); - } - else { - return null; - } - } catch (ApiException ex) { - throw ex; - } - } - - /** - * Updates a pet in the store with form data - * - * @param petId ID of pet that needs to be updated - * @param name Updated name of the pet - * @param status Updated status of the pet - * @return void - */ - 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/{pet_id}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - "application/x-www-form-urlencoded" - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if (name != null) { - hasFields = true; - mp.field("name", apiClient.parameterToString(name), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if (status != null) { - hasFields = true; - mp.field("status", apiClient.parameterToString(status), MediaType.MULTIPART_FORM_DATA_TYPE); - } - - if(hasFields) - postBody = mp; - } - else { - if (name != null) - formParams.put("name", apiClient.parameterToString(name)); - if (status != null) - formParams.put("status", apiClient.parameterToString(status)); - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - - /** - * Deletes a pet - * - * @param apiKey - * @param petId Pet id to delete - * @return void - */ - 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/{pet_id}".replaceAll("\\{format\\}","json") - .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - - // query params - Map queryParams = new HashMap(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); - - - - if (apiKey != null) - headerParams.put("api_key", apiClient.parameterToString(apiKey)); - - - final String[] accepts = { - "application/json", "application/xml" - }; - final String accept = apiClient.selectHeaderAccept(accepts); - - final String[] contentTypes = { - - }; - final String contentType = apiClient.selectHeaderContentType(contentTypes); - - if(contentType.startsWith("multipart/form-data")) { - boolean hasFields = false; - FormDataMultiPart mp = new FormDataMultiPart(); - - if(hasFields) - postBody = mp; - } - else { - - } - - try { - String[] authNames = new String[] { "petstore_auth" }; - String response = apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames); - if(response != null){ - return ; - } - else { - return ; - } - } catch (ApiException ex) { - throw ex; - } - } - } From 1de6952279897cb36d4e52ca7eb63070d5f8154f Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 26 Jun 2015 19:09:20 +0800 Subject: [PATCH 39/62] Support customizing default headers via config option for example: config.default_headers['X-MY-HEADER'] = 'my-header-value' --- .../ruby/swagger/configuration.mustache | 10 +++++++ .../resources/ruby/swagger/request.mustache | 27 ++++++++----------- .../swagger_client/swagger/configuration.rb | 10 +++++++ .../lib/swagger_client/swagger/request.rb | 27 ++++++++----------- .../client/petstore/ruby/spec/request_spec.rb | 5 ++++ 5 files changed, 47 insertions(+), 32 deletions(-) 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 9400bdce6b71..fe341f1ced4c 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -10,6 +10,11 @@ module {{moduleName}} # @return [String] attr_accessor :temp_folder_path + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + # Defaults go in here.. def initialize @format = 'json' @@ -21,6 +26,11 @@ module {{moduleName}} @force_ending_format = false @camelize_params = true + @default_headers = { + 'Content-Type' => "application/#{@format.downcase}", + 'User-Agent' => @user_agent + } + # keys for API key authentication (param-name => api-key) @api_key = {} # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) 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 99b58d58be85..9c3e25caff9f 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -10,27 +10,22 @@ module {{moduleName}} # 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] ||= {} + @http_method = http_method.to_sym + @path = path - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - 'User-Agent' => Swagger.configuration.user_agent - } + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) + end - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) + @format ||= Swagger.configuration.format + @params ||= {} + + # Apply default headers + @headers = Swagger.configuration.default_headers.merge(@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) + @headers.merge!({:auth_token => Swagger.configuration.auth_token}) end update_params_for_auth! diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb index 0b7836d989c5..c8c2220a5f92 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb @@ -10,6 +10,11 @@ module SwaggerClient # @return [String] attr_accessor :temp_folder_path + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + # Defaults go in here.. def initialize @format = 'json' @@ -21,6 +26,11 @@ module SwaggerClient @force_ending_format = false @camelize_params = true + @default_headers = { + 'Content-Type' => "application/#{@format.downcase}", + 'User-Agent' => @user_agent + } + # keys for API key authentication (param-name => api-key) @api_key = {} # api-key prefix for API key authentication, e.g. "Bearer" (param-name => api-key-prefix) 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 4cd5d84b0b9b..e4ce431e108e 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb @@ -10,27 +10,22 @@ module SwaggerClient # 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] ||= {} + @http_method = http_method.to_sym + @path = path - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - 'User-Agent' => Swagger.configuration.user_agent - } + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) + end - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) + @format ||= Swagger.configuration.format + @params ||= {} + + # Apply default headers + @headers = Swagger.configuration.default_headers.merge(@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) + @headers.merge!({:auth_token => Swagger.configuration.auth_token}) end update_params_for_auth! diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb index 49bbc5cdd1e2..9d9e61afcc59 100644 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -19,10 +19,15 @@ describe SwaggerClient::Swagger::Request do end describe "initialization" do + it "sets default response format to json" do @request.format.should == 'json' end + it "sets default headers correctly" do + @request.headers.should == {'Content-Type' => 'application/json', 'User-Agent' => 'ruby-swagger-1.0.0'} + end + it "allows params to be nil" do @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil) @request.query_string.should == "" From 38d62d768a42d08972168848b2788be30de0ae59 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 25 Jun 2015 22:40:14 +0800 Subject: [PATCH 40/62] fix optional for python, python3 --- .../src/main/resources/python/api.mustache | 2 +- .../src/main/resources/python3/api.mustache | 2 +- .../python/swagger_client/apis/pet_api.py | 18 +++++++++--------- .../python/swagger_client/apis/store_api.py | 2 +- .../python/swagger_client/apis/user_api.py | 12 ++++++------ .../client/petstore/python3/client/pet_api.py | 18 +++++++++--------- .../petstore/python3/client/store_api.py | 2 +- .../client/petstore/python3/client/user_api.py | 12 ++++++------ 8 files changed, 34 insertions(+), 34 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 867014d5e128..3fb62cb75eab 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -47,7 +47,7 @@ class {{classname}}(object): {{{summary}}} {{{notes}}} - {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} + {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}} :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} """ diff --git a/modules/swagger-codegen/src/main/resources/python3/api.mustache b/modules/swagger-codegen/src/main/resources/python3/api.mustache index 015158bccec7..2ff659b11b50 100644 --- a/modules/swagger-codegen/src/main/resources/python3/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python3/api.mustache @@ -36,7 +36,7 @@ class {{classname}}(object): {{{notes}}} Args: - {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}} Returns: {{returnType}} diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index 5f5c2fe81fa3..7f022930869a 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -46,7 +46,7 @@ class PetApi(object): Update an existing pet - :param Pet body: Pet object that needs to be added to the store + :param Pet body: Pet object that needs to be added to the store (optional) :return: None """ @@ -97,7 +97,7 @@ class PetApi(object): Add a new pet to the store - :param Pet body: Pet object that needs to be added to the store + :param Pet body: Pet object that needs to be added to the store (optional) :return: None """ @@ -148,7 +148,7 @@ class PetApi(object): Finds Pets by status Multiple status values can be provided with comma seperated strings - :param list[str] status: Status values that need to be considered for filter + :param list[str] status: Status values that need to be considered for filter (optional) :return: list[Pet] """ @@ -201,7 +201,7 @@ class PetApi(object): Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - :param list[str] tags: Tags to filter by + :param list[str] tags: Tags to filter by (optional) :return: list[Pet] """ @@ -312,8 +312,8 @@ class PetApi(object): :param str pet_id: ID of pet that needs to be updated (required) - :param str name: Updated name of the pet - :param str status: Updated status of the pet + :param str name: Updated name of the pet (optional) + :param str status: Updated status of the pet (optional) :return: None """ @@ -374,7 +374,7 @@ class PetApi(object): Deletes a pet - :param str api_key: + :param str api_key: (optional) :param int pet_id: Pet id to delete (required) :return: None @@ -434,8 +434,8 @@ class PetApi(object): :param int pet_id: ID of pet to update (required) - :param str additional_metadata: Additional data to pass to server - :param File file: file to upload + :param str additional_metadata: Additional data to pass to server (optional) + :param File file: file to upload (optional) :return: None """ diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index 1e024cfbb5b8..f017df791d9a 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -95,7 +95,7 @@ class StoreApi(object): Place an order for a pet - :param Order body: order placed for purchasing the pet + :param Order body: order placed for purchasing the pet (optional) :return: Order """ diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 84a40b06579e..177c5e3a565f 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -46,7 +46,7 @@ class UserApi(object): Create user This can only be done by the logged in user. - :param User body: Created user object + :param User body: Created user object (optional) :return: None """ @@ -97,7 +97,7 @@ class UserApi(object): Creates list of users with given input array - :param list[User] body: List of user object + :param list[User] body: List of user object (optional) :return: None """ @@ -148,7 +148,7 @@ class UserApi(object): Creates list of users with given input array - :param list[User] body: List of user object + :param list[User] body: List of user object (optional) :return: None """ @@ -199,8 +199,8 @@ class UserApi(object): Logs user into the system - :param str username: The user name for login - :param str password: The password for login in clear text + :param str username: The user name for login (optional) + :param str password: The password for login in clear text (optional) :return: str """ @@ -361,7 +361,7 @@ class UserApi(object): This can only be done by the logged in user. :param str username: name that need to be deleted (required) - :param User body: Updated user object + :param User body: Updated user object (optional) :return: None """ diff --git a/samples/client/petstore/python3/client/pet_api.py b/samples/client/petstore/python3/client/pet_api.py index 9293a89d2b04..cebab131778f 100644 --- a/samples/client/petstore/python3/client/pet_api.py +++ b/samples/client/petstore/python3/client/pet_api.py @@ -35,7 +35,7 @@ class PetApi(object): Args: - body, Pet: Pet object that needs to be added to the store (required) + body, Pet: Pet object that needs to be added to the store (optional) Returns: @@ -77,7 +77,7 @@ class PetApi(object): Args: - body, Pet: Pet object that needs to be added to the store (required) + body, Pet: Pet object that needs to be added to the store (optional) Returns: @@ -119,7 +119,7 @@ class PetApi(object): Multiple status values can be provided with comma seperated strings Args: - status, list[str]: Status values that need to be considered for filter (required) + status, list[str]: Status values that need to be considered for filter (optional) Returns: list[Pet] @@ -170,7 +170,7 @@ class PetApi(object): Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. Args: - tags, list[str]: Tags to filter by (required) + tags, list[str]: Tags to filter by (optional) Returns: list[Pet] @@ -275,8 +275,8 @@ class PetApi(object): Args: pet_id, str: ID of pet that needs to be updated (required) - name, str: Updated name of the pet (required) - status, str: Updated status of the pet (required) + name, str: Updated name of the pet (optional) + status, str: Updated status of the pet (optional) Returns: @@ -323,7 +323,7 @@ class PetApi(object): Args: - api_key, str: (required) + api_key, str: (optional) pet_id, int: Pet id to delete (required) @@ -375,8 +375,8 @@ class PetApi(object): Args: pet_id, int: ID of pet to update (required) - additional_metadata, str: Additional data to pass to server (required) - file, file: file to upload (required) + additional_metadata, str: Additional data to pass to server (optional) + file, file: file to upload (optional) Returns: diff --git a/samples/client/petstore/python3/client/store_api.py b/samples/client/petstore/python3/client/store_api.py index 8002b473f8ae..802e116f1ff1 100644 --- a/samples/client/petstore/python3/client/store_api.py +++ b/samples/client/petstore/python3/client/store_api.py @@ -82,7 +82,7 @@ class StoreApi(object): Args: - body, Order: order placed for purchasing the pet (required) + body, Order: order placed for purchasing the pet (optional) Returns: Order diff --git a/samples/client/petstore/python3/client/user_api.py b/samples/client/petstore/python3/client/user_api.py index c4c3c2ede52a..54813ca2dddd 100644 --- a/samples/client/petstore/python3/client/user_api.py +++ b/samples/client/petstore/python3/client/user_api.py @@ -35,7 +35,7 @@ class UserApi(object): This can only be done by the logged in user. Args: - body, User: Created user object (required) + body, User: Created user object (optional) Returns: @@ -77,7 +77,7 @@ class UserApi(object): Args: - body, list[User]: List of user object (required) + body, list[User]: List of user object (optional) Returns: @@ -119,7 +119,7 @@ class UserApi(object): Args: - body, list[User]: List of user object (required) + body, list[User]: List of user object (optional) Returns: @@ -161,8 +161,8 @@ class UserApi(object): Args: - username, str: The user name for login (required) - password, str: The password for login in clear text (required) + username, str: The user name for login (optional) + password, str: The password for login in clear text (optional) Returns: str @@ -311,7 +311,7 @@ class UserApi(object): Args: username, str: name that need to be deleted (required) - body, User: Updated user object (required) + body, User: Updated user object (optional) Returns: From 3eca940e7de98f33c5ce29d265365061899d5078 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 25 Jun 2015 23:10:25 +0800 Subject: [PATCH 41/62] fix perl and asyncscala optional tab --- .../main/resources/asyncscala/api.mustache | 11 +- .../src/main/resources/perl/api.mustache | 2 +- samples/client/petstore/async-scala/build.sbt | 12 +- .../io/swagger/client/SwaggerClient.scala | 28 +- .../scala/io/swagger/client/api/PetApi.scala | 360 +++++++++--------- .../io/swagger/client/api/StoreApi.scala | 171 ++++----- .../scala/io/swagger/client/api/UserApi.scala | 351 ++++++++--------- .../io/swagger/client/model/Category.scala | 12 +- .../scala/io/swagger/client/model/Order.scala | 20 +- .../scala/io/swagger/client/model/Pet.scala | 20 +- .../scala/io/swagger/client/model/Tag.scala | 12 +- .../scala/io/swagger/client/model/User.scala | 24 +- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 18 +- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 2 +- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 12 +- 15 files changed, 526 insertions(+), 529 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache index cd12ae188067..49b7c0897043 100644 --- a/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/asyncscala/api.mustache @@ -11,10 +11,9 @@ import collection.mutable class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { {{#operation}} - def {{nickname}}({{#allParams}}{{#optional}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}}, - {{/hasMore}} - {{/optional}}{{^optional}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, - {{/hasMore}}{{/optional}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { + def {{nickname}}({{#allParams}}{{^required}}{{paramName}}: Option[{{dataType}}] = {{#defaultValue}}Some({{defaultValue}}){{/defaultValue}}{{^defaultValue}}None{{/defaultValue}}{{#hasMore}},{{/hasMore}} + {{/required}}{{#required}}{{paramName}}: {{dataType}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{#hasMore}}, + {{/hasMore}}{{/required}}{{/allParams}})(implicit reader: ClientResponseReader[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}]{{#bodyParams}}, writer: RequestWriter[{{dataType}}]{{/bodyParams}}){{#returnType}}: Future[{{returnType}}]{{/returnType}}{{^returnType}}: Future[Unit]{{/returnType}} = { // create path and map variables val path = (addFmt("{{path}}"){{#pathParams}} replaceAll ("\\{" + "{{baseName}}" + "\\}",{{paramName}}.toString){{/pathParams}}) @@ -27,8 +26,8 @@ class {{classname}}(client: TransportClient, config: SwaggerConfig) extends ApiC val paramCount = (Set[Any]({{/requiredParamCount}}{{#requiredParams}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) - null).size if (paramCount != {{requiredParamCount}}) sys.error("missing required params"){{/requiredParamCount}} - {{#queryParams}}{{#optional}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/optional}}{{^optional}} - if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/optional}}{{/queryParams}} + {{#queryParams}}{{^required}}if({{paramName}} != null) {{paramName}}.foreach { v => queryParams += "{{baseName}}" -> v.toString }{{/required}}{{#required}} + if({{paramName}} != null) queryParams += "{{baseName}}" -> {{paramName}}.toString{{/required}}{{/queryParams}} {{#headerParams}}headerParams += "{{baseName}}" -> {{paramName}}.toString{{/headerParams}} diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 93848cf5af84..e69e4e3066f6 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -54,7 +54,7 @@ sub new { # # {{{summary}}} # -{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} +{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} {{/allParams}}# @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} # sub {{nickname}} { diff --git a/samples/client/petstore/async-scala/build.sbt b/samples/client/petstore/async-scala/build.sbt index 1d7306d541d0..b02498c74e87 100644 --- a/samples/client/petstore/async-scala/build.sbt +++ b/samples/client/petstore/async-scala/build.sbt @@ -3,10 +3,10 @@ organization := "" name := "-client" libraryDependencies ++= Seq( -"com.wordnik" %% "swagger-async-httpclient" % "0.3.5", -"joda-time" % "joda-time" % "2.3", -"org.joda" % "joda-convert" % "1.3.1", -"ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", -"org.scalatest" %% "scalatest" % "2.2.1" % "test", -"junit" % "junit" % "4.11" % "test" + "io.swagger" %% "swagger-async-httpclient" % "0.3.5", + "joda-time" % "joda-time" % "2.3", + "org.joda" % "joda-convert" % "1.3.1", + "ch.qos.logback" % "logback-classic" % "1.0.13" % "provided", + "org.scalatest" %% "scalatest" % "2.2.1" % "test", + "junit" % "junit" % "4.11" % "test" ) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala index 92262387823d..9d0c05187a9d 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/SwaggerClient.scala @@ -7,21 +7,21 @@ import io.swagger.client._ import java.io.Closeable class SwaggerClient(config: SwaggerConfig) extends Closeable { -val locator = config.locator -val name = config.name + val locator = config.locator + val name = config.name -private[this] val client = transportClient + private[this] val client = transportClient -protected def transportClient: TransportClient = new RestClient(config) + protected def transportClient: TransportClient = new RestClient(config) + + val user = new UserApi(client, config) + + val pet = new PetApi(client, config) + + val store = new StoreApi(client, config) + - val user = new UserApi(client, config) - - val pet = new PetApi(client, config) - - val store = new StoreApi(client, config) - - -def close() { -client.close() -} + def close() { + client.close() + } } \ No newline at end of file diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala index 5138049a22a2..4b6a2b155d9a 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -7,187 +7,191 @@ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable - class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { +class PetApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - def updatePet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet")) + + def updatePet(body: Option[Pet] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet")) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def addPet(body: Pet)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def findPetsByStatus(status: List[String] = available)(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { - // create path and map variables - val path = (addFmt("/pet/findByStatus")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - if(status != null) queryParams += "status" -> status.toString - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def findPetsByTags(tags: List[String])(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { - // create path and map variables - val path = (addFmt("/pet/findByTags")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - if(tags != null) queryParams += "tags" -> tags.toString - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { - // create path and map variables - val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def updatePetWithForm(petId: String, - name: String, - status: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def deletePet(apiKey: String, - petId: Long)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet/{petId}") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - headerParams += "api_key" -> apiKey.toString - - val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def uploadFile(petId: Long, - additionalMetadata: String, - file: File)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/pet/{petId}/uploadImage") - replaceAll ("\\{" + "petId" + "\\}",petId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) } + } + + + def addPet(body: Option[Pet] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[Pet]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def findPetsByStatus(status: Option[List[String]] = Some(available) + )(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByStatus")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + if(status != null) status.foreach { v => queryParams += "status" -> v.toString } + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def findPetsByTags(tags: Option[List[String]] = None + )(implicit reader: ClientResponseReader[List[Pet]]): Future[List[Pet]] = { + // create path and map variables + val path = (addFmt("/pet/findByTags")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + if(tags != null) tags.foreach { v => queryParams += "tags" -> v.toString } + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getPetById(petId: Long)(implicit reader: ClientResponseReader[Pet]): Future[Pet] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def updatePetWithForm(petId: String, + name: Option[String] = None, + status: Option[String] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deletePet(apiKey: Option[String] = None, + petId: Long)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + headerParams += "api_key" -> apiKey.toString + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def uploadFile(petId: Long, + additionalMetadata: Option[String] = None, + file: Option[File] = None + )(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/pet/{petId}/uploadImage") + replaceAll ("\\{" + "petId" + "\\}",petId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala index c98675739dee..c7a18efbf145 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -6,94 +6,95 @@ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable - class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { +class StoreApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { - // create path and map variables - val path = (addFmt("/store/inventory")) + + def getInventory()(implicit reader: ClientResponseReader[Map[String, Integer]]): Future[Map[String, Integer]] = { + // create path and map variables + val path = (addFmt("/store/inventory")) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def placeOrder(body: Order)(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { - // create path and map variables - val path = (addFmt("/store/order")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def getOrderById(orderId: String)(implicit reader: ClientResponseReader[Order]): Future[Order] = { - // create path and map variables - val path = (addFmt("/store/order/{orderId}") - replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/store/order/{orderId}") - replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) } + } + + + def placeOrder(body: Option[Order] = None + )(implicit reader: ClientResponseReader[Order], writer: RequestWriter[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getOrderById(orderId: String)(implicit reader: ClientResponseReader[Order]): Future[Order] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deleteOrder(orderId: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/store/order/{orderId}") + replaceAll ("\\{" + "orderId" + "\\}",orderId.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala index 3b8ba3cdc2e3..766e4d22312e 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -6,183 +6,186 @@ import scala.concurrent.{ Future, Await } import scala.concurrent.duration._ import collection.mutable - class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { +class UserApi(client: TransportClient, config: SwaggerConfig) extends ApiClient(client, config) { - - def createUser(body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user")) + + def createUser(body: Option[User] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user")) - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def createUsersWithArrayInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/createWithArray")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def createUsersWithListInput(body: List[User])(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/createWithList")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def loginUser(username: String, - password: String)(implicit reader: ClientResponseReader[String]): Future[String] = { - // create path and map variables - val path = (addFmt("/user/login")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - if(username != null) queryParams += "username" -> username.toString - if(password != null) queryParams += "password" -> password.toString - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/logout")) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { - // create path and map variables - val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def updateUser(username: String, - body: User)(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) - resFuture flatMap { resp => - process(reader.read(resp)) - } - } - - - def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { - // create path and map variables - val path = (addFmt("/user/{username}") - replaceAll ("\\{" + "username" + "\\}",username.toString)) - - // query params - val queryParams = new mutable.HashMap[String, String] - val headerParams = new mutable.HashMap[String, String] - - - - - - - - val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") - resFuture flatMap { resp => - process(reader.read(resp)) - } - } + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) } + } + + + def createUsersWithArrayInput(body: Option[List[User]] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithArray")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def createUsersWithListInput(body: Option[List[User]] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[List[User]]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/createWithList")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("POST", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def loginUser(username: Option[String] = None, + password: Option[String] = None + )(implicit reader: ClientResponseReader[String]): Future[String] = { + // create path and map variables + val path = (addFmt("/user/login")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + if(username != null) username.foreach { v => queryParams += "username" -> v.toString }if(password != null) password.foreach { v => queryParams += "password" -> v.toString } + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def logoutUser()(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/logout")) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def getUserByName(username: String)(implicit reader: ClientResponseReader[User]): Future[User] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("GET", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def updateUser(username: String, + body: Option[User] = None + )(implicit reader: ClientResponseReader[Unit], writer: RequestWriter[User]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("PUT", path, queryParams.toMap, headerParams.toMap, writer.write(body)) + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + def deleteUser(username: String)(implicit reader: ClientResponseReader[Unit]): Future[Unit] = { + // create path and map variables + val path = (addFmt("/user/{username}") + replaceAll ("\\{" + "username" + "\\}",username.toString)) + + // query params + val queryParams = new mutable.HashMap[String, String] + val headerParams = new mutable.HashMap[String, String] + + + + + + + + val resFuture = client.submit("DELETE", path, queryParams.toMap, headerParams.toMap, "") + resFuture flatMap { resp => + process(reader.read(resp)) + } + } + + + +} diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala index a19b846e8758..1b410e7c59ea 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -3,10 +3,8 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Category ( - id: Long, - name: String - - ) - +case class Category ( + id: Long, + name: String + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala index 4e847e74b277..f7a10a449657 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -3,14 +3,12 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Order ( - id: Long, - petId: Long, - quantity: Integer, - shipDate: DateTime, - status: String, // Order Status - complete: Boolean - - ) - +case class Order ( + id: Long, + petId: Long, + quantity: Integer, + shipDate: DateTime, + status: String, // Order Status + complete: Boolean + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala index d7da69df9ee7..7e76c72914b1 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -3,14 +3,12 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Pet ( - id: Long, - category: Category, - name: String, - photoUrls: List[String], - tags: List[Tag], - status: String // pet status in the store - - ) - +case class Pet ( + id: Long, + category: Category, + name: String, + photoUrls: List[String], + tags: List[Tag], + status: String // pet status in the store + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala index aa2a883063f2..9dfe60d36f8b 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -3,10 +3,8 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class Tag ( - id: Long, - name: String - - ) - +case class Tag ( + id: Long, + name: String + +) diff --git a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala index 692ec7153472..598adae451ad 100644 --- a/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/async-scala/src/main/scala/io/swagger/client/model/User.scala @@ -3,16 +3,14 @@ package io.swagger.client.model import org.joda.time.DateTime - - case class User ( - id: Long, - username: String, - firstName: String, - lastName: String, - email: String, - password: String, - phone: String, - userStatus: Integer // User Status - - ) - +case class User ( + id: Long, + username: String, + firstName: String, + lastName: String, + email: String, + password: String, + phone: String, + userStatus: Integer // User Status + +) diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 7fe640aaea46..bf085889e79d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -52,7 +52,7 @@ sub new { # # Update an existing pet # -# @param Pet $body Pet object that needs to be added to the store (required) +# @param Pet $body Pet object that needs to be added to the store (optional) # @return void # sub update_pet { @@ -102,7 +102,7 @@ sub update_pet { # # Add a new pet to the store # -# @param Pet $body Pet object that needs to be added to the store (required) +# @param Pet $body Pet object that needs to be added to the store (optional) # @return void # sub add_pet { @@ -152,7 +152,7 @@ sub add_pet { # # Finds Pets by status # -# @param ARRAY[string] $status Status values that need to be considered for filter (required) +# @param ARRAY[string] $status Status values that need to be considered for filter (optional) # @return ARRAY[Pet] # sub find_pets_by_status { @@ -205,7 +205,7 @@ sub find_pets_by_status { # # Finds Pets by tags # -# @param ARRAY[string] $tags Tags to filter by (required) +# @param ARRAY[string] $tags Tags to filter by (optional) # @return ARRAY[Pet] # sub find_pets_by_tags { @@ -319,8 +319,8 @@ sub get_pet_by_id { # 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) +# @param string $name Updated name of the pet (optional) +# @param string $status Updated status of the pet (optional) # @return void # sub update_pet_with_form { @@ -387,7 +387,7 @@ sub update_pet_with_form { # # Deletes a pet # -# @param string $api_key (required) +# @param string $api_key (optional) # @param int $pet_id Pet id to delete (required) # @return void # @@ -449,8 +449,8 @@ sub delete_pet { # 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) +# @param string $additional_metadata Additional data to pass to server (optional) +# @param file $file file to upload (optional) # @return void # sub upload_file { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index 6072f61518c5..a2ac9010e779 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -101,7 +101,7 @@ sub get_inventory { # # Place an order for a pet # -# @param Order $body order placed for purchasing the pet (required) +# @param Order $body order placed for purchasing the pet (optional) # @return Order # sub place_order { diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index f588f1bb410f..4c6e293aaaa6 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -52,7 +52,7 @@ sub new { # # Create user # -# @param User $body Created user object (required) +# @param User $body Created user object (optional) # @return void # sub create_user { @@ -102,7 +102,7 @@ sub create_user { # # 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 (optional) # @return void # sub create_users_with_array_input { @@ -152,7 +152,7 @@ sub create_users_with_array_input { # # 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 (optional) # @return void # sub create_users_with_list_input { @@ -202,8 +202,8 @@ sub create_users_with_list_input { # # 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) +# @param string $username The user name for login (optional) +# @param string $password The password for login in clear text (optional) # @return string # sub login_user { @@ -366,7 +366,7 @@ sub get_user_by_name { # Updated user # # @param string $username name that need to be deleted (required) -# @param User $body Updated user object (required) +# @param User $body Updated user object (optional) # @return void # sub update_user { From 91af76cf4187f2f60c3e200cbca3a4ce5364b7ec Mon Sep 17 00:00:00 2001 From: kubo_takaichi Date: Sat, 27 Jun 2015 21:04:01 +0900 Subject: [PATCH 42/62] Use CLI option --- README.md | 2 +- bin/swift-petstore.json | 4 + bin/swift-petstore.sh | 4 +- ...{SwiftGenerator.java => SwiftCodegen.java} | 85 ++++++++---- .../services/io.swagger.codegen.CodegenConfig | 2 +- .../src/main/resources/swift/APIs.mustache | 10 +- .../swift/AlamofireImplementations.mustache | 18 +-- .../main/resources/swift/Extensions.mustache | 18 ++- .../src/main/resources/swift/Models.mustache | 4 +- .../src/main/resources/swift/model.mustache | 10 +- .../petstore/swift/PetstoreClient/Cartfile | 2 - .../Classes/Swaggers/APIs.swift | 10 +- .../Classes/Swaggers/APIs/PetAPI.swift | 128 ++++++++++++++++-- .../Classes/Swaggers/APIs/StoreAPI.swift | 76 +++++++++-- .../Classes/Swaggers/APIs/UserAPI.swift | 18 ++- .../Swaggers/AlamofireImplementations.swift | 22 +-- .../Classes/Swaggers/Extensions.swift | 14 ++ 17 files changed, 326 insertions(+), 101 deletions(-) create mode 100644 bin/swift-petstore.json rename modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/{SwiftGenerator.java => SwiftCodegen.java} (78%) delete mode 100644 samples/client/petstore/swift/PetstoreClient/Cartfile diff --git a/README.md b/README.md index f2c44ebf7183..2fb525528a3e 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,7 @@ StaticDocCodegen.java StaticHtmlGenerator.java SwaggerGenerator.java SwaggerYamlGenerator.java -SwiftGenerator.java +SwiftCodegen.java TizenClientCodegen.java ``` diff --git a/bin/swift-petstore.json b/bin/swift-petstore.json new file mode 100644 index 000000000000..700fdeff0617 --- /dev/null +++ b/bin/swift-petstore.json @@ -0,0 +1,4 @@ +{ + "projectName": "PetstoreClient", + "responseAs": "PromiseKit" +} \ No newline at end of file diff --git a/bin/swift-petstore.sh b/bin/swift-petstore.sh index 4436ed8774d9..96433e5b72d0 100755 --- a/bin/swift-petstore.sh +++ b/bin/swift-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 -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -o samples/client/petstore/swift" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/swift -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l swift -c ./bin/swift-petstore.json -o samples/client/petstore/swift" -java -DsuppressRequired=true -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java similarity index 78% rename from modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java rename to modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 96f0666df52c..5d4f5f341a79 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -11,6 +11,7 @@ import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import javax.annotation.Nullable; @@ -19,8 +20,13 @@ import java.io.File; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { +public class SwiftCodegen extends DefaultCodegen implements CodegenConfig { private static final Pattern PATH_PARAM_PATTERN = Pattern.compile("\\{[a-zA-Z_]+\\}"); + protected static final String LIBRARY_PROMISE_KIT = "PromiseKit"; + protected static final String[] RESPONSE_LIBRARIES = { LIBRARY_PROMISE_KIT }; + protected String projectName = "SwaggerClient"; + protected boolean unwrapRequired = false; + protected String[] responseAs = new String[0]; protected String sourceFolder = "Classes" + File.separator + "Swaggers"; public CodegenType getTag() { @@ -35,7 +41,7 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { return "Generates a swift client library."; } - public SwiftGenerator() { + public SwiftCodegen() { super(); outputFolder = "generated-code" + File.separator + "swift"; modelTemplateFiles.put("model.mustache", ".swift"); @@ -44,34 +50,6 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { apiPackage = File.separator + "APIs"; modelPackage = File.separator + "Models"; - // Inject application name - String appName = System.getProperty("appName"); - if (appName == null) { - appName = "SwaggerClient"; - } - additionalProperties.put("projectName", appName); - - // Inject base url override - String basePathOverride = System.getProperty("basePathOverride"); - if (basePathOverride != null) { - additionalProperties.put("basePathOverride", basePathOverride); - } - - // Make all the variable optional - String suppressRequired = System.getProperty("suppressRequired"); - if (suppressRequired != null) { - additionalProperties.put("suppressRequired", suppressRequired); - } - - sourceFolder = appName + File.separator + sourceFolder; - - supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); - supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); - supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, "AlamofireImplementations.swift")); - supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); - supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); - supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); - languageSpecificPrimitives = new HashSet( Arrays.asList( "Int", @@ -125,6 +103,53 @@ public class SwiftGenerator extends DefaultCodegen implements CodegenConfig { typeMapping.put("file", "NSData"); importMapping = new HashMap(); + + cliOptions.add(new CliOption("projectName", "Project name in Xcode")); + cliOptions.add(new CliOption("responseAs", "Optionally use libraries to manage response. Currently " + + StringUtils.join(RESPONSE_LIBRARIES, ", ") + " are available.")); + cliOptions.add(new CliOption("unwrapRequired", "Treat 'required' properties in response as non-optional " + + "(which would crash the app if api returns null as opposed to required option specified in json schema")); + } + + @Override + public void processOpts() { + super.processOpts(); + + // Setup project name + if (additionalProperties.containsKey("projectName")) { + projectName = (String) additionalProperties.get("projectName"); + } else { + additionalProperties.put("projectName", projectName); + } + sourceFolder = projectName + File.separator + sourceFolder; + + // Setup unwrapRequired option, which makes all the properties with "required" non-optional + if (additionalProperties.containsKey("unwrapRequired")) { + unwrapRequired = Boolean.parseBoolean(String.valueOf(additionalProperties.get("unwrapRequired"))); + } + additionalProperties.put("unwrapRequired", unwrapRequired); + + // Setup unwrapRequired option, which makes all the properties with "required" non-optional + if (additionalProperties.containsKey("responseAs")) { + Object responseAsObject = additionalProperties.get("responseAs"); + if (responseAsObject instanceof String) { + responseAs = ((String)responseAsObject).split(","); + } else { + responseAs = (String[]) responseAsObject; + } + } + additionalProperties.put("responseAs", responseAs); + if (ArrayUtils.contains(responseAs, LIBRARY_PROMISE_KIT)) { + additionalProperties.put("usePromiseKit", true); + } + + supportingFiles.add(new SupportingFile("Cartfile.mustache", "", "Cartfile")); + supportingFiles.add(new SupportingFile("APIHelper.mustache", sourceFolder, "APIHelper.swift")); + supportingFiles.add(new SupportingFile("AlamofireImplementations.mustache", sourceFolder, + "AlamofireImplementations.swift")); + supportingFiles.add(new SupportingFile("Extensions.mustache", sourceFolder, "Extensions.swift")); + supportingFiles.add(new SupportingFile("Models.mustache", sourceFolder, "Models.swift")); + supportingFiles.add(new SupportingFile("APIs.mustache", sourceFolder, "APIs.swift")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 7360129285e8..29c7ed0f729a 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -21,7 +21,7 @@ io.swagger.codegen.languages.StaticDocCodegen io.swagger.codegen.languages.StaticHtmlGenerator io.swagger.codegen.languages.SwaggerGenerator io.swagger.codegen.languages.SwaggerYamlGenerator -io.swagger.codegen.languages.SwiftGenerator +io.swagger.codegen.languages.SwiftCodegen io.swagger.codegen.languages.TizenClientCodegen io.swagger.codegen.languages.TypeScriptAngularClientCodegen io.swagger.codegen.languages.TypeScriptNodeClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index d9fcb84c1254..e473915cf245 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -5,10 +5,9 @@ // import Foundation -import PromiseKit -class {{projectName}}API { - static let basePath = "{{^basePathOverride}}{{basePath}}{{/basePathOverride}}{{basePathOverride}}" +class OneteamAPI { + static let basePath = "http://ec2-52-68-31-200.ap-northeast-1.compute.amazonaws.com/" static var credential: NSURLCredential? static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } @@ -44,7 +43,7 @@ class RequestBuilder { self.isBody = isBody } - func execute() -> Promise> { fatalError("Not implemented") } + func execute(completion: (response: Response?, erorr: NSError?) -> Void) { } func addHeader(#name: String, value: String) -> Self { if !value.isEmpty { @@ -54,7 +53,7 @@ class RequestBuilder { } func addCredential() -> Self { - self.credential = {{projectName}}API.credential + self.credential = OneteamAPI.credential return self } } @@ -63,4 +62,3 @@ protocol RequestBuilderFactory { func getBuilder() -> RequestBuilder.Type } - diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index edc7a51a1691..61e2bf2886d5 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -5,7 +5,6 @@ // import Alamofire -import PromiseKit class AlamofireRequestBuilderFactory: RequestBuilderFactory { func getBuilder() -> RequestBuilder.Type { @@ -21,7 +20,7 @@ class AlamofireRequestBuilder: RequestBuilder { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) } - override func execute() -> Promise> { + override func execute(completion: (response: Response?, erorr: NSError?) -> Void) { let managerId = NSUUID().UUIDString // Create a new manager for each request to customize its request header let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() @@ -35,43 +34,41 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - let defer = Promise>.defer() request.responseJSON(options: .AllowFragments) { (req, res, json, error) in managerStore.removeValueForKey(managerId) if let error = error { - defer.reject(error) + completion(response: nil, erorr: error) return } if res!.statusCode >= 400 { //TODO: Add error entity let userInfo: [NSObject : AnyObject] = (json != nil) ? ["data": json!] : [:] let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: userInfo) - defer.reject(error) + completion(response: nil, erorr: error) return } if () is T { let response = Response(response: res!, body: () as! T) - defer.fulfill(response) + completion(response: response, erorr: nil) return } if let json: AnyObject = json { let body = Decoders.decode(clazz: T.self, source: json) let response = Response(response: res!, body: body) - defer.fulfill(response) + completion(response: response, erorr: nil) return } else if "" is T { // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release // https://github.com/swagger-api/swagger-parser/pull/34 let response = Response(response: res!, body: "" as! T) - defer.fulfill(response) + completion(response: response, erorr: nil) return } - defer.reject(NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } - return defer.promise } private func buildHeaders() -> [String: AnyObject] { @@ -83,4 +80,3 @@ class AlamofireRequestBuilder: RequestBuilder { } } - diff --git a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache index a06ebae7026c..801e90514ffc 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Extensions.mustache @@ -4,8 +4,8 @@ // https://github.com/swagger-api/swagger-codegen // -import Alamofire -import PromiseKit +import Alamofire{{#usePromiseKit}} +import PromiseKit{{/usePromiseKit}} extension Bool: JSONEncodable { func encodeToJSON() -> AnyObject { return self } @@ -63,3 +63,17 @@ extension NSDate: JSONEncodable { return dateFormatter.stringFromDate(self) } } + +{{#usePromiseKit}}extension RequestBuilder { + func execute() -> Promise> { + let deferred = Promise>.defer() + self.execute { (response: Response?, error: NSError?) in + if let response = response { + deferred.fulfill(response) + } else { + deferred.reject(error!) + } + } + return deferred.promise + } +}{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index b2f72e483add..f832cdab9a4d 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -121,8 +121,8 @@ class Decoders { Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] var instance = {{classname}}(){{#vars}}{{#isEnum}} - instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{^suppressRequired}}{{#required}}!{{/required}}{{/suppressRequired}} {{/isEnum}}{{^isEnum}} - instance.{{name}} = Decoders.decode{{#suppressRequired}}Optional{{/suppressRequired}}{{^suppressRequired}}{{^required}}Optional{{/required}}{{/suppressRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{^suppressRequired}}{{#required}}!{{/required}}{{/suppressRequired}}){{/isEnum}}{{/vars}} + instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}} return instance }{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/swift/model.mustache b/modules/swagger-codegen/src/main/resources/swift/model.mustache index 2302a6f44a51..bcd4702fb3bb 100644 --- a/modules/swagger-codegen/src/main/resources/swift/model.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/model.mustache @@ -17,17 +17,17 @@ class {{classname}}: JSONEncodable { } {{/isEnum}}{{/vars}} {{#vars}}{{#isEnum}}{{#description}}/** {{description}} */ - {{/description}}var {{name}}: {{{datatypeWithEnum}}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/suppressRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ - {{/description}}var {{name}}: {{{datatype}}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/suppressRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} + {{/description}}var {{name}}: {{{datatypeWithEnum}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}}{{^isEnum}}{{#description}}/** {{description}} */ + {{/description}}var {{name}}: {{{datatype}}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{#required}}!{{/required}}{{/unwrapRequired}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{/isEnum}} {{/vars}} // MARK: JSONEncodable func encodeToJSON() -> AnyObject { var nillableDictionary = [String:AnyObject?](){{#vars}}{{#isNotContainer}}{{#isPrimitiveType}}{{^isEnum}} nillableDictionary["{{name}}"] = self.{{name}}{{/isEnum}}{{/isPrimitiveType}}{{#isEnum}} - nillableDictionary["{{name}}"] = self.{{name}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} - nillableDictionary["{{name}}"] = self.{{name}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} - nillableDictionary["{{name}}"] = self.{{name}}{{#suppressRequired}}?{{/suppressRequired}}{{^suppressRequired}}{{^required}}?{{/required}}{{/suppressRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} + nillableDictionary["{{name}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.rawValue{{/isEnum}}{{^isPrimitiveType}} + nillableDictionary["{{name}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isPrimitiveType}}{{/isNotContainer}}{{#isContainer}} + nillableDictionary["{{name}}"] = self.{{name}}{{^unwrapRequired}}?{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}?{{/required}}{{/unwrapRequired}}.encodeToJSON(){{/isContainer}}{{/vars}} let dictionary: [String:AnyObject] = APIHelper.rejectNil(nillableDictionary) ?? [:] return dictionary } diff --git a/samples/client/petstore/swift/PetstoreClient/Cartfile b/samples/client/petstore/swift/PetstoreClient/Cartfile deleted file mode 100644 index 245a690a74b0..000000000000 --- a/samples/client/petstore/swift/PetstoreClient/Cartfile +++ /dev/null @@ -1,2 +0,0 @@ -github "Alamofire/Alamofire" >= 1.2 -github "mxcl/PromiseKit" \ No newline at end of file diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift index 75138ff689a0..e473915cf245 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs.swift @@ -5,10 +5,9 @@ // import Foundation -import PromiseKit -class PetstoreClientAPI { - static let basePath = "http://petstore.swagger.io/v2" +class OneteamAPI { + static let basePath = "http://ec2-52-68-31-200.ap-northeast-1.compute.amazonaws.com/" static var credential: NSURLCredential? static var requestBuilderFactory: RequestBuilderFactory = AlamofireRequestBuilderFactory() } @@ -44,7 +43,7 @@ class RequestBuilder { self.isBody = isBody } - func execute() -> Promise> { fatalError("Not implemented") } + func execute(completion: (response: Response?, erorr: NSError?) -> Void) { } func addHeader(#name: String, value: String) -> Self { if !value.isEmpty { @@ -54,7 +53,7 @@ class RequestBuilder { } func addCredential() -> Self { - self.credential = PetstoreClientAPI.credential + self.credential = OneteamAPI.credential return self } } @@ -63,4 +62,3 @@ protocol RequestBuilderFactory { func getBuilder() -> RequestBuilder.Type } - diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift index b136a04f8d2d..5202240bbc97 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/PetAPI.swift @@ -71,8 +71,44 @@ extension PetstoreClientAPI { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] - - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= + 123456 + doggie + string + string +, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= + 123456 + doggie + string + string +, contentType=application/xml}] :param: status (query) Status values that need to be considered for filter @@ -101,8 +137,44 @@ extension PetstoreClientAPI { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] - - examples: [{example=[ {\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} ], contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= + 123456 + doggie + string + string +, contentType=application/xml}] + - examples: [{example=[ { + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +} ], contentType=application/json}, {example= + 123456 + doggie + string + string +, contentType=application/xml}] :param: tags (query) Tags to filter by @@ -134,14 +206,50 @@ extension PetstoreClientAPI { - OAuth: - type: oauth2 - name: petstore_auth - - examples: [{example={\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}, contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] - - examples: [{example={\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}, contentType=application/json}, {example=\n 123456\n \n 123456\n string\n \n doggie\n string\n \n 123456\n string\n \n string\n, contentType=application/xml}] + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= + 123456 + doggie + string + string +, contentType=application/xml}] + - examples: [{example={ + "tags" : [ { + "id" : 123456789, + "name" : "aeiou" + } ], + "id" : 123456789, + "category" : { + "id" : 123456789, + "name" : "aeiou" + }, + "status" : "aeiou", + "name" : "doggie", + "photoUrls" : [ "aeiou" ] +}, contentType=application/json}, {example= + 123456 + doggie + string + string +, contentType=application/xml}] :param: petId (path) ID of pet that needs to be fetched :returns: Promise> */ - func getPetById(#petId: Int?) -> RequestBuilder { + func getPetById(#petId: Int) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -170,7 +278,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func updatePetWithForm(#petId: String?, name: String?, status: String?) -> RequestBuilder { + func updatePetWithForm(#petId: String, name: String?, status: String?) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -197,7 +305,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func deletePet(#petId: Int?) -> RequestBuilder { + func deletePet(#petId: Int) -> RequestBuilder { var path = "/pet/{petId}" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -226,7 +334,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func uploadFile(#petId: Int?, additionalMetadata: String?, file: NSData?) -> RequestBuilder { + func uploadFile(#petId: Int, additionalMetadata: String?, file: NSData?) -> RequestBuilder { var path = "/pet/{petId}/uploadImage" path = path.stringByReplacingOccurrencesOfString("{petId}", withString: "\(petId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift index ed0c5a87889c..ad122129939a 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/StoreAPI.swift @@ -21,8 +21,12 @@ extension PetstoreClientAPI { - API Key: - type: apiKey api_key - name: api_key - - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@5c7e707e, contentType=application/xml}] - - examples: [{example={\n "key" : 123\n}, contentType=application/json}, {example=not implemented com.wordnik.swagger.models.properties.MapProperty@5c7e707e, contentType=application/xml}] + - examples: [{example={ + "key" : 123 +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@3e, contentType=application/xml}] + - examples: [{example={ + "key" : 123 +}, contentType=application/json}, {example=not implemented io.swagger.models.properties.MapProperty@3e, contentType=application/xml}] :returns: Promise> */ @@ -44,8 +48,36 @@ extension PetstoreClientAPI { - POST /store/order - - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.814+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.817Z\n string\n true\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.814+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.817Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2015-06-27T13:41:28.102+0000" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2015-06-27T22:41:28.105Z + string + true +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2015-06-27T13:41:28.102+0000" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2015-06-27T22:41:28.105Z + string + true +, contentType=application/xml}] :param: body (body) order placed for purchasing the pet @@ -68,14 +100,42 @@ extension PetstoreClientAPI { - GET /store/order/{orderId} - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.818+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.818Z\n string\n true\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "petId" : 123456789,\n "complete" : true,\n "status" : "aeiou",\n "quantity" : 123,\n "shipDate" : "2015-05-27T04:22:21.818+0000"\n}, contentType=application/json}, {example=\n 123456\n 123456\n 0\n 2015-05-27T13:22:21.818Z\n string\n true\n, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2015-06-27T13:41:28.106+0000" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2015-06-27T22:41:28.106Z + string + true +, contentType=application/xml}] + - examples: [{example={ + "id" : 123456789, + "petId" : 123456789, + "complete" : true, + "status" : "aeiou", + "quantity" : 123, + "shipDate" : "2015-06-27T13:41:28.106+0000" +}, contentType=application/json}, {example= + 123456 + 123456 + 0 + 2015-06-27T22:41:28.106Z + string + true +, contentType=application/xml}] :param: orderId (path) ID of pet that needs to be fetched :returns: Promise> */ - func getOrderById(#orderId: String?) -> RequestBuilder { + func getOrderById(#orderId: String) -> RequestBuilder { var path = "/store/order/{orderId}" path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -99,7 +159,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func deleteOrder(#orderId: String?) -> RequestBuilder { + func deleteOrder(#orderId: String) -> RequestBuilder { var path = "/store/order/{orderId}" path = path.stringByReplacingOccurrencesOfString("{orderId}", withString: "\(orderId)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift index 812d823459d6..9c2833962146 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/APIs/UserAPI.swift @@ -134,14 +134,22 @@ extension PetstoreClientAPI { - GET /user/{username} - - - examples: [{example={\n "id" : 123456789,\n "lastName" : "aeiou",\n "phone" : "aeiou",\n "username" : "aeiou",\n "email" : "aeiou",\n "userStatus" : 123,\n "firstName" : "aeiou",\n "password" : "aeiou"\n}, contentType=application/json}, {example=\n 123456\n string\n string\n string\n string\n string\n string\n 0\n, contentType=application/xml}] - - examples: [{example={\n "id" : 123456789,\n "lastName" : "aeiou",\n "phone" : "aeiou",\n "username" : "aeiou",\n "email" : "aeiou",\n "userStatus" : 123,\n "firstName" : "aeiou",\n "password" : "aeiou"\n}, contentType=application/json}, {example=\n 123456\n string\n string\n string\n string\n string\n string\n 0\n, contentType=application/xml}] + - examples: [{example={ + "id" : 1, + "username" : "johnp", + "firstName" : "John", + "lastName" : "Public", + "email" : "johnp@swagger.io", + "password" : "-secret-", + "phone" : "0123456789", + "userStatus" : 0 +}, contentType=application/json}] :param: username (path) The name that needs to be fetched. Use user1 for testing. :returns: Promise> */ - func getUserByName(#username: String?) -> RequestBuilder { + func getUserByName(#username: String) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -166,7 +174,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func updateUser(#username: String?, body: User?) -> RequestBuilder { + func updateUser(#username: String, body: User?) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path @@ -189,7 +197,7 @@ extension PetstoreClientAPI { :returns: Promise> */ - func deleteUser(#username: String?) -> RequestBuilder { + func deleteUser(#username: String) -> RequestBuilder { var path = "/user/{username}" path = path.stringByReplacingOccurrencesOfString("{username}", withString: "\(username)", options: .LiteralSearch, range: nil) let url = PetstoreClientAPI.basePath + path diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift index 37edceea13c7..61e2bf2886d5 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/AlamofireImplementations.swift @@ -5,7 +5,6 @@ // import Alamofire -import PromiseKit class AlamofireRequestBuilderFactory: RequestBuilderFactory { func getBuilder() -> RequestBuilder.Type { @@ -21,7 +20,7 @@ class AlamofireRequestBuilder: RequestBuilder { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) } - override func execute() -> Promise> { + override func execute(completion: (response: Response?, erorr: NSError?) -> Void) { let managerId = NSUUID().UUIDString // Create a new manager for each request to customize its request header let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() @@ -35,37 +34,41 @@ class AlamofireRequestBuilder: RequestBuilder { request.authenticate(usingCredential: credential) } - let defer = Promise>.defer() request.responseJSON(options: .AllowFragments) { (req, res, json, error) in managerStore.removeValueForKey(managerId) if let error = error { - defer.reject(error) + completion(response: nil, erorr: error) return } if res!.statusCode >= 400 { //TODO: Add error entity let userInfo: [NSObject : AnyObject] = (json != nil) ? ["data": json!] : [:] let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: userInfo) - defer.reject(error) + completion(response: nil, erorr: error) return } if () is T { let response = Response(response: res!, body: () as! T) - defer.fulfill(response) + completion(response: response, erorr: nil) return } if let json: AnyObject = json { let body = Decoders.decode(clazz: T.self, source: json) let response = Response(response: res!, body: body) - defer.fulfill(response) + completion(response: response, erorr: nil) + return + } else if "" is T { + // swagger-parser currently doesn't support void, which will be fixed in future swagger-parser release + // https://github.com/swagger-api/swagger-parser/pull/34 + let response = Response(response: res!, body: "" as! T) + completion(response: response, erorr: nil) return } - defer.reject(NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) + completion(response: nil, erorr: NSError(domain: "localhost", code: 500, userInfo: ["reason": "unreacheable code"])) } - return defer.promise } private func buildHeaders() -> [String: AnyObject] { @@ -77,4 +80,3 @@ class AlamofireRequestBuilder: RequestBuilder { } } - diff --git a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift index a06ebae7026c..80af4351f048 100644 --- a/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift +++ b/samples/client/petstore/swift/PetstoreClient/Classes/Swaggers/Extensions.swift @@ -63,3 +63,17 @@ extension NSDate: JSONEncodable { return dateFormatter.stringFromDate(self) } } + +extension RequestBuilder { + func execute() -> Promise> { + let deferred = Promise>.defer() + self.execute { (response: Response?, error: NSError?) in + if let response = response { + deferred.fulfill(response) + } else { + deferred.reject(error!) + } + } + return deferred.promise + } +} From 2d59c5d1903d594cc83dfbffa48d96c38f8be0d4 Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 29 Jun 2015 13:39:39 +0200 Subject: [PATCH 43/62] generate oauth2 fields in the data for the templates Fixes #347 --- .../io/swagger/codegen/CodegenSecurity.java | 5 +++++ .../io/swagger/codegen/DefaultCodegen.java | 14 +++++++++++--- .../io/swagger/codegen/DefaultGenerator.java | 18 +++++++++++++++++- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index 8613e0a8d416..edd65cc06034 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -1,5 +1,7 @@ package io.swagger.codegen; +import java.util.Set; + public class CodegenSecurity { public String name; public String type; @@ -7,4 +9,7 @@ public class CodegenSecurity { // ApiKey specific public String keyParamName; public Boolean isKeyInQuery, isKeyInHeader; + // Oauth specific + public String flow, authorizationUrl, tokenUrl; + public Set scopes; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 71b6295c9bee..e4967cd8b2b7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -14,6 +14,7 @@ import io.swagger.models.Swagger; import io.swagger.models.auth.ApiKeyAuthDefinition; import io.swagger.models.auth.BasicAuthDefinition; import io.swagger.models.auth.In; +import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.models.parameters.BodyParameter; import io.swagger.models.parameters.CookieParameter; @@ -1056,10 +1057,17 @@ public class DefaultCodegen { sec.keyParamName = apiKeyDefinition.getName(); sec.isKeyInHeader = apiKeyDefinition.getIn() == In.HEADER; sec.isKeyInQuery = !sec.isKeyInHeader; + } else if(schemeDefinition instanceof BasicAuthDefinition) { + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isOAuth = false; + sec.isBasic = true; } else { - sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = false; - sec.isBasic = schemeDefinition instanceof BasicAuthDefinition; - sec.isOAuth = !sec.isBasic; + final OAuth2Definition oauth2Definition = (OAuth2Definition) schemeDefinition; + sec.isKeyInHeader = sec.isKeyInQuery = sec.isApiKey = sec.isBasic = false; + sec.isOAuth = true; + sec.flow = oauth2Definition.getFlow(); + sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); + sec.tokenUrl = oauth2Definition.getTokenUrl(); + sec.scopes = oauth2Definition.getScopes().keySet(); } sec.hasMore = it.hasNext(); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index a04e517bee5b..8ace77d5641a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -9,6 +9,7 @@ import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; +import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; import io.swagger.util.Json; import org.apache.commons.io.IOUtils; @@ -366,7 +367,22 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { String securityName = security.keySet().iterator().next(); SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); if (securityDefinition != null) { - authMethods.put(securityName, securityDefinition); + if(securityDefinition instanceof OAuth2Definition) { + OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; + OAuth2Definition oauth2Operation = new OAuth2Definition(); + oauth2Operation.setType(oauth2Definition.getType()); + oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); + oauth2Operation.setFlow(oauth2Definition.getFlow()); + oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); + for (String scope : security.values().iterator().next()) { + if (oauth2Definition.getScopes().containsKey(scope)) { + oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); + } + } + authMethods.put(securityName, oauth2Operation); + } else { + authMethods.put(securityName, securityDefinition); + } } } if (!authMethods.isEmpty()) { From 20c7932df46101c787d5e0d029a333e6cd57d65c Mon Sep 17 00:00:00 2001 From: DariusM Date: Tue, 7 Jul 2015 13:00:28 +0200 Subject: [PATCH 44/62] Python /python3 datetime and date fixed --- .../io/swagger/codegen/languages/Python3ClientCodegen.java | 4 +++- .../io/swagger/codegen/languages/PythonClientCodegen.java | 4 +++- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java index 4911ca06850c..71562e6ba370 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java @@ -33,6 +33,7 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("datetime"); + languageSpecificPrimitives.add("date"); typeMapping.clear(); typeMapping.put("integer", "int"); @@ -43,7 +44,8 @@ public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfi typeMapping.put("map", "map"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "str"); - typeMapping.put("date", "datetime"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); // from https://docs.python.org/release/2.5.4/ref/keywords.html reservedWords = new HashSet( diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 475a816aa5c4..090c0e0c3dc8 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -34,6 +34,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("str"); languageSpecificPrimitives.add("datetime"); + languageSpecificPrimitives.add("date"); typeMapping.clear(); typeMapping.put("integer", "int"); @@ -44,7 +45,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("map", "dict"); typeMapping.put("boolean", "bool"); typeMapping.put("string", "str"); - typeMapping.put("date", "datetime"); + typeMapping.put("date", "date"); + typeMapping.put("DateTime", "datetime"); typeMapping.put("object", "object"); // from https://docs.python.org/release/2.5.4/ref/keywords.html From f6a1af28317a6a17b15c34e6fad8780aa5bf8632 Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Wed, 8 Jul 2015 11:17:06 +0200 Subject: [PATCH 45/62] Changed maps to any and DateTime to Date --- .../codegen/languages/TypeScriptNodeClientCodegen.java | 3 +++ .../scala/typescriptangular/TypeScriptAngularModelTest.scala | 4 ++-- .../test/scala/typescriptnode/TypeScriptNodeModelTest.scala | 4 ++-- 3 files changed, 7 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index 19b8514f8e3c..a66d2de737ed 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -1,6 +1,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; +import io.swagger.models.Swagger; import io.swagger.models.properties.*; import java.util.*; @@ -77,6 +78,8 @@ public class TypeScriptNodeClientCodegen extends DefaultCodegen implements Codeg typeMapping.put("double", "number"); typeMapping.put("object", "any"); typeMapping.put("integer", "number"); + typeMapping.put("Map", "any"); + typeMapping.put("DateTime", "Date"); } diff --git a/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala b/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala index 5e28e3e8dc79..f82215253382 100644 --- a/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala @@ -49,8 +49,8 @@ class TypeScriptAngularModelTest extends FlatSpec with Matchers { vars.get(1).isNotContainer should equal(true) vars.get(2).baseName should be("createdAt") - vars.get(2).complexType should be("DateTime") - vars.get(2).datatype should be("DateTime") + vars.get(2).complexType should be("Date") + vars.get(2).datatype should be("Date") vars.get(2).name should be("createdAt") vars.get(2).defaultValue should be("null") vars.get(2).hasMore should equal(null) diff --git a/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala b/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala index 0b91d717bf66..3ab26be651be 100644 --- a/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala @@ -49,8 +49,8 @@ class TypeScriptNodeModelTest extends FlatSpec with Matchers { vars.get(1).isNotContainer should equal(true) vars.get(2).baseName should be("createdAt") - vars.get(2).complexType should be("DateTime") - vars.get(2).datatype should be("DateTime") + vars.get(2).complexType should be("Date") + vars.get(2).datatype should be("Date") vars.get(2).name should be("createdAt") vars.get(2).defaultValue should be("null") vars.get(2).hasMore should equal(null) From 4133cae2bce577f8e6f4d59d0d0c3387d5bd61e7 Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Wed, 8 Jul 2015 11:19:25 +0200 Subject: [PATCH 46/62] Fixed mustache to handle non-required parameters --- .../src/main/resources/TypeScript-Angular/api.mustache | 4 ++-- .../src/main/resources/TypeScript-node/api.mustache | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 88f7f9ff15a2..eb9e27fc06a0 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -22,7 +22,7 @@ module {{package}} { } } {{#operation}} - public {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}, {{/allParams}} extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { var path = this.basePath + '{{path}}'; {{#pathParams}} path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); @@ -50,7 +50,7 @@ module {{package}} { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams){ + for (var k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index eb569cdc9289..22775f703404 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -16,7 +16,7 @@ export class {{classname}} { } {{#operation}} - public {{nickname}} ({{#allParams}}{{paramName}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}} ) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { + public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { var path = this.url + this.basePath + '{{path}}'; {{#pathParams}} From d3bc347e317aaf7cfccfe6b574a2f7b4edf8c478 Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Thu, 9 Jul 2015 10:34:39 +0200 Subject: [PATCH 47/62] Changed base path to use contextPath --- .../src/main/resources/TypeScript-Angular/api.mustache | 2 +- .../src/main/resources/TypeScript-node/api.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index eb9e27fc06a0..83fee2ce4e36 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -12,7 +12,7 @@ module {{package}} { */ {{/description}} export class {{classname}} { - private basePath = '{{basePath}}'; + private basePath = '{{contextPath}}'; static $inject: string[] = ['$http']; diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 22775f703404..debeed69515b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -7,7 +7,7 @@ */ {{/description}} export class {{classname}} { - private basePath = '{{basePath}}'; + private basePath = '{{contextPath}}'; constructor(private url: string, private username: string, private password: string, basePath?: string) { if (basePath) { From abc7100a1705c2c126fefc1da101008f1cf63c9d Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Thu, 9 Jul 2015 14:54:36 +0200 Subject: [PATCH 48/62] Removed unused code from the api classes --- .../src/main/resources/TypeScript-Angular/api.mustache | 3 --- 1 file changed, 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 83fee2ce4e36..bd5eaaef87af 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -61,8 +61,5 @@ module {{package}} { } {{/operation}} } - - angular.module('{{package}}_{{classname}}', ['$http']) - .service('{{classname}}', {{classname}}); } {{/operations}} From 7e8f8e85d7ad4469ae8777f4d599fe8a4bd46560 Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Thu, 9 Jul 2015 14:55:15 +0200 Subject: [PATCH 49/62] Changed default name of the modelPackage --- .../codegen/languages/TypeScriptAngularClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java index a31e15878cff..11cae0de0ef1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptAngularClientCodegen.java @@ -18,7 +18,7 @@ public class TypeScriptAngularClientCodegen extends TypeScriptNodeClientCodegen apiTemplateFiles.put("api.mustache", ".ts"); templateDir = "TypeScript-Angular"; apiPackage = "api"; - modelPackage = "api"; + modelPackage = "model"; supportingFiles.add(new SupportingFile("api.d.mustache", apiPackage + File.separator, "api.d.ts")); } From e3d3641b962b1ba5cf17639173d8e97fa061b50a Mon Sep 17 00:00:00 2001 From: Martin Hardorf Date: Thu, 9 Jul 2015 14:57:40 +0200 Subject: [PATCH 50/62] Removed unused import --- .../swagger/codegen/languages/TypeScriptNodeClientCodegen.java | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java index a66d2de737ed..0ea33f21709f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptNodeClientCodegen.java @@ -1,7 +1,6 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; -import io.swagger.models.Swagger; import io.swagger.models.properties.*; import java.util.*; From 9283249963c92fd0c1243b8134d076c44a85915d Mon Sep 17 00:00:00 2001 From: Dilip Krishnan Date: Tue, 7 Jul 2015 17:55:07 -0500 Subject: [PATCH 51/62] Updated the swagger-codegen sample for generating the service side stubs for spring mvc using springfox implementation --- .../languages/SpringMVCServerCodegen.java | 9 +++ .../resources/JavaSpringMVC/README.mustache | 3 +- .../main/resources/JavaSpringMVC/api.mustache | 6 +- .../main/resources/JavaSpringMVC/pom.mustache | 70 +------------------ samples/server/petstore/spring-mvc/pom.xml | 66 +---------------- 5 files changed, 17 insertions(+), 137 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index a90533a36143..626421839066 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -2,6 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenResponse; import io.swagger.codegen.CodegenType; import io.swagger.codegen.SupportingFile; import io.swagger.models.Operation; @@ -146,6 +147,14 @@ public class SpringMVCServerCodegen extends JavaClientCodegen implements Codegen if (operations != null) { List ops = (List) operations.get("operation"); for (CodegenOperation operation : ops) { + List responses = operation.responses; + if (responses != null) { + for (CodegenResponse resp : responses) { + if ("0".equals(resp.code)) { + resp.code = "200"; + } + } + } if (operation.returnType == null) { operation.returnType = "Void"; } else if (operation.returnType.startsWith("List")) { diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/README.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/README.mustache index f357cb9a081f..9cf2b4bc6e80 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/README.mustache @@ -8,4 +8,5 @@ This server was generated by the [swagger-codegen](https://github.com/swagger-ap The underlying library integrating swagger to Spring-MVC is [springfox](https://github.com/springfox/springfox) -You can view the server in swagger-ui by pointing to http://localhost:8002{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}/sdoc.jsp \ No newline at end of file +You can view the server in swagger-ui by pointing to +http://localhost:8002{{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}}/swagger-ui.html \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index d6a24b69311b..4f3c5489169b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -8,8 +8,8 @@ import {{modelPackage}}.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; -import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.model.ApiResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -35,8 +35,8 @@ public class {{classname}} { {{#operation}} @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @ApiResponses(value = { {{#responses}} - @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) + @io.swagger.annotations.ApiResponses(value = { {{#responses}} + @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{path}}", {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache index 3b068adffdf3..9896c3ac6d83 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/pom.mustache @@ -33,8 +33,7 @@ {{^contextPath}}/{{/contextPath}}{{#contextPath}}{{contextPath}}{{/contextPath}} - target/${project.artifactId}-${project-version} - ${project.basedir}/conf/jetty/webdefault.xml + target/${project.artifactId}-${project.version} 8079 stopit @@ -63,49 +62,6 @@ - - com.googlecode.maven-download-plugin - download-maven-plugin - 1.2.1 - - - swagger-ui - - wget - - - https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz - true - ${project.build.directory} - - - - - - maven-resources-plugin - 2.6 - - - copy-resources - validate - - copy-resources - - - target/${project.artifactId}-${project.version} - - - ${project.build.directory}/swagger-ui-${swagger-ui-version}/dist - true - - index.html - - - - - - - @@ -163,21 +119,6 @@ - - io.springfox - springfox-core - ${springfox-version} - - - io.springfox - springfox-spi - ${springfox-version} - - - io.springfox - springfox-spring-web - ${springfox-version} - io.springfox springfox-swagger2 @@ -189,12 +130,6 @@ ${springfox-version} - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test - junit junit @@ -217,13 +152,12 @@ 1.5.0 9.2.9.v20150224 - 2.1.0-M2 1.13 1.6.3 1.6.1 4.8.1 2.5 - 2.0.0-SNAPSHOT + 2.0.4-SNAPSHOT 4.0.9.RELEASE \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 30cd3a414845..0aaf79440b45 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -63,49 +63,6 @@ - - com.googlecode.maven-download-plugin - download-maven-plugin - 1.2.1 - - - swagger-ui - - wget - - - https://github.com/swagger-api/swagger-ui/archive/v${swagger-ui-version}.tar.gz - true - ${project.build.directory} - - - - - - maven-resources-plugin - 2.6 - - - copy-resources - validate - - copy-resources - - - target/${project.artifactId}-${project.version} - - - ${project.build.directory}/swagger-ui-${swagger-ui-version}/dist - true - - index.html - - - - - - - @@ -163,21 +120,6 @@ - - io.springfox - springfox-core - ${springfox-version} - - - io.springfox - springfox-spi - ${springfox-version} - - - io.springfox - springfox-spring-web - ${springfox-version} - io.springfox springfox-swagger2 @@ -189,12 +131,6 @@ ${springfox-version} - - org.scalatest - scalatest_2.9.1 - ${scala-test-version} - test - junit junit @@ -223,7 +159,7 @@ 1.6.1 4.8.1 2.5 - 2.0.0-SNAPSHOT + 2.0.4-SNAPSHOT 4.0.9.RELEASE \ No newline at end of file From 7cc9581f042b6a0ff0d74ce158540fecc43fd48e Mon Sep 17 00:00:00 2001 From: Dilip Krishnan Date: Sun, 12 Jul 2015 20:50:32 -0500 Subject: [PATCH 52/62] Updated the mustache template to remove the spurious import Also regenerated the spring-mvc server sample --- .../src/main/resources/JavaSpringMVC/api.mustache | 6 +++--- samples/server/petstore/spring-mvc/README.md | 3 ++- samples/server/petstore/spring-mvc/pom.xml | 4 +--- .../spring-mvc/src/main/java/io/swagger/api/PetApi.java | 2 +- .../spring-mvc/src/main/java/io/swagger/api/UserApi.java | 8 ++++---- 5 files changed, 11 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index 4f3c5489169b..d6a24b69311b 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -8,8 +8,8 @@ import {{modelPackage}}.*; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; +import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import io.swagger.model.ApiResponse; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -35,8 +35,8 @@ public class {{classname}} { {{#operation}} @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @io.swagger.annotations.ApiResponses(value = { {{#responses}} - @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) + @ApiResponses(value = { {{#responses}} + @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{path}}", {{#hasProduces}}produces = { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }, {{/hasProduces}} {{#hasConsumes}}consumes = { {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} },{{/hasConsumes}} diff --git a/samples/server/petstore/spring-mvc/README.md b/samples/server/petstore/spring-mvc/README.md index 3ec7c5d70eae..3fa87e708933 100644 --- a/samples/server/petstore/spring-mvc/README.md +++ b/samples/server/petstore/spring-mvc/README.md @@ -8,4 +8,5 @@ This server was generated by the [swagger-codegen](https://github.com/swagger-ap The underlying library integrating swagger to Spring-MVC is [springfox](https://github.com/springfox/springfox) -You can view the server in swagger-ui by pointing to http://localhost:8002/v2/sdoc.jsp \ No newline at end of file +You can view the server in swagger-ui by pointing to +http://localhost:8002/v2/swagger-ui.html \ No newline at end of file diff --git a/samples/server/petstore/spring-mvc/pom.xml b/samples/server/petstore/spring-mvc/pom.xml index 0aaf79440b45..1b49d0a46918 100644 --- a/samples/server/petstore/spring-mvc/pom.xml +++ b/samples/server/petstore/spring-mvc/pom.xml @@ -33,8 +33,7 @@ /v2 - target/${project.artifactId}-${project-version} - ${project.basedir}/conf/jetty/webdefault.xml + target/${project.artifactId}-${project.version} 8079 stopit @@ -153,7 +152,6 @@ 1.5.0 9.2.9.v20150224 - 2.1.0-M2 1.13 1.6.3 1.6.1 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 6264ec785679..52ddc63c23cb 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 @@ -171,7 +171,7 @@ public class PetApi { @ApiOperation(value = "uploads an image", notes = "", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 0, message = "successful operation") }) + @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", produces = { "application/json", "application/xml" }, consumes = { "multipart/form-data" }, 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 35227db7c677..dd5fbc6c279e 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 @@ -35,7 +35,7 @@ public class UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 0, message = "successful operation") }) + @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, @@ -52,7 +52,7 @@ public class UserApi { @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 0, message = "successful operation") }) + @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithArray", produces = { "application/json", "application/xml" }, @@ -69,7 +69,7 @@ public class UserApi { @ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 0, message = "successful operation") }) + @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/createWithList", produces = { "application/json", "application/xml" }, @@ -107,7 +107,7 @@ public class UserApi { @ApiOperation(value = "Logs out current logged in user session", notes = "", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 0, message = "successful operation") }) + @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/logout", produces = { "application/json", "application/xml" }, From fcd0b31d7d3b2d7a7a185481676a58942404a691 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Jun 2015 17:06:30 +0800 Subject: [PATCH 53/62] add file response for php --- .../codegen/languages/PhpClientCodegen.java | 2 +- .../src/main/resources/php/ApiClient.mustache | 7 ++- .../resources/php/ObjectSerializer.mustache | 28 ++++++++++-- .../src/main/resources/php/api.mustache | 6 +-- .../main/resources/php/configuration.mustache | 14 ++++++ .../src/main/resources/php/model.mustache | 4 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 36 +++++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 20 ++++----- .../php/SwaggerClient-php/lib/Api/UserApi.php | 24 +++++----- .../php/SwaggerClient-php/lib/ApiClient.php | 7 ++- .../SwaggerClient-php/lib/Configuration.php | 14 ++++++ .../SwaggerClient-php/lib/Model/Category.php | 4 +- .../php/SwaggerClient-php/lib/Model/Order.php | 4 +- .../php/SwaggerClient-php/lib/Model/Pet.php | 4 +- .../php/SwaggerClient-php/lib/Model/Tag.php | 4 +- .../php/SwaggerClient-php/lib/Model/User.php | 4 +- .../lib/ObjectSerializer.php | 28 ++++++++++-- .../php-coveralls/build/config/apigen.neon | 5 --- .../php-coveralls/build/config/phpcs.xml | 31 ------------- .../php-coveralls/build/config/phpmd.xml | 45 ------------------- .../satooshi/php-coveralls/travis/empty | 0 samples/client/petstore/php/test.php | 16 +++---- 22 files changed, 154 insertions(+), 153 deletions(-) delete mode 100644 samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/apigen.neon delete mode 100644 samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpcs.xml delete mode 100644 samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpmd.xml delete mode 100644 samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/travis/empty diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index e2ddba4bf345..c6e6d65596c3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -79,7 +79,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("boolean", "bool"); typeMapping.put("date", "\\DateTime"); typeMapping.put("datetime", "\\DateTime"); - typeMapping.put("file", "string"); + typeMapping.put("file", "\\SplFileObject"); typeMapping.put("map", "map"); typeMapping.put("array", "array"); typeMapping.put("list", "array"); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 2862a0e0538e..3a4f8dfc8be3 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -90,7 +90,7 @@ class ApiClient { * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { $headers = array(); @@ -174,6 +174,11 @@ class ApiClient { if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + // return raw body if response is a file + if ($responseType == 'SplFileObject') { + return array($http_body, $http_header); + } + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string $data = $http_body; diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 56a61e97c916..26999668b9e9 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -79,7 +79,11 @@ class ObjectSerializer { * @return string the form string */ public function toFormValue($value) { - return $this->toString($value); + if ($value instanceof SplFileObject) { + return $value->getRealPath(); + } else { + return $this->toString($value); + } } /** @@ -104,7 +108,7 @@ class ObjectSerializer { * @param string $class class name is passed as a string * @return object an instance of $class */ - public function deserialize($data, $class) { + public function deserialize($data, $class, $httpHeader=null) { if (null === $data) { $deserialized = null; } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] @@ -129,6 +133,24 @@ class ObjectSerializer { } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; + } elseif ($class === 'SplFileObject') { + # determine temp folder path + if (!isset(Configuration::$tempFolderPath) || '' === Configuration::$tempFolderPath) { + $tmpFolderPath = sys_get_temp_dir(); + } else { + $tmpFolderPath = Configuration::tempFolderPath; + } + + # determine file name + if (preg_match('/Content-Disposition: inline; filename=(.*)/i', $httpHeader, $match)) { + $filename = $tmpFolderPath.$match[1]; + } else { + $filename = tempnam($tmpFolderPath, ''); + } + $deserialized = new \SplFileObject($filename, "w"); + $byte_written = $deserialized->fwrite($data); + error_log("[INFO] Written $byte_written to $filename. Please move the file to a proper folder for further processing and delete the temp afterwards", 3, Configuration::$debug_file); + } else { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { @@ -148,4 +170,4 @@ class ObjectSerializer { return $deserialized; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index fb0a6f99e7ca..367ba037d598 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -134,13 +134,13 @@ class {{classname}} { {{/authMethods}} // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}}); } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $httpHeader); $e->setResponseObject($data); break;{{/dataType}}{{/responses}} } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index b85ad289418c..687470669730 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -263,4 +263,18 @@ class Configuration { public static function setDefaultConfiguration(Configuration $config) { self::$defaultConfiguration = $config; } + + /* + * return the report for debuggin + */ + public static function toDebugReport() { + $report = "PHP SDK ({{invokerPackage}}) Debug Report:\n"; + $report .= " OS: ".php_uname()."\n"; + $report .= " PHP Version: ".phpversion()."\n"; + $report .= " Swagger Spec Version: {{version}}\n"; + $report .= " SDK Package Version: {{version}}\n"; + + return $report; + } + } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 35795bf8c0b7..1d241529538f 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -100,9 +100,9 @@ class {{classname}} implements ArrayAccess { public function __toString() { if (defined('JSON_PRETTY_PRINT')) { - return json_encode($this, JSON_PRETTY_PRINT); + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { - return json_encode($this); + return json_encode(get_object_vars($this)); } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index b6766d8d13f2..afbe1991690e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -110,7 +110,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -171,7 +171,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -231,13 +231,13 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, '\Swagger\Client\Model\Pet[]'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); $e->setResponseObject($data); break; } @@ -302,13 +302,13 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, '\Swagger\Client\Model\Pet[]'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); $e->setResponseObject($data); break; } @@ -375,9 +375,6 @@ class PetApi { $httpBody = $formParams; } - //TODO support oauth - - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); if (isset($apiKey)) { $headerParams['api_key'] = $apiKey; @@ -385,15 +382,18 @@ class PetApi { + + //TODO support oauth + // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, '\Swagger\Client\Model\Pet'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $httpHeader); $e->setResponseObject($data); break; } @@ -473,7 +473,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -544,7 +544,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -563,7 +563,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 string $file file to upload (required) + * @param \SplFileObject $file file to upload (required) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ @@ -619,7 +619,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 237ba3f1acf8..5c9d38a8b5e2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -109,13 +109,13 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, 'map[string,int]'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $httpHeader); $e->setResponseObject($data); break; } @@ -178,13 +178,13 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, '\Swagger\Client\Model\Order'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); $e->setResponseObject($data); break; } @@ -253,13 +253,13 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, '\Swagger\Client\Model\Order'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); $e->setResponseObject($data); break; } @@ -328,7 +328,7 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 1d0765bbb815..a95d93bb55e4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -107,7 +107,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -165,7 +165,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -223,7 +223,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -284,13 +284,13 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, 'string'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $httpHeader); $e->setResponseObject($data); break; } @@ -348,7 +348,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -412,13 +412,13 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, '\Swagger\Client\Model\User'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User'); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $httpHeader); $e->setResponseObject($data); break; } @@ -492,7 +492,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -556,7 +556,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callAPI($resourcePath, $method, + $response = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 66204f0c4f36..92d8c2aa1193 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -90,7 +90,7 @@ class ApiClient { * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { $headers = array(); @@ -174,6 +174,11 @@ class ApiClient { if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + // return raw body if response is a file + if ($responseType == 'SplFileObject') { + return array($http_body, $http_header); + } + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string $data = $http_body; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index a407fe4dd49b..f4ccef391ef7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -263,4 +263,18 @@ class Configuration { public static function setDefaultConfiguration(Configuration $config) { self::$defaultConfiguration = $config; } + + /* + * return the report for debuggin + */ + public static function toDebugReport() { + $report = "PHP SDK (Swagger\Client) Debug Report:\n"; + $report .= " OS: ".php_uname()."\n"; + $report .= " PHP Version: ".phpversion()."\n"; + $report .= " Swagger Spec Version: 1.0.0\n"; + $report .= " SDK Package Version: 1.0.0\n"; + + return $report; + } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 75aaf2eeeada..9995dccdd4e0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -119,9 +119,9 @@ class Category implements ArrayAccess { public function __toString() { if (defined('JSON_PRETTY_PRINT')) { - return json_encode($this, JSON_PRETTY_PRINT); + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { - return json_encode($this); + return json_encode(get_object_vars($this)); } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index c7a433c3d8c4..2e0386d0ed74 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -223,9 +223,9 @@ class Order implements ArrayAccess { public function __toString() { if (defined('JSON_PRETTY_PRINT')) { - return json_encode($this, JSON_PRETTY_PRINT); + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { - return json_encode($this); + return json_encode(get_object_vars($this)); } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index cbe27e1fce93..a7b259a2fbe8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -223,9 +223,9 @@ class Pet implements ArrayAccess { public function __toString() { if (defined('JSON_PRETTY_PRINT')) { - return json_encode($this, JSON_PRETTY_PRINT); + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { - return json_encode($this); + return json_encode(get_object_vars($this)); } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 3fd785f001bd..6e8ae3e27a1a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -119,9 +119,9 @@ class Tag implements ArrayAccess { public function __toString() { if (defined('JSON_PRETTY_PRINT')) { - return json_encode($this, JSON_PRETTY_PRINT); + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { - return json_encode($this); + return json_encode(get_object_vars($this)); } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 2bb31056bdef..b1e2d2b809ca 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -275,9 +275,9 @@ class User implements ArrayAccess { public function __toString() { if (defined('JSON_PRETTY_PRINT')) { - return json_encode($this, JSON_PRETTY_PRINT); + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { - return json_encode($this); + return json_encode(get_object_vars($this)); } } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 802a49bc01ad..d002b3368520 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -79,7 +79,11 @@ class ObjectSerializer { * @return string the form string */ public function toFormValue($value) { - return $this->toString($value); + if ($value instanceof SplFileObject) { + return $value->getRealPath(); + } else { + return $this->toString($value); + } } /** @@ -104,7 +108,7 @@ class ObjectSerializer { * @param string $class class name is passed as a string * @return object an instance of $class */ - public function deserialize($data, $class) { + public function deserialize($data, $class, $httpHeader=null) { if (null === $data) { $deserialized = null; } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] @@ -129,6 +133,24 @@ class ObjectSerializer { } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; + } elseif ($class === 'SplFileObject') { + # determine temp folder path + if (!isset(Configuration::$tempFolderPath) || '' === Configuration::$tempFolderPath) { + $tmpFolderPath = sys_get_temp_dir(); + } else { + $tmpFolderPath = Configuration::tempFolderPath; + } + + # determine file name + if (preg_match('/Content-Disposition: inline; filename=(.*)/i', $httpHeader, $match)) { + $filename = $tmpFolderPath.$match[1]; + } else { + $filename = tempnam($tmpFolderPath, ''); + } + $deserialized = new \SplFileObject($filename, "w"); + $byte_written = $deserialized->fwrite($data); + error_log("[INFO] Written $byte_written to $filename. Please move the file to a proper folder for further processing and delete the temp afterwards", 3, Configuration::$debug_file); + } else { $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { @@ -148,4 +170,4 @@ class ObjectSerializer { return $deserialized; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/apigen.neon b/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/apigen.neon deleted file mode 100644 index c067c2c290f2..000000000000 --- a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/apigen.neon +++ /dev/null @@ -1,5 +0,0 @@ -main: Contrib -title: php-coveralls -internal: yes -todo: yes -wipeout: yes diff --git a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpcs.xml b/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpcs.xml deleted file mode 100644 index 82a58e1b3244..000000000000 --- a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpcs.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - The coding standard for standard PHP application - */img/* - */images/* - */less/* - */css/* - */js/* - *.html - *.twig - *.yml - *.xml - *.txt - *.less - *.css - *.js - *.jpg - *.jpeg - *.png - *.gif - - - - - - - - - - - diff --git a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpmd.xml b/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpmd.xml deleted file mode 100644 index 27d3193e749f..000000000000 --- a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/build/config/phpmd.xml +++ /dev/null @@ -1,45 +0,0 @@ - - - - My custom rule set that checks my code... - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/travis/empty b/samples/client/petstore/php/SwaggerClient/vendor/satooshi/php-coveralls/travis/empty deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index f5383a9a4dc5..55aae557a234 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -19,7 +19,7 @@ try { //$pet_api = new SwaggerClient\PetAPI($api_client); $pet_api = new Swagger\Client\Api\PetAPI(); // test default header - $pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); + //$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); // return Pet (model) $response = $pet_api->getPetById($petId); // to test __toString() @@ -28,26 +28,26 @@ try { // add pet (post json) $new_pet_id = 10005; $new_pet = new Swagger\Client\Model\Pet; - $new_pet->id = $new_pet_id; - $new_pet->name = "PHP Unit Test"; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); // new tag $tag= new Swagger\Client\Model\Tag; - $tag->id = $new_pet_id; // use the same id as pet + $tag->setId($new_pet_id); // use the same id as pet //$tag->name = "test php tag"; // new category $category = new Swagger\Client\Model\Category; - $category->id = 0; // use the same id as pet + $category->setId(10005); // use the same id as pet //$category->name = "test php category"; - $new_pet->tags = array($tag); - $new_pet->category = $category; + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); $pet_api = new Swagger\Client\Api\PetAPI(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // test upload file (exception) - $upload_response = $pet_api->uploadFile($petId, "test meta", NULL); + //$upload_response = $pet_api->uploadFile($petId, "test meta", NULL); } catch (Swagger\Client\Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; From 7f31da734d94fd34d9d39070509d4ed536533190 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Jun 2015 20:50:57 +0800 Subject: [PATCH 54/62] add file response for php, update test case --- .../src/main/resources/php/ApiClient.mustache | 4 ++-- .../resources/php/ObjectSerializer.mustache | 4 ++-- .../src/main/resources/php/api.mustache | 2 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 16 ++++++------- .../SwaggerClient-php/lib/Api/StoreApi.php | 8 +++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 16 ++++++------- .../php/SwaggerClient-php/lib/ApiClient.php | 4 ++-- .../lib/ObjectSerializer.php | 4 ++-- .../SwaggerClient-php/tests/PetApiTest.php | 8 ++++--- .../SwaggerClient-php/tests/StoreApiTest.php | 24 +++++++++++++++++-- 10 files changed, 56 insertions(+), 34 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 3a4f8dfc8be3..b43c83dd8844 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -175,7 +175,7 @@ class ApiClient { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { // return raw body if response is a file - if ($responseType == 'SplFileObject') { + if ($responseType == '\SplFileObject') { return array($http_body, $http_header); } @@ -187,7 +187,7 @@ class ApiClient { throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", $response_info['http_code'], $http_header, $http_body); } - return $data; + return array($data, $http_header); } /* diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 26999668b9e9..8e433e6185bf 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -133,7 +133,7 @@ class ObjectSerializer { } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; - } elseif ($class === 'SplFileObject') { + } elseif ($class === '\SplFileObject') { # determine temp folder path if (!isset(Configuration::$tempFolderPath) || '' === Configuration::$tempFolderPath) { $tmpFolderPath = sys_get_temp_dir(); @@ -149,7 +149,7 @@ class ObjectSerializer { } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written to $filename. Please move the file to a proper folder for further processing and delete the temp afterwards", 3, Configuration::$debug_file); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); } else { $instance = new $class(); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 367ba037d598..dcbc8b4b3a61 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -134,7 +134,7 @@ class {{classname}} { {{/authMethods}} // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}}); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index afbe1991690e..64ef731c4b0f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -110,7 +110,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -171,7 +171,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -231,7 +231,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]'); } catch (ApiException $e) { @@ -302,7 +302,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]'); } catch (ApiException $e) { @@ -387,7 +387,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet'); } catch (ApiException $e) { @@ -473,7 +473,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -544,7 +544,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -619,7 +619,7 @@ class PetApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 5c9d38a8b5e2..c047182133d5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -109,7 +109,7 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, 'map[string,int]'); } catch (ApiException $e) { @@ -178,7 +178,7 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order'); } catch (ApiException $e) { @@ -253,7 +253,7 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order'); } catch (ApiException $e) { @@ -328,7 +328,7 @@ class StoreApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index a95d93bb55e4..d9f2a08ccb8f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -107,7 +107,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -165,7 +165,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -223,7 +223,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -284,7 +284,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, 'string'); } catch (ApiException $e) { @@ -348,7 +348,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -412,7 +412,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\User'); } catch (ApiException $e) { @@ -492,7 +492,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { @@ -556,7 +556,7 @@ class UserApi { // make the API Call try { - $response = $this->apiClient->callApi($resourcePath, $method, + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, $headerParams); } catch (ApiException $e) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 92d8c2aa1193..b47e104ec1e1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -175,7 +175,7 @@ class ApiClient { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { // return raw body if response is a file - if ($responseType == 'SplFileObject') { + if ($responseType == '\SplFileObject') { return array($http_body, $http_header); } @@ -187,7 +187,7 @@ class ApiClient { throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", $response_info['http_code'], $http_header, $http_body); } - return $data; + return array($data, $http_header); } /* diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index d002b3368520..59b7601d1407 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -133,7 +133,7 @@ class ObjectSerializer { } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; - } elseif ($class === 'SplFileObject') { + } elseif ($class === '\SplFileObject') { # determine temp folder path if (!isset(Configuration::$tempFolderPath) || '' === Configuration::$tempFolderPath) { $tmpFolderPath = sys_get_temp_dir(); @@ -149,7 +149,7 @@ class ObjectSerializer { } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written to $filename. Please move the file to a proper folder for further processing and delete the temp afterwards", 3, Configuration::$debug_file); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); } else { $instance = new $class(); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 3ac287722915..76c88d20c4e9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -10,9 +10,11 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // for error reporting (need to run with php5.3 to get no warning) //ini_set('display_errors', 1); //error_reporting(~0); - ini_set('display_startup_errors',1); - ini_set('display_errors',1); - error_reporting(-1); + // when running with php5.5, comment out below to skip the warning about + // using @ to handle file upload + //ini_set('display_startup_errors',1); + //ini_set('display_errors',1); + //error_reporting(-1); // enable debugging //Swagger\Client\Configuration::$debug = true; diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php index 05bd873c993d..fcba8adf20ad 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/StoreApiTest.php @@ -10,6 +10,27 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase // for error reporting (need to run with php5.3 to get no warning) //ini_set('display_errors', 1); //error_reporting(~0); + // new pet + $new_pet_id = 10005; + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); + $new_pet->setStatus("available"); + // new tag + $tag= new Swagger\Client\Model\Tag; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("test php tag"); + // new category + $category = new Swagger\Client\Model\Category; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("test php category"); + + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); + + $pet_api = new Swagger\Client\Api\PetAPI(); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); } // test get inventory @@ -22,8 +43,7 @@ class StoreApiTest extends \PHPUnit_Framework_TestCase // get inventory $get_response = $store_api->getInventory(); - $this->assertInternalType("int", $get_response['sold']); - $this->assertInternalType("int", $get_response['pending']); + $this->assertInternalType("int", $get_response['available']); } From 259b31ccd44d534cddbcd54af82354a8662dfdf5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 26 Jun 2015 23:55:51 +0800 Subject: [PATCH 55/62] temporary folder setting --- .../src/main/resources/php/ApiClient.mustache | 392 +++--- .../main/resources/php/ApiException.mustache | 92 +- .../resources/php/ObjectSerializer.mustache | 194 +-- .../src/main/resources/php/api.mustache | 252 ++-- .../src/main/resources/php/composer.mustache | 60 +- .../main/resources/php/configuration.mustache | 511 ++++---- .../src/main/resources/php/model.mustache | 148 +-- .../src/test/resources/2_0/petstore.json | 2 +- .../php/SwaggerClient-php/composer.json | 58 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 1165 ++++++++--------- .../SwaggerClient-php/lib/Api/StoreApi.php | 601 +++++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 1040 ++++++++------- .../php/SwaggerClient-php/lib/ApiClient.php | 392 +++--- .../SwaggerClient-php/lib/ApiException.php | 92 +- .../SwaggerClient-php/lib/Configuration.php | 532 ++++---- .../SwaggerClient-php/lib/Model/Category.php | 184 +-- .../php/SwaggerClient-php/lib/Model/Order.php | 390 +++--- .../php/SwaggerClient-php/lib/Model/Pet.php | 390 +++--- .../php/SwaggerClient-php/lib/Model/Tag.php | 184 +-- .../php/SwaggerClient-php/lib/Model/User.php | 494 +++---- .../lib/ObjectSerializer.php | 192 ++- samples/client/petstore/php/test.php | 3 + 22 files changed, 3697 insertions(+), 3671 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index b43c83dd8844..158c9c662c00 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -19,206 +19,206 @@ namespace {{invokerPackage}}; class ApiClient { - public static $PATCH = "PATCH"; - public static $POST = "POST"; - public static $GET = "GET"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; - - /** @var Configuration */ - protected $config; - - /** @var ObjectSerializer */ - protected $serializer; - - /** - * @param Configuration $config config for this ApiClient - */ - function __construct(Configuration $config = null) { - if ($config == null) { - $config = Configuration::getDefaultConfiguration(); + public static $PATCH = "PATCH"; + public static $POST = "POST"; + public static $GET = "GET"; + public static $PUT = "PUT"; + public static $DELETE = "DELETE"; + + /** @var Configuration */ + protected $config; + + /** @var ObjectSerializer */ + protected $serializer; + + /** + * @param Configuration $config config for this ApiClient + */ + function __construct(Configuration $config = null) { + if ($config == null) { + $config = Configuration::getDefaultConfiguration(); + } + + $this->config = $config; + $this->serializer = new ObjectSerializer(); + } + + /** + * get the config + * @return Configuration + */ + public function getConfig() { + return $this->config; + } + + /** + * get the serializer + * @return ObjectSerializer + */ + public function getSerializer() { + return $this->serializer; + } + + /** + * Get API key (with prefix if set) + * @param string $apiKey name of apikey + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) { + $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->config->getApiKey($apiKeyIdentifier); + + if (!isset($apiKey)) { + return null; + } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; + } else { + $keyWithPrefix = $apiKey; + } + + return $keyWithPrefix; } - $this->config = $config; - $this->serializer = new ObjectSerializer(); - } - - /** - * get the config - * @return Configuration - */ - public function getConfig() { - return $this->config; - } - - /** - * get the serializer - * @return ObjectSerializer - */ - public function getSerializer() { - return $this->serializer; - } - - /** - * Get API key (with prefix if set) - * @param string $apiKey name of apikey - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKey) { - $prefix = $this->config->getApiKeyPrefix($apiKey); - $apiKey = $this->config->getApiKey($apiKey); - - if (!isset($apiKey)) { - return null; - } - - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; - } - - return $keyWithPrefix; - } + /** + * @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 + * @throws \{{invokerPackage}}\ApiException on a non 2xx response + * @return mixed + */ + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - /** - * @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 - * @throws \{{invokerPackage}}\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - - $headers = array(); - - # construct the http header - $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; + $headers = array(); + + # construct the http header + $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); + + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + } + + // 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->serializer->sanitizeForSerialization($postData)); + } + + $url = $this->config->getHost() . $resourcePath; + + $curl = curl_init(); + // set timeout, if needed + if ($this->config->getCurlTimeout() != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); + } + // 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 ApiException('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); + + // Set user agent + curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); + + // debugging for curl + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); + + curl_setopt($curl, CURLOPT_VERBOSE, 1); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); + } else { + curl_setopt($curl, CURLOPT_VERBOSE, 0); + } + + // obtain the HTTP response headers + curl_setopt($curl, CURLOPT_HEADER, 1); + + // Make the request + $response = curl_exec($curl); + $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $http_header = substr($response, 0, $http_header_size); + $http_body = substr($response, $http_header_size); + $response_info = curl_getinfo($curl); + + // debug HTTP response body + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); + } + + // Handle the response + if ($response_info['http_code'] == 0) { + throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + // return raw body if response is a file + if ($responseType == '\SplFileObject') { + return array($http_body, $http_header); + } + + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + } else { + throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body); + } + return array($data, $http_header); } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { - $postData = http_build_query($postData); + + /* + * return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * @return string Accept (e.g. application/json) + */ + public static function selectHeaderAccept($accept) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + return NULL; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } } - else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); + + /* + * return the content type based on an array of content-type provided + * + * @param string[] content_type_array Array fo content-type + * @return string Content-Type (e.g. application/json) + */ + public static function selectHeaderContentType($content_type) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $content_type)) { + return 'application/json'; + } else { + return implode(',', $content_type); + } } - - $url = $this->config->getHost() . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->config->getCurlTimeout() != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); - } - // 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 ApiException('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); - - // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); - } else { - curl_setopt($curl, CURLOPT_VERBOSE, 0); - } - - // obtain the HTTP response headers - curl_setopt($curl, CURLOPT_HEADER, 1); - - // Make the request - $response = curl_exec($curl); - $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); - } - - // Handle the response - if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - // return raw body if response is a file - if ($responseType == '\SplFileObject') { - return array($http_body, $http_header); - } - - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body); - } - return array($data, $http_header); - } - - /* - * return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * @return string Accept (e.g. application/json) - */ - public static function selectHeaderAccept($accept) { - if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { - return NULL; - } elseif (preg_grep("/application\/json/i", $accept)) { - return 'application/json'; - } else { - return implode(',', $accept); - } - } - - /* - * return the content type based on an array of content-type provided - * - * @param string[] content_type_array Array fo content-type - * @return string Content-Type (e.g. application/json) - */ - public static function selectHeaderContentType($content_type) { - if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { - return 'application/json'; - } elseif (preg_grep("/application\/json/i", $content_type)) { - return 'application/json'; - } else { - return implode(',', $content_type); - } - } } diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index 6d5415f798d4..c57310ccece4 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -21,50 +21,50 @@ use \Exception; class ApiException extends Exception { - /** @var string The HTTP body of the server response. */ - protected $responseBody; - - /** @var string[] The HTTP header of the server response. */ - protected $responseHeaders; - - /** - * The deserialized response object - */ - protected $responseObject; - - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { - parent::__construct($message, $code); - $this->responseHeaders = $responseHeaders; - $this->responseBody = $responseBody; - } - - /** - * Get the HTTP response header - * - * @return string HTTP response header - */ - public function getResponseHeaders() { - return $this->responseHeaders; - } - - /** - * Get the HTTP response body - * - * @return string HTTP response body - */ - public function getResponseBody() { - return $this->responseBody; - } - - /** - * sets the deseralized response object (during deserialization) - * @param mixed $obj - */ - public function setResponseObject($obj) { - $this->responseObject = $obj; - } - - public function getResponseObject() { - return $this->responseObject; - } + /** @var string The HTTP body of the server response. */ + protected $responseBody; + + /** @var string[] The HTTP header of the server response. */ + protected $responseHeaders; + + /** + * The deserialized response object + */ + protected $responseObject; + + public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { + parent::__construct($message, $code); + $this->responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Get the HTTP response header + * + * @return string HTTP response header + */ + public function getResponseHeaders() { + return $this->responseHeaders; + } + + /** + * Get the HTTP response body + * + * @return string HTTP response body + */ + public function getResponseBody() { + return $this->responseBody; + } + + /** + * sets the deseralized response object (during deserialization) + * @param mixed $obj + */ + public function setResponseObject($obj) { + $this->responseObject = $obj; + } + + public function getResponseObject() { + return $this->responseObject; + } } diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 8e433e6185bf..4463236063a9 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -9,29 +9,29 @@ class ObjectSerializer { * @return string serialized form of $data */ public 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); + 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) { + $getter = $data::$getters[$property]; + if ($data->$getter() !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); + } + } + $sanitized = $values; + } else { + $sanitized = (string)$data; } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $getter = $data::$getters[$property]; - if ($data->$getter() !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - return $sanitized; + return $sanitized; } /** @@ -41,7 +41,7 @@ class ObjectSerializer { * @return string the serialized object */ public function toPathValue($value) { - return rawurlencode($this->toString($value)); + return rawurlencode($this->toString($value)); } /** @@ -53,11 +53,11 @@ class ObjectSerializer { * @return string the serialized object */ public function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $this->toString($object); - } + if (is_array($object)) { + return implode(',', $object); + } else { + return $this->toString($object); + } } /** @@ -68,7 +68,7 @@ class ObjectSerializer { * @return string the header string */ public function toHeaderValue($value) { - return $this->toString($value); + return $this->toString($value); } /** @@ -79,11 +79,11 @@ class ObjectSerializer { * @return string the form string */ public function toFormValue($value) { - if ($value instanceof SplFileObject) { - return $value->getRealPath(); - } else { - return $this->toString($value); - } + if ($value instanceof SplFileObject) { + return $value->getRealPath(); + } else { + return $this->toString($value); + } } /** @@ -94,11 +94,11 @@ class ObjectSerializer { * @return string the header string */ public function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } else { - return $value; - } + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } else { + return $value; + } } /** @@ -109,65 +109,65 @@ class ObjectSerializer { * @return object an instance of $class */ public function deserialize($data, $class, $httpHeader=null) { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = $this->deserialize($value, $subClass); - } + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = $this->deserialize($value, $subClass); + } + } + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); + $values = array(); + foreach ($data as $key => $value) { + $values[] = $this->deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + settype($data, $class); + $deserialized = $data; + } elseif ($class === '\SplFileObject') { + # determine temp folder path + if (!isset(Configuration::getDefaultConfig->$tempFolderPath) || '' === Configuration::$tempFolderPath) { + $tmpFolderPath = sys_get_temp_dir(); + } else { + $tmpFolderPath = Configuration::tempFolderPath; + } + + # determine file name + if (preg_match('/Content-Disposition: inline; filename=(.*)/i', $httpHeader, $match)) { + $filename = $tmpFolderPath.$match[1]; + } else { + $filename = tempnam($tmpFolderPath, ''); + } + $deserialized = new \SplFileObject($filename, "w"); + $byte_written = $deserialized->fwrite($data); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $propertySetter = $instance::$setters[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::$attributeMap[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter($this->deserialize($propertyValue, $type)); + } + } + $deserialized = $instance; } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { - $subClass = substr($class, 0, -2); - $values = array(); - foreach ($data as $key => $value) { - $values[] = $this->deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } elseif ($class === '\SplFileObject') { - # determine temp folder path - if (!isset(Configuration::$tempFolderPath) || '' === Configuration::$tempFolderPath) { - $tmpFolderPath = sys_get_temp_dir(); - } else { - $tmpFolderPath = Configuration::tempFolderPath; - } - - # determine file name - if (preg_match('/Content-Disposition: inline; filename=(.*)/i', $httpHeader, $match)) { - $filename = $tmpFolderPath.$match[1]; - } else { - $filename = tempnam($tmpFolderPath, ''); - } - $deserialized = new \SplFileObject($filename, "w"); - $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $propertySetter = $instance::$setters[$property]; - - if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { - continue; - } - - $propertyValue = $data->{$instance::$attributeMap[$property]}; - if (isset($propertyValue)) { - $instance->$propertySetter($this->deserialize($propertyValue, $type)); - } - } - $deserialized = $instance; - } - - return $deserialized; + + return $deserialized; } } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index dcbc8b4b3a61..5a97244bfe88 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -30,132 +30,132 @@ use \{{invokerPackage}}\ObjectSerializer; {{#operations}} class {{classname}} { - /** @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ - private $apiClient; - - /** - * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use - */ - function __construct($apiClient = null) { - if ($apiClient == null) { - $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('{{basePath}}'); - } - - $this->apiClient = $apiClient; - } - - /** - * @return \{{invokerPackage}}\ApiClient get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * @param \{{invokerPackage}}\ApiClient $apiClient set the API client - * @return {{classname}} - */ - public function setApiClient(ApiClient $apiClient) { - $this->apiClient = $apiClient; - return $this; - } - - {{#operation}} - /** - * {{{nickname}}} - * - * {{{summary}}} - * -{{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} -{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - * @throws \{{invokerPackage}}\ApiException on non-2xx response - */ - public function {{nickname}}({{#allParams}}${{paramName}}{{^required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if (${{paramName}} === null) { - throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); - } - {{/required}}{{/allParams}} - - // parse inputs - $resourcePath = "{{path}}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "{{httpMethod}}"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); - - {{#queryParams}}// query params - if(${{paramName}} !== null) { - $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); - }{{/queryParams}} - {{#headerParams}}// header params - if(${{paramName}} !== null) { - $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); - }{{/headerParams}} - {{#pathParams}}// path params - if(${{paramName}} !== null) { - $resourcePath = str_replace("{" . "{{baseName}}" . "}", - $this->apiClient->getSerializer()->toPathValue(${{paramName}}), - $resourcePath); - }{{/pathParams}} - {{#formParams}}// form params - if (${{paramName}} !== null) { - $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->getSerializer()->toFormValue(${{paramName}}); - }{{/formParams}} - {{#bodyParams}}// body params - $_tempBody = null; - if (isset(${{paramName}})) { - $_tempBody = ${{paramName}}; - }{{/bodyParams}} - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - {{#authMethods}}{{#isApiKey}} - $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); - if (isset($apiKey)) { - {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} - }{{/isApiKey}} - {{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->apiClient->getConfig()->getUsername().":".$this->apiClient->getConfig()->getPassword());{{/isBasic}} - {{#isOAuth}}//TODO support oauth{{/isOAuth}} - {{/authMethods}} - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}}); - } catch (ApiException $e) { - switch ($e->getCode()) { {{#responses}}{{#dataType}} - case {{code}}: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $httpHeader); - $e->setResponseObject($data); - break;{{/dataType}}{{/responses}} + /** @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ + private $apiClient; + + /** + * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('{{basePath}}'); } - - throw $e; - } - {{#returnType}} - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'{{returnType}}'); - return $responseObject; - {{/returnType}} - } - {{/operation}} + + $this->apiClient = $apiClient; + } + + /** + * @return \{{invokerPackage}}\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \{{invokerPackage}}\ApiClient $apiClient set the API client + * @return {{classname}} + */ + public function setApiClient(ApiClient $apiClient) { + $this->apiClient = $apiClient; + return $this; + } + + {{#operation}} + /** + * {{{nickname}}} + * + * {{{summary}}} + * + {{#allParams}} * @param {{dataType}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} + {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + * @throws \{{invokerPackage}}\ApiException on non-2xx response + */ + public function {{nickname}}({{#allParams}}${{paramName}}{{^required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if (${{paramName}} === null) { + throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); +>>>>>>> temporary folder setting + } + {{/required}}{{/allParams}} + + // parse inputs + $resourcePath = "{{path}}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "{{httpMethod}}"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); + + {{#queryParams}}// query params + if(${{paramName}} !== null) { + $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); + }{{/queryParams}} + {{#headerParams}}// header params + if(${{paramName}} !== null) { + $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); + }{{/headerParams}} + {{#pathParams}}// path params + if(${{paramName}} !== null) { + $resourcePath = str_replace("{" . "{{baseName}}" . "}", + $this->apiClient->getSerializer()->toPathValue(${{paramName}}), + $resourcePath); + }{{/pathParams}} + {{#formParams}}// form params + if (${{paramName}} !== null) { + $formParams['{{baseName}}'] = {{#isFile}}'@' . {{/isFile}}$this->apiClient->getSerializer()->toFormValue(${{paramName}}); + }{{/formParams}} + {{#bodyParams}}// body params + $_tempBody = null; + if (isset(${{paramName}})) { + $_tempBody = ${{paramName}}; + }{{/bodyParams}} + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + {{#authMethods}}{{#isApiKey}} + $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); + if (isset($apiKey)) { + {{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $apiKey;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $apiKey;{{/isKeyInQuery}} + }{{/isApiKey}} + {{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode($this->apiClient->getConfig()->getUsername().":".$this->apiClient->getConfig()->getPassword());{{/isBasic}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + {{/authMethods}} + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}}); + } catch (ApiException $e) { + switch ($e->getCode()) { {{#responses}}{{#dataType}} + case {{code}}: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $httpHeader); + $e->setResponseObject($data); + break;{{/dataType}}{{/responses}} + } + + throw $e; + } + {{#returnType}} + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'{{returnType}}'); + {{/returnType}} + } + {{/operation}} } {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/php/composer.mustache b/modules/swagger-codegen/src/main/resources/php/composer.mustache index d36267617c4d..52425899ce74 100644 --- a/modules/swagger-codegen/src/main/resources/php/composer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/composer.mustache @@ -1,33 +1,33 @@ { - "name": "{{groupId}}/{{artifactId}}",{{#artifactVersion}} - "version": "{{artifactVersion}}",{{/artifactVersion}} - "description": "{{description}}", - "keywords": [ - "swagger", - "php", - "sdk", - "api" - ], - "homepage": "http://swagger.io", - "license": "Apache v2", - "authors": [ - { - "name": "Swagger and contributors", - "homepage": "https://github.com/swagger-api/swagger-codegen" + "name": "{{groupId}}/{{artifactId}}",{{#artifactVersion}} + "version": "{{artifactVersion}}",{{/artifactVersion}} + "description": "{{description}}", + "keywords": [ + "swagger", + "php", + "sdk", + "api" + ], + "homepage": "http://swagger.io", + "license": "Apache v2", + "authors": [ + { + "name": "Swagger and contributors", + "homepage": "https://github.com/swagger-api/swagger-codegen" + } + ], + "require": { + "php": ">=5.3.3", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*" + }, + "require-dev": { + "phpunit/phpunit": "~4.0", + "satooshi/php-coveralls": "~0.6.1", + "squizlabs/php_codesniffer": "~2.0" + }, + "autoload": { + "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } } - ], - "require": { - "php": ">=5.3.3", - "ext-curl": "*", - "ext-json": "*", - "ext-mbstring": "*" - }, - "require-dev": { - "phpunit/phpunit": "~4.0", - "satooshi/php-coveralls": "~0.6.1", - "squizlabs/php_codesniffer": "~2.0" - }, - "autoload": { - "psr-4": { "{{escapedInvokerPackage}}\\" : "{{srcBasePath}}/" } - } } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 687470669730..94e0165b4a83 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -19,262 +19,265 @@ namespace {{invokerPackage}}; class Configuration { - private static $defaultConfiguration = null; - - /** @var string[] Associate array to store API key(s) */ - protected $apiKeys = array(); - - /** string[] Associate array to store API prefix (e.g. Bearer) */ - protected $apiKeyPrefixes = array(); - - /** @var string Username for HTTP basic authentication */ - protected $username = ''; - - /** @var string Password for HTTP basic authentication */ - protected $password = ''; - - /** @var \{{invokerPackage}}\ApiClient The default instance of ApiClient */ - protected $defaultHeaders = array(); - - /** @var string The host */ - protected $host = 'http://localhost'; - - /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ - protected $curlTimeout = 0; - - /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ - protected $userAgent = "PHP-Swagger"; - - /** @var bool Debug switch (default set to false) */ - protected $debug = false; - - /** @var string Debug file location (log to STDOUT by default) */ - protected $debugFile = 'php://output'; - - /** - * @param string $key - * @param string $value - * @return Configuration - */ - public function setApiKey($key, $value) { - $this->apiKeys[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKey($key) { - return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; - } - - /** - * @param string $key - * @param string $value - * @return Configuration - */ - public function setApiKeyPrefix($key, $value) { - $this->apiKeyPrefixes[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKeyPrefix($key) { - return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; - } - - /** - * @param string $username - * @return Configuration - */ - public function setUsername($username) { - $this->username = $username; - return $this; - } - - /** - * @return string - */ - public function getUsername() { - return $this->username; - } - - /** - * @param string $password - * @return Configuration - */ - public function setPassword($password) { - $this->password = $password; - return $this; - } - - /** - * @return string - */ - public function getPassword() { - return $this->password; - } - - /** - * add default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * @return ApiClient - */ - public function addDefaultHeader($headerName, $headerValue) { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); + private static $defaultConfiguration = null; + + /** @var string[] Associate array to store API key(s) */ + protected $apiKeys = array(); + + /** string[] Associate array to store API prefix (e.g. Bearer) */ + protected $apiKeyPrefixes = array(); + + /** @var string Username for HTTP basic authentication */ + protected $username = ''; + + /** @var string Password for HTTP basic authentication */ + protected $password = ''; + + /** @var \{{invokerPackage}}\ApiClient The default instance of ApiClient */ + protected $defaultHeaders = array(); + + /** @var string The host */ + protected $host = 'http://localhost'; + + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ + protected $curlTimeout = 0; + + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ + protected $userAgent = "PHP-Swagger"; + + /** @var bool Debug switch (default set to false) */ + protected $debug = false; + + /** @var string Debug file location (log to STDOUT by default) */ + protected $debugFile = 'php://output'; + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; } - - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * get the default header - * - * @return array default header - */ - public function getDefaultHeaders() { - return $this->defaultHeaders; - } - - /** - * delete a default header - * @param string $headerName the header to delete - * @return Configuration - */ - public function deleteDefaultHeader($headerName) { - unset($this->defaultHeaders[$headerName]); - } - - /** - * @param string $host - * @return Configuration - */ - public function setHost($host) { - $this->host = $host; - return $this; - } - - /** - * @return string - */ - public function getHost() { - return $this->host; - } - - /** - * set the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * @return ApiClient - */ - public function setUserAgent($userAgent) { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); + + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; } - - $this->userAgent = $userAgent; - return $this; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() { - return $this->userAgent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * @return ApiClient - */ - public function setCurlTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; } - - $this->curlTimeout = $seconds; - return $this; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getCurlTimeout() { - return $this->curlTimeout; - } - - /** - * @param bool $debug - * @return Configuration - */ - public function setDebug($debug) { - $this->debug = $debug; - return $this; - } - - /** - * @return bool - */ - public function getDebug() { - return $this->debug; - } - - /** - * @param string $debugFile - * @return Configuration - */ - public function setDebugFile($debugFile) { - $this->debugFile = $debugFile; - return $this; - } - - /** - * @return string - */ - public function getDebugFile() { - return $this->debugFile; - } - - /** - * @return Configuration - */ - public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { - return new Configuration(); + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; } - - return self::$defaultConfiguration; - } - - public static function setDefaultConfiguration(Configuration $config) { - self::$defaultConfiguration = $config; - } - - /* - * return the report for debuggin - */ - public static function toDebugReport() { - $report = "PHP SDK ({{invokerPackage}}) Debug Report:\n"; - $report .= " OS: ".php_uname()."\n"; - $report .= " PHP Version: ".phpversion()."\n"; - $report .= " Swagger Spec Version: {{version}}\n"; - $report .= " SDK Package Version: {{version}}\n"; - - return $report; - } - + + /** + * @param string $username + * @return Configuration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return Configuration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * delete a default header + * @param string $headerName the header to delete + * @return Configuration + */ + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); + } + + /** + * @param string $host + * @return Configuration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + public function setCurlTimeout($seconds) { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + } + + $this->curlTimeout = $seconds; + return $this; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + + /** + * @param bool $debug + * @return Configuration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @return Configuration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new Configuration(); + } + + return self::$defaultConfiguration; + } + + /** + * @param Configuration $config + */ + public static function setDefaultConfiguration(Configuration $config) { + self::$defaultConfiguration = $config; + } + + /* + * return the report for debugging + */ + public static function toDebugReport() { + $report = "PHP SDK ({{invokerPackage}}) Debug Report:\n"; + $report .= " OS: ".php_uname()."\n"; + $report .= " PHP Version: ".phpversion()."\n"; + $report .= " Swagger Spec Version: {{version}}\n"; + $report .= " SDK Package Version: {{version}}\n"; + + return $report; + } + } diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 1d241529538f..9b8307f6ec47 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -29,82 +29,82 @@ namespace {{modelPackage}}; use \ArrayAccess; class {{classname}} implements ArrayAccess { - /** @var string[] Array of property to type mappings. Used for (de)serialization */ - static $swaggerTypes = array( - {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - ); - - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ - static $attributeMap = array( - {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - ); - - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ - static $setters = array( - {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - ); - - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ - static $getters = array( - {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} - ); - - {{#vars}} - /** @var {{datatype}} ${{name}} {{#description}}{{{description}}} {{/description}}*/ - protected ${{name}}; - {{/vars}} - public function __construct(array $data = null) { - if ($data != null) { - {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} - {{/hasMore}}{{/vars}} + /** @var string[] Array of property to type mappings. Used for (de)serialization */ + static $swaggerTypes = array( + {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + static $attributeMap = array( + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} + ); + + {{#vars}} + /** @var {{datatype}} ${{name}} {{#description}}{{{description}}} {{/description}}*/ + protected ${{name}}; + {{/vars}} + public function __construct(array $data = null) { + if ($data != null) { + {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} + {{/hasMore}}{{/vars}} + } } - } - {{#vars}} - /** - * get {{name}} - * @return {{datatype}} - */ - public function {{getter}}() { - return $this->{{name}}; - } - - /** - * set {{name}} - * @param {{datatype}} ${{name}} - * @return $this - */ - public function {{setter}}(${{name}}) { - $this->{{name}} = ${{name}}; - return $this; - } - {{/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); - } - - public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); - } else { - return json_encode(get_object_vars($this)); + {{#vars}} + /** + * get {{name}} + * @return {{datatype}} + */ + public function {{getter}}() { + return $this->{{name}}; + } + + /** + * set {{name}} + * @param {{datatype}} ${{name}} + * @return $this + */ + public function {{setter}}(${{name}}) { + $this->{{name}} = ${{name}}; + return $this; + } + {{/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); + } + + public function __toString() { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); + } else { + return json_encode(get_object_vars($this)); + } } - } } {{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 66762d74b2bc..df781a90c494 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -235,7 +235,7 @@ "200": { "description": "successful operation", "schema": { - "$ref": "#/definitions/Pet" + "type": "file" } }, "400": { diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index db0fe7cd5b93..5a76d804876b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -1,32 +1,32 @@ { - "name": "swagger/swagger-client", - "description": "", - "keywords": [ - "swagger", - "php", - "sdk", - "api" - ], - "homepage": "http://swagger.io", - "license": "Apache v2", - "authors": [ - { - "name": "Swagger and contributors", - "homepage": "https://github.com/swagger-api/swagger-codegen" + "name": "swagger/swagger-client", + "description": "", + "keywords": [ + "swagger", + "php", + "sdk", + "api" + ], + "homepage": "http://swagger.io", + "license": "Apache v2", + "authors": [ + { + "name": "Swagger and contributors", + "homepage": "https://github.com/swagger-api/swagger-codegen" + } + ], + "require": { + "php": ">=5.3.3", + "ext-curl": "*", + "ext-json": "*", + "ext-mbstring": "*" + }, + "require-dev": { + "phpunit/phpunit": "~4.0", + "satooshi/php-coveralls": "~0.6.1", + "squizlabs/php_codesniffer": "~2.0" + }, + "autoload": { + "psr-4": { "Swagger\\Client\\" : "lib/" } } - ], - "require": { - "php": ">=5.3.3", - "ext-curl": "*", - "ext-json": "*", - "ext-mbstring": "*" - }, - "require-dev": { - "phpunit/phpunit": "~4.0", - "satooshi/php-coveralls": "~0.6.1", - "squizlabs/php_codesniffer": "~2.0" - }, - "autoload": { - "psr-4": { "Swagger\\Client\\" : "lib/" } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 64ef731c4b0f..54926f3c9f74 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -29,606 +29,603 @@ use \Swagger\Client\ObjectSerializer; class PetApi { - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ - private $apiClient; - - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use - */ - function __construct($apiClient = null) { - if ($apiClient == null) { - $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + /** @var \Swagger\Client\ApiClient instance of the ApiClient */ + private $apiClient; + + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; } - - $this->apiClient = $apiClient; - } - - /** - * @return \Swagger\Client\ApiClient get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * @param \Swagger\Client\ApiClient $apiClient set the API client - * @return PetApi - */ - public function setApiClient(ApiClient $apiClient) { - $this->apiClient = $apiClient; - return $this; - } - - /** - * updatePet - * - * Update an existing pet - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function updatePet($body) { - - - // parse inputs - $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + /** + * @return \Swagger\Client\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return PetApi + */ + public function setApiClient(ApiClient $apiClient) { + $this->apiClient = $apiClient; + return $this; + } + + + /** + * updatePet + * + * Update an existing pet + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updatePet($body) { + + + // parse inputs + $resourcePath = "/pet"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "PUT"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; } - - throw $e; - } - - } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); - /** - * addPet - * - * Add a new pet to the store - * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function addPet($body) { - - - // parse inputs - $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; } - - throw $e; - } - - } - /** - * findPetsByStatus - * - * Finds Pets by status - * - * @param string[] $status Status values that need to be considered for filter (required) - * @return \Swagger\Client\Model\Pet[] - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function findPetsByStatus($status) { - - - // parse inputs - $resourcePath = "/pet/findByStatus"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - // query params - if($status !== null) { - $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); - } - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); - $e->setResponseObject($data); - break; + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); - return $responseObject; - - } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } - /** - * findPetsByTags - * - * Finds Pets by tags - * - * @param string[] $tags Tags to filter by (required) - * @return \Swagger\Client\Model\Pet[] - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function findPetsByTags($tags) { - - - // parse inputs - $resourcePath = "/pet/findByTags"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - // query params - if($tags !== null) { - $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); - } - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); - $e->setResponseObject($data); - break; + throw $e; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); - return $responseObject; - - } + + } + + /** + * addPet + * + * Add a new pet to the store + * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function addPet($body) { + - /** - * getPetById - * - * Find pet by ID - * - * @param int $pet_id ID of pet that needs to be fetched (required) - * @return \Swagger\Client\Model\Pet - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getPetById($pet_id) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (isset($apiKey)) { - $headerParams['api_key'] = $apiKey; - } - - - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $httpHeader); - $e->setResponseObject($data); - break; + // parse inputs + $resourcePath = "/pet"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet'); - return $responseObject; - - } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/json','application/xml')); - /** - * 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 - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function updatePetWithForm($pet_id, $name, $status) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/x-www-form-urlencoded')); - - - - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); - } - // form params - if ($name !== null) { - $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); - }// form params - if ($status !== null) { - $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); - } - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; } - - throw $e; - } - - } - /** - * deletePet - * - * Deletes a pet - * - * @param string $api_key (required) - * @param int $pet_id Pet id to delete (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function deletePet($api_key, $pet_id) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - // header params - if($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); - } - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } - - throw $e; - } - - } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } - /** - * 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 \SplFileObject $file file to upload (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function uploadFile($pet_id, $additional_metadata, $file) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}/uploadImage"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('multipart/form-data')); - - - - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); - } - // form params - if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); - }// form params - if ($file !== null) { - $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); - } - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - - //TODO support oauth - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + throw $e; } - - throw $e; - } - - } + + } + + /** + * findPetsByStatus + * + * Finds Pets by status + * + * @param string[] $status Status values that need to be considered for filter (required) + * @return \Swagger\Client\Model\Pet[] + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function findPetsByStatus($status) { + + // parse inputs + $resourcePath = "/pet/findByStatus"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + // query params + if($status !== null) { + $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); + } + + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Pet[]'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); + + } + + /** + * findPetsByTags + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @return \Swagger\Client\Model\Pet[] + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function findPetsByTags($tags) { + + + // parse inputs + $resourcePath = "/pet/findByTags"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + // query params + if($tags !== null) { + $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); + } + + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Pet[]'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); + + } + + /** + * getPetById + * + * Find pet by ID + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return \SplFileObject + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getPetById($pet_id) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); + } + + + // parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + // path params + if($pet_id !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); + } + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\SplFileObject'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\SplFileObject', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'\SplFileObject'); + + } + + /** + * 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 + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updatePetWithForm($pet_id, $name, $status) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); + } + + + // parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('application/x-www-form-urlencoded')); + + + + // path params + if($pet_id !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); + } + // form params + if ($name !== null) { + $formParams['name'] = $this->apiClient->getSerializer()->toFormValue($name); + }// form params + if ($status !== null) { + $formParams['status'] = $this->apiClient->getSerializer()->toFormValue($status); + } + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + + /** + * deletePet + * + * Deletes a pet + * + * @param string $api_key (required) + * @param int $pet_id Pet id to delete (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deletePet($api_key, $pet_id) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); + } + + + // parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + // header params + if($api_key !== null) { + $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); + } + // path params + if($pet_id !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); + } + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + + /** + * 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 \SplFileObject $file file to upload (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function uploadFile($pet_id, $additional_metadata, $file) { + + // verify the required parameter 'pet_id' is set + if ($pet_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); + } + + + // parse inputs + $resourcePath = "/pet/{petId}/uploadImage"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array('multipart/form-data')); + + + + // path params + if($pet_id !== null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath); + } + // form params + if ($additional_metadata !== null) { + $formParams['additionalMetadata'] = $this->apiClient->getSerializer()->toFormValue($additional_metadata); + }// form params + if ($file !== null) { + $formParams['file'] = '@' . $this->apiClient->getSerializer()->toFormValue($file); + } + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + + //TODO support oauth + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index c047182133d5..a132b3e3ef5d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -29,315 +29,312 @@ use \Swagger\Client\ObjectSerializer; class StoreApi { - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ - private $apiClient; - - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use - */ - function __construct($apiClient = null) { - if ($apiClient == null) { - $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + /** @var \Swagger\Client\ApiClient instance of the ApiClient */ + private $apiClient; + + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; } - - $this->apiClient = $apiClient; - } - - /** - * @return \Swagger\Client\ApiClient get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * @param \Swagger\Client\ApiClient $apiClient set the API client - * @return StoreApi - */ - public function setApiClient(ApiClient $apiClient) { - $this->apiClient = $apiClient; - return $this; - } - - /** - * getInventory - * - * Returns pet inventories by status - * - * @return map[string,int] - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getInventory() { - - - // parse inputs - $resourcePath = "/store/inventory"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (isset($apiKey)) { - $headerParams['api_key'] = $apiKey; - } - - - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, 'map[string,int]'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $httpHeader); - $e->setResponseObject($data); - break; + /** + * @return \Swagger\Client\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return StoreApi + */ + public function setApiClient(ApiClient $apiClient) { + $this->apiClient = $apiClient; + return $this; + } + + + /** + * getInventory + * + * Returns pet inventories by status + * + * @return map[string,int] + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getInventory() { + + + // parse inputs + $resourcePath = "/store/inventory"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'map[string,int]'); - return $responseObject; - - } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - /** - * placeOrder - * - * Place an order for a pet - * - * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) - * @return \Swagger\Client\Model\Order - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function placeOrder($body) { - - - // parse inputs - $resourcePath = "/store/order"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); - $e->setResponseObject($data); - break; + + + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); - return $responseObject; - - } - - /** - * getOrderById - * - * Find purchase order by ID - * - * @param string $order_id ID of pet that needs to be fetched (required) - * @return \Swagger\Client\Model\Order - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getOrderById($order_id) { - - // verify the required parameter 'order_id' is set - if ($order_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); - } - - - // parse inputs - $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - if($order_id !== null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); - $e->setResponseObject($data); - break; + + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); - return $responseObject; - - } + + + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, 'map[string,int]'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $httpHeader); + $e->setResponseObject($data); + break; + } - /** - * deleteOrder - * - * Delete purchase order by ID - * - * @param string $order_id ID of the order that needs to be deleted (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function deleteOrder($order_id) { - - // verify the required parameter 'order_id' is set - if ($order_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); - } - - - // parse inputs - $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - if($order_id !== null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + throw $e; + } + + if (!$response) { + return null; } - - throw $e; - } - - } + return $this->apiClient->getSerializer()->deserialize($response,'map[string,int]'); + + } + + /** + * placeOrder + * + * Place an order for a pet + * + * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function placeOrder($body) { + + + // parse inputs + $resourcePath = "/store/order"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Order'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); + + } + + /** + * getOrderById + * + * Find purchase order by ID + * + * @param string $order_id ID of pet that needs to be fetched (required) + * @return \Swagger\Client\Model\Order + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getOrderById($order_id) { + + // verify the required parameter 'order_id' is set + if ($order_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); + } + + + // parse inputs + $resourcePath = "/store/order/{orderId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + // path params + if($order_id !== null) { + $resourcePath = str_replace("{" . "orderId" . "}", + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath); + } + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Order'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); + + } + + /** + * deleteOrder + * + * Delete purchase order by ID + * + * @param string $order_id ID of the order that needs to be deleted (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deleteOrder($order_id) { + + // verify the required parameter 'order_id' is set + if ($order_id === null) { + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); + } + + + // parse inputs + $resourcePath = "/store/order/{orderId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + // path params + if($order_id !== null) { + $resourcePath = str_replace("{" . "orderId" . "}", + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath); + } + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index d9f2a08ccb8f..62204e182e79 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -29,543 +29,541 @@ use \Swagger\Client\ObjectSerializer; class UserApi { - /** @var \Swagger\Client\ApiClient instance of the ApiClient */ - private $apiClient; - - /** - * @param \Swagger\Client\ApiClient|null $apiClient The api client to use - */ - function __construct($apiClient = null) { - if ($apiClient == null) { - $apiClient = new ApiClient(); - $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + /** @var \Swagger\Client\ApiClient instance of the ApiClient */ + private $apiClient; + + /** + * @param \Swagger\Client\ApiClient|null $apiClient The api client to use + */ + function __construct($apiClient = null) { + if ($apiClient == null) { + $apiClient = new ApiClient(); + $apiClient->getConfig()->setHost('http://petstore.swagger.io/v2'); + } + + $this->apiClient = $apiClient; } - - $this->apiClient = $apiClient; - } - - /** - * @return \Swagger\Client\ApiClient get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * @param \Swagger\Client\ApiClient $apiClient set the API client - * @return UserApi - */ - public function setApiClient(ApiClient $apiClient) { - $this->apiClient = $apiClient; - return $this; - } - - /** - * createUser - * - * Create user - * - * @param \Swagger\Client\Model\User $body Created user object (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function createUser($body) { - - - // parse inputs - $resourcePath = "/user"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + /** + * @return \Swagger\Client\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \Swagger\Client\ApiClient $apiClient set the API client + * @return UserApi + */ + public function setApiClient(ApiClient $apiClient) { + $this->apiClient = $apiClient; + return $this; + } + + + /** + * createUser + * + * Create user + * + * @param \Swagger\Client\Model\User $body Created user object (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function createUser($body) { + + + // parse inputs + $resourcePath = "/user"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; } - - throw $e; - } - - } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - /** - * createUsersWithArrayInput - * - * Creates list of users with given input array - * - * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function createUsersWithArrayInput($body) { - - - // parse inputs - $resourcePath = "/user/createWithArray"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; } - - throw $e; - } - - } - /** - * createUsersWithListInput - * - * Creates list of users with given input array - * - * @param \Swagger\Client\Model\User[] $body List of user object (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function createUsersWithListInput($body) { - - - // parse inputs - $resourcePath = "/user/createWithList"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } - - throw $e; - } - - } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } - /** - * 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 - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function loginUser($username, $password) { - - - // parse inputs - $resourcePath = "/user/login"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - // query params - if($username !== null) { - $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); - }// query params - if($password !== null) { - $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); - } - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, 'string'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $httpHeader); - $e->setResponseObject($data); - break; + throw $e; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'string'); - return $responseObject; - - } + + } + + /** + * createUsersWithArrayInput + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $body List of user object (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function createUsersWithArrayInput($body) { + - /** - * logoutUser - * - * Logs out current logged in user session - * - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function logoutUser() { - - - // parse inputs - $resourcePath = "/user/logout"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + // parse inputs + $resourcePath = "/user/createWithArray"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; } - - throw $e; - } - - } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - /** - * getUserByName - * - * Get user by user name - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @return \Swagger\Client\Model\User - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function getUserByName($username) { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); - } - - - // parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\User'); - } catch (ApiException $e) { - switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $httpHeader); - $e->setResponseObject($data); - break; + + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; } - - throw $e; - } - - if (!$response) { - return null; - } - - $responseObject = $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\User'); - return $responseObject; - - } - /** - * updateUser - * - * Updated user - * - * @param string $username name that need to be deleted (required) - * @param \Swagger\Client\Model\User $body Updated user object (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function updateUser($username, $body) { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); - } - - - // parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath); - } - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; } - - throw $e; - } - - } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } - /** - * deleteUser - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @return void - * @throws \Swagger\Client\ApiException on non-2xx response - */ - public function deleteUser($username) { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); - } - - - // parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); - - - - // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); - } catch (ApiException $e) { - switch ($e->getCode()) { + throw $e; } - - throw $e; - } - - } + + } + + /** + * createUsersWithListInput + * + * Creates list of users with given input array + * + * @param \Swagger\Client\Model\User[] $body List of user object (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function createUsersWithListInput($body) { + + // parse inputs + $resourcePath = "/user/createWithList"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + + /** + * 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 + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function loginUser($username, $password) { + + + // parse inputs + $resourcePath = "/user/login"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + // query params + if($username !== null) { + $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); + }// query params + if($password !== null) { + $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); + } + + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, 'string'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'string'); + + } + + /** + * logoutUser + * + * Logs out current logged in user session + * + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function logoutUser() { + + + // parse inputs + $resourcePath = "/user/logout"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + + /** + * getUserByName + * + * Get user by user name + * + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @return \Swagger\Client\Model\User + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function getUserByName($username) { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); + } + + + // parse inputs + $resourcePath = "/user/{username}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "GET"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + // path params + if($username !== null) { + $resourcePath = str_replace("{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); + } + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\User'); + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $httpHeader); + $e->setResponseObject($data); + break; + } + + throw $e; + } + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\User'); + + } + + /** + * updateUser + * + * Updated user + * + * @param string $username name that need to be deleted (required) + * @param \Swagger\Client\Model\User $body Updated user object (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function updateUser($username, $body) { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); + } + + + // parse inputs + $resourcePath = "/user/{username}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "PUT"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + // path params + if($username !== null) { + $resourcePath = str_replace("{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); + } + + // body params + $_tempBody = null; + if (isset($body)) { + $_tempBody = $body; + } + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + + /** + * deleteUser + * + * Delete user + * + * @param string $username The name that needs to be deleted (required) + * @return void + * @throws \Swagger\Client\ApiException on non-2xx response + */ + public function deleteUser($username) { + + // verify the required parameter 'username' is set + if ($username === null) { + throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); + } + + + // parse inputs + $resourcePath = "/user/{username}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $httpBody = ''; + $queryParams = array(); + $headerParams = array(); + $formParams = array(); + $_header_accept = ApiClient::selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { + $headerParams['Accept'] = $_header_accept; + } + $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); + + + + // path params + if($username !== null) { + $resourcePath = str_replace("{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath); + } + + + + // for model (json/xml) + if (isset($_tempBody)) { + $httpBody = $_tempBody; // $_tempBody is the method argument, if present + } else if (count($formParams) > 0) { + // for HTTP post (form) + $httpBody = $formParams; + } + + // make the API Call + try { + list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, + $queryParams, $httpBody, + $headerParams); + } catch (ApiException $e) { + switch ($e->getCode()) { + } + + throw $e; + } + + } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index b47e104ec1e1..1f466389cfdb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -19,206 +19,206 @@ namespace Swagger\Client; class ApiClient { - public static $PATCH = "PATCH"; - public static $POST = "POST"; - public static $GET = "GET"; - public static $PUT = "PUT"; - public static $DELETE = "DELETE"; - - /** @var Configuration */ - protected $config; - - /** @var ObjectSerializer */ - protected $serializer; - - /** - * @param Configuration $config config for this ApiClient - */ - function __construct(Configuration $config = null) { - if ($config == null) { - $config = Configuration::getDefaultConfiguration(); + public static $PATCH = "PATCH"; + public static $POST = "POST"; + public static $GET = "GET"; + public static $PUT = "PUT"; + public static $DELETE = "DELETE"; + + /** @var Configuration */ + protected $config; + + /** @var ObjectSerializer */ + protected $serializer; + + /** + * @param Configuration $config config for this ApiClient + */ + function __construct(Configuration $config = null) { + if ($config == null) { + $config = Configuration::getDefaultConfiguration(); + } + + $this->config = $config; + $this->serializer = new ObjectSerializer(); + } + + /** + * get the config + * @return Configuration + */ + public function getConfig() { + return $this->config; + } + + /** + * get the serializer + * @return ObjectSerializer + */ + public function getSerializer() { + return $this->serializer; + } + + /** + * Get API key (with prefix if set) + * @param string $apiKey name of apikey + * @return string API key with the prefix + */ + public function getApiKeyWithPrefix($apiKeyIdentifier) { + $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); + $apiKey = $this->config->getApiKey($apiKeyIdentifier); + + if (!isset($apiKey)) { + return null; + } + + if (isset($prefix)) { + $keyWithPrefix = $prefix." ".$apiKey; + } else { + $keyWithPrefix = $apiKey; + } + + return $keyWithPrefix; } - $this->config = $config; - $this->serializer = new ObjectSerializer(); - } - - /** - * get the config - * @return Configuration - */ - public function getConfig() { - return $this->config; - } - - /** - * get the serializer - * @return ObjectSerializer - */ - public function getSerializer() { - return $this->serializer; - } - - /** - * Get API key (with prefix if set) - * @param string $apiKey name of apikey - * @return string API key with the prefix - */ - public function getApiKeyWithPrefix($apiKey) { - $prefix = $this->config->getApiKeyPrefix($apiKey); - $apiKey = $this->config->getApiKey($apiKey); - - if (!isset($apiKey)) { - return null; - } - - if (isset($prefix)) { - $keyWithPrefix = $prefix." ".$apiKey; - } else { - $keyWithPrefix = $apiKey; - } - - return $keyWithPrefix; - } + /** + * @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 + * @throws \Swagger\Client\ApiException on a non 2xx response + * @return mixed + */ + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - /** - * @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 - * @throws \Swagger\Client\ApiException on a non 2xx response - * @return mixed - */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - - $headers = array(); - - # construct the http header - $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); - - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; + $headers = array(); + + # construct the http header + $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); + + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; + } + + // 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->serializer->sanitizeForSerialization($postData)); + } + + $url = $this->config->getHost() . $resourcePath; + + $curl = curl_init(); + // set timeout, if needed + if ($this->config->getCurlTimeout() != 0) { + curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); + } + // 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 ApiException('Method ' . $method . ' is not recognized.'); + } + curl_setopt($curl, CURLOPT_URL, $url); + + // Set user agent + curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); + + // debugging for curl + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); + + curl_setopt($curl, CURLOPT_VERBOSE, 1); + curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); + } else { + curl_setopt($curl, CURLOPT_VERBOSE, 0); + } + + // obtain the HTTP response headers + curl_setopt($curl, CURLOPT_HEADER, 1); + + // Make the request + $response = curl_exec($curl); + $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); + $http_header = substr($response, 0, $http_header_size); + $http_body = substr($response, $http_header_size); + $response_info = curl_getinfo($curl); + + // debug HTTP response body + if ($this->config->getDebug()) { + error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); + } + + // Handle the response + if ($response_info['http_code'] == 0) { + throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); + } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { + // return raw body if response is a file + if ($responseType == '\SplFileObject') { + return array($http_body, $http_header); + } + + $data = json_decode($http_body); + if (json_last_error() > 0) { // if response is a string + $data = $http_body; + } + } else { + throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body); + } + return array($data, $http_header); } - - // form data - if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { - $postData = http_build_query($postData); + + /* + * return the header 'Accept' based on an array of Accept provided + * + * @param string[] $accept Array of header + * @return string Accept (e.g. application/json) + */ + public static function selectHeaderAccept($accept) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + return NULL; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } } - else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model - $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); + + /* + * return the content type based on an array of content-type provided + * + * @param string[] content_type_array Array fo content-type + * @return string Content-Type (e.g. application/json) + */ + public static function selectHeaderContentType($content_type) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $content_type)) { + return 'application/json'; + } else { + return implode(',', $content_type); + } } - - $url = $this->config->getHost() . $resourcePath; - - $curl = curl_init(); - // set timeout, if needed - if ($this->config->getCurlTimeout() != 0) { - curl_setopt($curl, CURLOPT_TIMEOUT, $this->config->getCurlTimeout()); - } - // 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 ApiException('Method ' . $method . ' is not recognized.'); - } - curl_setopt($curl, CURLOPT_URL, $url); - - // Set user agent - curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); - - // debugging for curl - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); - - curl_setopt($curl, CURLOPT_VERBOSE, 1); - curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); - } else { - curl_setopt($curl, CURLOPT_VERBOSE, 0); - } - - // obtain the HTTP response headers - curl_setopt($curl, CURLOPT_HEADER, 1); - - // Make the request - $response = curl_exec($curl); - $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); - $http_header = substr($response, 0, $http_header_size); - $http_body = substr($response, $http_header_size); - $response_info = curl_getinfo($curl); - - // debug HTTP response body - if ($this->config->getDebug()) { - error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); - } - - // Handle the response - if ($response_info['http_code'] == 0) { - throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); - } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - // return raw body if response is a file - if ($responseType == '\SplFileObject') { - return array($http_body, $http_header); - } - - $data = json_decode($http_body); - if (json_last_error() > 0) { // if response is a string - $data = $http_body; - } - } else { - throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body); - } - return array($data, $http_header); - } - - /* - * return the header 'Accept' based on an array of Accept provided - * - * @param string[] $accept Array of header - * @return string Accept (e.g. application/json) - */ - public static function selectHeaderAccept($accept) { - if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { - return NULL; - } elseif (preg_grep("/application\/json/i", $accept)) { - return 'application/json'; - } else { - return implode(',', $accept); - } - } - - /* - * return the content type based on an array of content-type provided - * - * @param string[] content_type_array Array fo content-type - * @return string Content-Type (e.g. application/json) - */ - public static function selectHeaderContentType($content_type) { - if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { - return 'application/json'; - } elseif (preg_grep("/application\/json/i", $content_type)) { - return 'application/json'; - } else { - return implode(',', $content_type); - } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 51774137aed2..b1342921a0a1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -21,50 +21,50 @@ use \Exception; class ApiException extends Exception { - /** @var string The HTTP body of the server response. */ - protected $responseBody; - - /** @var string[] The HTTP header of the server response. */ - protected $responseHeaders; - - /** - * The deserialized response object - */ - protected $responseObject; - - public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { - parent::__construct($message, $code); - $this->responseHeaders = $responseHeaders; - $this->responseBody = $responseBody; - } - - /** - * Get the HTTP response header - * - * @return string HTTP response header - */ - public function getResponseHeaders() { - return $this->responseHeaders; - } - - /** - * Get the HTTP response body - * - * @return string HTTP response body - */ - public function getResponseBody() { - return $this->responseBody; - } - - /** - * sets the deseralized response object (during deserialization) - * @param mixed $obj - */ - public function setResponseObject($obj) { - $this->responseObject = $obj; - } - - public function getResponseObject() { - return $this->responseObject; - } + /** @var string The HTTP body of the server response. */ + protected $responseBody; + + /** @var string[] The HTTP header of the server response. */ + protected $responseHeaders; + + /** + * The deserialized response object + */ + protected $responseObject; + + public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { + parent::__construct($message, $code); + $this->responseHeaders = $responseHeaders; + $this->responseBody = $responseBody; + } + + /** + * Get the HTTP response header + * + * @return string HTTP response header + */ + public function getResponseHeaders() { + return $this->responseHeaders; + } + + /** + * Get the HTTP response body + * + * @return string HTTP response body + */ + public function getResponseBody() { + return $this->responseBody; + } + + /** + * sets the deseralized response object (during deserialization) + * @param mixed $obj + */ + public function setResponseObject($obj) { + $this->responseObject = $obj; + } + + public function getResponseObject() { + return $this->responseObject; + } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index f4ccef391ef7..5f40dcfe3bdd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -19,262 +19,292 @@ namespace Swagger\Client; class Configuration { - private static $defaultConfiguration = null; + private static $defaultConfiguration = null; + + /** @var string[] Associate array to store API key(s) */ + protected $apiKeys = array(); + + /** string[] Associate array to store API prefix (e.g. Bearer) */ + protected $apiKeyPrefixes = array(); + + /** @var string Username for HTTP basic authentication */ + protected $username = ''; + + /** @var string Password for HTTP basic authentication */ + protected $password = ''; + + /** @var \Swagger\Client\ApiClient The default instance of ApiClient */ + protected $defaultHeaders = array(); + + /** @var string The host */ + protected $host = 'http://localhost'; + + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ + protected $curlTimeout = 0; + + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ + protected $userAgent = "PHP-Swagger"; + + /** @var bool Debug switch (default set to false) */ + protected $debug = false; + + /** @var string Debug file location (log to STDOUT by default) */ + protected $debugFile = 'php://output'; + + /** @var string Debug file location (log to STDOUT by default) */ + protected $tempFolderPath; - /** @var string[] Associate array to store API key(s) */ - protected $apiKeys = array(); + /** + * @param string $tempFolderPath + */ + public function __construct() { + $this->tempFolderPath = sys_get_temp_dir(); + } + - /** string[] Associate array to store API prefix (e.g. Bearer) */ - protected $apiKeyPrefixes = array(); - - /** @var string Username for HTTP basic authentication */ - protected $username = ''; - - /** @var string Password for HTTP basic authentication */ - protected $password = ''; - - /** @var \Swagger\Client\ApiClient The default instance of ApiClient */ - protected $defaultHeaders = array(); - - /** @var string The host */ - protected $host = 'http://localhost'; - - /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ - protected $curlTimeout = 0; - - /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ - protected $userAgent = "PHP-Swagger"; - - /** @var bool Debug switch (default set to false) */ - protected $debug = false; - - /** @var string Debug file location (log to STDOUT by default) */ - protected $debugFile = 'php://output'; - - /** - * @param string $key - * @param string $value - * @return Configuration - */ - public function setApiKey($key, $value) { - $this->apiKeys[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKey($key) { - return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; - } - - /** - * @param string $key - * @param string $value - * @return Configuration - */ - public function setApiKeyPrefix($key, $value) { - $this->apiKeyPrefixes[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKeyPrefix($key) { - return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; - } - - /** - * @param string $username - * @return Configuration - */ - public function setUsername($username) { - $this->username = $username; - return $this; - } - - /** - * @return string - */ - public function getUsername() { - return $this->username; - } - - /** - * @param string $password - * @return Configuration - */ - public function setPassword($password) { - $this->password = $password; - return $this; - } - - /** - * @return string - */ - public function getPassword() { - return $this->password; - } - - /** - * add default header - * - * @param string $headerName header name (e.g. Token) - * @param string $headerValue header value (e.g. 1z8wp3) - * @return ApiClient - */ - public function addDefaultHeader($headerName, $headerValue) { - if (!is_string($headerName)) { - throw new \InvalidArgumentException('Header name must be a string.'); + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKey($key, $value) { + $this->apiKeys[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKey($key) { + return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + } + + /** + * @param string $key + * @param string $value + * @return Configuration + */ + public function setApiKeyPrefix($key, $value) { + $this->apiKeyPrefixes[$key] = $value; + return $this; + } + + /** + * @param $key + * @return string + */ + public function getApiKeyPrefix($key) { + return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; + } + + /** + * @param string $username + * @return Configuration + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * @param string $password + * @return Configuration + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * add default header + * + * @param string $headerName header name (e.g. Token) + * @param string $headerValue header value (e.g. 1z8wp3) + * @return ApiClient + */ + public function addDefaultHeader($headerName, $headerValue) { + if (!is_string($headerName)) { + throw new \InvalidArgumentException('Header name must be a string.'); + } + + $this->defaultHeaders[$headerName] = $headerValue; + return $this; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeaders() { + return $this->defaultHeaders; + } + + /** + * delete a default header + * @param string $headerName the header to delete + * @return Configuration + */ + public function deleteDefaultHeader($headerName) { + unset($this->defaultHeaders[$headerName]); + } + + /** + * @param string $host + * @return Configuration + */ + public function setHost($host) { + $this->host = $host; + return $this; + } + + /** + * @return string + */ + public function getHost() { + return $this->host; + } + + /** + * set the user agent of the api client + * + * @param string $userAgent the user agent of the api client + * @return ApiClient + */ + public function setUserAgent($userAgent) { + if (!is_string($userAgent)) { + throw new \InvalidArgumentException('User-agent must be a string.'); + } + + $this->userAgent = $userAgent; + return $this; + } + + /** + * get the user agent of the api client + * + * @return string user agent + */ + public function getUserAgent() { + return $this->userAgent; + } + + /** + * set the HTTP timeout value + * + * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * @return ApiClient + */ + public function setCurlTimeout($seconds) { + if (!is_numeric($seconds) || $seconds < 0) { + throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + } + + $this->curlTimeout = $seconds; + return $this; + } + + /** + * get the HTTP timeout value + * + * @return string HTTP timeout value + */ + public function getCurlTimeout() { + return $this->curlTimeout; + } + + /** + * @param bool $debug + * @return Configuration + */ + public function setDebug($debug) { + $this->debug = $debug; + return $this; + } + + /** + * @return bool + */ + public function getDebug() { + return $this->debug; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setDebugFile($debugFile) { + $this->debugFile = $debugFile; + return $this; + } + + /** + * @return string + */ + public function getDebugFile() { + return $this->debugFile; + } + + /** + * @param string $debugFile + * @return Configuration + */ + public function setTempFolderPath($tempFolderPath) { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * @return string + */ + public function getTempFolderPath() { + return $this->tempFolderPath; } - $this->defaultHeaders[$headerName] = $headerValue; - return $this; - } - - /** - * get the default header - * - * @return array default header - */ - public function getDefaultHeaders() { - return $this->defaultHeaders; - } - - /** - * delete a default header - * @param string $headerName the header to delete - * @return Configuration - */ - public function deleteDefaultHeader($headerName) { - unset($this->defaultHeaders[$headerName]); - } - - /** - * @param string $host - * @return Configuration - */ - public function setHost($host) { - $this->host = $host; - return $this; - } - - /** - * @return string - */ - public function getHost() { - return $this->host; - } - - /** - * set the user agent of the api client - * - * @param string $userAgent the user agent of the api client - * @return ApiClient - */ - public function setUserAgent($userAgent) { - if (!is_string($userAgent)) { - throw new \InvalidArgumentException('User-agent must be a string.'); + /** + * @return Configuration + */ + public static function getDefaultConfiguration() { + if (self::$defaultConfiguration == null) { + return new Configuration(); + } + + return self::$defaultConfiguration; } - - $this->userAgent = $userAgent; - return $this; - } - - /** - * get the user agent of the api client - * - * @return string user agent - */ - public function getUserAgent() { - return $this->userAgent; - } - - /** - * set the HTTP timeout value - * - * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - * @return ApiClient - */ - public function setCurlTimeout($seconds) { - if (!is_numeric($seconds) || $seconds < 0) { - throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); + + /** + * @param Configuration $config + */ + public static function setDefaultConfiguration(Configuration $config) { + self::$defaultConfiguration = $config; } - - $this->curlTimeout = $seconds; - return $this; - } - - /** - * get the HTTP timeout value - * - * @return string HTTP timeout value - */ - public function getCurlTimeout() { - return $this->curlTimeout; - } - - /** - * @param bool $debug - * @return Configuration - */ - public function setDebug($debug) { - $this->debug = $debug; - return $this; - } - - /** - * @return bool - */ - public function getDebug() { - return $this->debug; - } - - /** - * @param string $debugFile - * @return Configuration - */ - public function setDebugFile($debugFile) { - $this->debugFile = $debugFile; - return $this; - } - - /** - * @return string - */ - public function getDebugFile() { - return $this->debugFile; - } - - /** - * @return Configuration - */ - public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { - return new Configuration(); + + /* + * return the report for debugging + */ + public static function toDebugReport() { + $report = "PHP SDK (Swagger\Client) Debug Report:\n"; + $report .= " OS: ".php_uname()."\n"; + $report .= " PHP Version: ".phpversion()."\n"; + $report .= " Swagger Spec Version: 1.0.0\n"; + $report .= " SDK Package Version: 1.0.0\n"; + + return $report; } - - return self::$defaultConfiguration; - } - - public static function setDefaultConfiguration(Configuration $config) { - self::$defaultConfiguration = $config; - } - - /* - * return the report for debuggin - */ - public static function toDebugReport() { - $report = "PHP SDK (Swagger\Client) Debug Report:\n"; - $report .= " OS: ".php_uname()."\n"; - $report .= " PHP Version: ".phpversion()."\n"; - $report .= " Swagger Spec Version: 1.0.0\n"; - $report .= " SDK Package Version: 1.0.0\n"; - - return $report; - } - + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 9995dccdd4e0..eb6603043df1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -27,101 +27,101 @@ namespace Swagger\Client\Model; use \ArrayAccess; class Category implements ArrayAccess { - /** @var string[] Array of property to type mappings. Used for (de)serialization */ - static $swaggerTypes = array( - 'id' => 'int', - 'name' => 'string' - ); - - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ - static $setters = array( - 'id' => 'setId', - 'name' => 'setName' - ); - - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ - static $getters = array( - 'id' => 'getId', - 'name' => 'getName' - ); - + /** @var string[] Array of property to type mappings. Used for (de)serialization */ + static $swaggerTypes = array( + 'id' => 'int', + 'name' => 'string' + ); - /** @var int $id */ - protected $id; + /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); - /** @var string $name */ - protected $name; + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'name' => 'setName' + ); - public function __construct(array $data = null) { - if ($data != null) { - $this->id = $data["id"]; - $this->name = $data["name"]; + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'name' => 'getName' + ); + + + /** @var int $id */ + protected $id; + + /** @var string $name */ + protected $name; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } } - } - - /** - * get id - * @return int - */ - public function getId() { - return $this->id; - } - - /** - * set id - * @param int $id - * @return $this - */ - public function setId($id) { - $this->id = $id; - return $this; - } - - /** - * get name - * @return string - */ - public function getName() { - return $this->name; - } - - /** - * set name - * @param string $name - * @return $this - */ - public function setName($name) { - $this->name = $name; - return $this; - } - - 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); - } - - public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); - } else { - return json_encode(get_object_vars($this)); + + /** + * get id + * @return int + */ + public function getId() { + return $this->id; + } + + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + + 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); + } + + public function __toString() { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); + } else { + return json_encode(get_object_vars($this)); + } } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 2e0386d0ed74..bcea02d96862 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -27,205 +27,205 @@ namespace Swagger\Client\Model; use \ArrayAccess; class Order implements ArrayAccess { - /** @var string[] Array of property to type mappings. Used for (de)serialization */ - static $swaggerTypes = array( - 'id' => 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => '\DateTime', - 'status' => 'string', - 'complete' => 'bool' - ); - - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ - static $attributeMap = array( - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' - ); - - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ - static $setters = array( - 'id' => 'setId', - 'pet_id' => 'setPetId', - 'quantity' => 'setQuantity', - 'ship_date' => 'setShipDate', - 'status' => 'setStatus', - 'complete' => 'setComplete' - ); - - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ - static $getters = array( - 'id' => 'getId', - 'pet_id' => 'getPetId', - 'quantity' => 'getQuantity', - 'ship_date' => 'getShipDate', - 'status' => 'getStatus', - 'complete' => 'getComplete' - ); - + /** @var string[] Array of property to type mappings. Used for (de)serialization */ + static $swaggerTypes = array( + 'id' => 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => '\DateTime', + 'status' => 'string', + 'complete' => 'bool' + ); - /** @var int $id */ - protected $id; + /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + static $attributeMap = array( + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' + ); - /** @var int $pet_id */ - protected $pet_id; + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'pet_id' => 'setPetId', + 'quantity' => 'setQuantity', + 'ship_date' => 'setShipDate', + 'status' => 'setStatus', + 'complete' => 'setComplete' + ); - /** @var int $quantity */ - protected $quantity; + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'pet_id' => 'getPetId', + 'quantity' => 'getQuantity', + 'ship_date' => 'getShipDate', + 'status' => 'getStatus', + 'complete' => 'getComplete' + ); - /** @var \DateTime $ship_date */ - protected $ship_date; - - /** @var string $status Order Status */ - protected $status; - - /** @var bool $complete */ - protected $complete; - - public function __construct(array $data = null) { - if ($data != null) { - $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"]; + + /** @var int $id */ + protected $id; + + /** @var int $pet_id */ + protected $pet_id; + + /** @var int $quantity */ + protected $quantity; + + /** @var \DateTime $ship_date */ + protected $ship_date; + + /** @var string $status Order Status */ + protected $status; + + /** @var bool $complete */ + protected $complete; + + public function __construct(array $data = null) { + if ($data != null) { + $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"]; + } } - } - - /** - * get id - * @return int - */ - public function getId() { - return $this->id; - } - - /** - * set id - * @param int $id - * @return $this - */ - public function setId($id) { - $this->id = $id; - return $this; - } - - /** - * get pet_id - * @return int - */ - public function getPetId() { - return $this->pet_id; - } - - /** - * set pet_id - * @param int $pet_id - * @return $this - */ - public function setPetId($pet_id) { - $this->pet_id = $pet_id; - return $this; - } - - /** - * get quantity - * @return int - */ - public function getQuantity() { - return $this->quantity; - } - - /** - * set quantity - * @param int $quantity - * @return $this - */ - public function setQuantity($quantity) { - $this->quantity = $quantity; - return $this; - } - - /** - * get ship_date - * @return \DateTime - */ - public function getShipDate() { - return $this->ship_date; - } - - /** - * set ship_date - * @param \DateTime $ship_date - * @return $this - */ - public function setShipDate($ship_date) { - $this->ship_date = $ship_date; - return $this; - } - - /** - * get status - * @return string - */ - public function getStatus() { - return $this->status; - } - - /** - * set status - * @param string $status - * @return $this - */ - public function setStatus($status) { - $this->status = $status; - return $this; - } - - /** - * get complete - * @return bool - */ - public function getComplete() { - return $this->complete; - } - - /** - * set complete - * @param bool $complete - * @return $this - */ - public function setComplete($complete) { - $this->complete = $complete; - return $this; - } - - 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); - } - - public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); - } else { - return json_encode(get_object_vars($this)); + + /** + * get id + * @return int + */ + public function getId() { + return $this->id; + } + + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get pet_id + * @return int + */ + public function getPetId() { + return $this->pet_id; + } + + /** + * set pet_id + * @param int $pet_id + * @return $this + */ + public function setPetId($pet_id) { + $this->pet_id = $pet_id; + return $this; + } + + /** + * get quantity + * @return int + */ + public function getQuantity() { + return $this->quantity; + } + + /** + * set quantity + * @param int $quantity + * @return $this + */ + public function setQuantity($quantity) { + $this->quantity = $quantity; + return $this; + } + + /** + * get ship_date + * @return \DateTime + */ + public function getShipDate() { + return $this->ship_date; + } + + /** + * set ship_date + * @param \DateTime $ship_date + * @return $this + */ + public function setShipDate($ship_date) { + $this->ship_date = $ship_date; + return $this; + } + + /** + * get status + * @return string + */ + public function getStatus() { + return $this->status; + } + + /** + * set status + * @param string $status + * @return $this + */ + public function setStatus($status) { + $this->status = $status; + return $this; + } + + /** + * get complete + * @return bool + */ + public function getComplete() { + return $this->complete; + } + + /** + * set complete + * @param bool $complete + * @return $this + */ + public function setComplete($complete) { + $this->complete = $complete; + return $this; + } + + 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); + } + + public function __toString() { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); + } else { + return json_encode(get_object_vars($this)); + } } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index a7b259a2fbe8..2e6947144c97 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -27,205 +27,205 @@ namespace Swagger\Client\Model; use \ArrayAccess; class Pet implements ArrayAccess { - /** @var string[] Array of property to type mappings. Used for (de)serialization */ - static $swaggerTypes = array( - 'id' => 'int', - 'category' => '\Swagger\Client\Model\Category', - 'name' => 'string', - 'photo_urls' => 'string[]', - 'tags' => '\Swagger\Client\Model\Tag[]', - 'status' => 'string' - ); - - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ - static $attributeMap = array( - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' - ); - - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ - static $setters = array( - 'id' => 'setId', - 'category' => 'setCategory', - 'name' => 'setName', - 'photo_urls' => 'setPhotoUrls', - 'tags' => 'setTags', - 'status' => 'setStatus' - ); - - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ - static $getters = array( - 'id' => 'getId', - 'category' => 'getCategory', - 'name' => 'getName', - 'photo_urls' => 'getPhotoUrls', - 'tags' => 'getTags', - 'status' => 'getStatus' - ); - + /** @var string[] Array of property to type mappings. Used for (de)serialization */ + static $swaggerTypes = array( + 'id' => 'int', + 'category' => '\Swagger\Client\Model\Category', + 'name' => 'string', + 'photo_urls' => 'string[]', + 'tags' => '\Swagger\Client\Model\Tag[]', + 'status' => 'string' + ); - /** @var int $id */ - protected $id; + /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + static $attributeMap = array( + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' + ); - /** @var \Swagger\Client\Model\Category $category */ - protected $category; + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'category' => 'setCategory', + 'name' => 'setName', + 'photo_urls' => 'setPhotoUrls', + 'tags' => 'setTags', + 'status' => 'setStatus' + ); - /** @var string $name */ - protected $name; + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'category' => 'getCategory', + 'name' => 'getName', + 'photo_urls' => 'getPhotoUrls', + 'tags' => 'getTags', + 'status' => 'getStatus' + ); - /** @var string[] $photo_urls */ - protected $photo_urls; - - /** @var \Swagger\Client\Model\Tag[] $tags */ - protected $tags; - - /** @var string $status pet status in the store */ - protected $status; - - public function __construct(array $data = null) { - if ($data != null) { - $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"]; + + /** @var int $id */ + protected $id; + + /** @var \Swagger\Client\Model\Category $category */ + protected $category; + + /** @var string $name */ + protected $name; + + /** @var string[] $photo_urls */ + protected $photo_urls; + + /** @var \Swagger\Client\Model\Tag[] $tags */ + protected $tags; + + /** @var string $status pet status in the store */ + protected $status; + + public function __construct(array $data = null) { + if ($data != null) { + $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"]; + } } - } - - /** - * get id - * @return int - */ - public function getId() { - return $this->id; - } - - /** - * set id - * @param int $id - * @return $this - */ - public function setId($id) { - $this->id = $id; - return $this; - } - - /** - * get category - * @return \Swagger\Client\Model\Category - */ - public function getCategory() { - return $this->category; - } - - /** - * set category - * @param \Swagger\Client\Model\Category $category - * @return $this - */ - public function setCategory($category) { - $this->category = $category; - return $this; - } - - /** - * get name - * @return string - */ - public function getName() { - return $this->name; - } - - /** - * set name - * @param string $name - * @return $this - */ - public function setName($name) { - $this->name = $name; - return $this; - } - - /** - * get photo_urls - * @return string[] - */ - public function getPhotoUrls() { - return $this->photo_urls; - } - - /** - * set photo_urls - * @param string[] $photo_urls - * @return $this - */ - public function setPhotoUrls($photo_urls) { - $this->photo_urls = $photo_urls; - return $this; - } - - /** - * get tags - * @return \Swagger\Client\Model\Tag[] - */ - public function getTags() { - return $this->tags; - } - - /** - * set tags - * @param \Swagger\Client\Model\Tag[] $tags - * @return $this - */ - public function setTags($tags) { - $this->tags = $tags; - return $this; - } - - /** - * get status - * @return string - */ - public function getStatus() { - return $this->status; - } - - /** - * set status - * @param string $status - * @return $this - */ - public function setStatus($status) { - $this->status = $status; - return $this; - } - - 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); - } - - public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); - } else { - return json_encode(get_object_vars($this)); + + /** + * get id + * @return int + */ + public function getId() { + return $this->id; + } + + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get category + * @return \Swagger\Client\Model\Category + */ + public function getCategory() { + return $this->category; + } + + /** + * set category + * @param \Swagger\Client\Model\Category $category + * @return $this + */ + public function setCategory($category) { + $this->category = $category; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + + /** + * get photo_urls + * @return string[] + */ + public function getPhotoUrls() { + return $this->photo_urls; + } + + /** + * set photo_urls + * @param string[] $photo_urls + * @return $this + */ + public function setPhotoUrls($photo_urls) { + $this->photo_urls = $photo_urls; + return $this; + } + + /** + * get tags + * @return \Swagger\Client\Model\Tag[] + */ + public function getTags() { + return $this->tags; + } + + /** + * set tags + * @param \Swagger\Client\Model\Tag[] $tags + * @return $this + */ + public function setTags($tags) { + $this->tags = $tags; + return $this; + } + + /** + * get status + * @return string + */ + public function getStatus() { + return $this->status; + } + + /** + * set status + * @param string $status + * @return $this + */ + public function setStatus($status) { + $this->status = $status; + return $this; + } + + 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); + } + + public function __toString() { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); + } else { + return json_encode(get_object_vars($this)); + } } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 6e8ae3e27a1a..bdd133810c57 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -27,101 +27,101 @@ namespace Swagger\Client\Model; use \ArrayAccess; class Tag implements ArrayAccess { - /** @var string[] Array of property to type mappings. Used for (de)serialization */ - static $swaggerTypes = array( - 'id' => 'int', - 'name' => 'string' - ); - - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ - static $setters = array( - 'id' => 'setId', - 'name' => 'setName' - ); - - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ - static $getters = array( - 'id' => 'getId', - 'name' => 'getName' - ); - + /** @var string[] Array of property to type mappings. Used for (de)serialization */ + static $swaggerTypes = array( + 'id' => 'int', + 'name' => 'string' + ); - /** @var int $id */ - protected $id; + /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + static $attributeMap = array( + 'id' => 'id', + 'name' => 'name' + ); - /** @var string $name */ - protected $name; + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'name' => 'setName' + ); - public function __construct(array $data = null) { - if ($data != null) { - $this->id = $data["id"]; - $this->name = $data["name"]; + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'name' => 'getName' + ); + + + /** @var int $id */ + protected $id; + + /** @var string $name */ + protected $name; + + public function __construct(array $data = null) { + if ($data != null) { + $this->id = $data["id"]; + $this->name = $data["name"]; + } } - } - - /** - * get id - * @return int - */ - public function getId() { - return $this->id; - } - - /** - * set id - * @param int $id - * @return $this - */ - public function setId($id) { - $this->id = $id; - return $this; - } - - /** - * get name - * @return string - */ - public function getName() { - return $this->name; - } - - /** - * set name - * @param string $name - * @return $this - */ - public function setName($name) { - $this->name = $name; - return $this; - } - - 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); - } - - public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); - } else { - return json_encode(get_object_vars($this)); + + /** + * get id + * @return int + */ + public function getId() { + return $this->id; + } + + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get name + * @return string + */ + public function getName() { + return $this->name; + } + + /** + * set name + * @param string $name + * @return $this + */ + public function setName($name) { + $this->name = $name; + return $this; + } + + 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); + } + + public function __toString() { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); + } else { + return json_encode(get_object_vars($this)); + } } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index b1e2d2b809ca..160d93e8f58d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -27,257 +27,257 @@ namespace Swagger\Client\Model; use \ArrayAccess; class User implements ArrayAccess { - /** @var string[] Array of property to type mappings. Used for (de)serialization */ - static $swaggerTypes = array( - 'id' => 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' - ); - - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ - static $attributeMap = array( - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' - ); - - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ - static $setters = array( - 'id' => 'setId', - 'username' => 'setUsername', - 'first_name' => 'setFirstName', - 'last_name' => 'setLastName', - 'email' => 'setEmail', - 'password' => 'setPassword', - 'phone' => 'setPhone', - 'user_status' => 'setUserStatus' - ); - - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ - static $getters = array( - 'id' => 'getId', - 'username' => 'getUsername', - 'first_name' => 'getFirstName', - 'last_name' => 'getLastName', - 'email' => 'getEmail', - 'password' => 'getPassword', - 'phone' => 'getPhone', - 'user_status' => 'getUserStatus' - ); - + /** @var string[] Array of property to type mappings. Used for (de)serialization */ + static $swaggerTypes = array( + 'id' => 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' + ); - /** @var int $id */ - protected $id; + /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + static $attributeMap = array( + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' + ); - /** @var string $username */ - protected $username; + /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + static $setters = array( + 'id' => 'setId', + 'username' => 'setUsername', + 'first_name' => 'setFirstName', + 'last_name' => 'setLastName', + 'email' => 'setEmail', + 'password' => 'setPassword', + 'phone' => 'setPhone', + 'user_status' => 'setUserStatus' + ); - /** @var string $first_name */ - protected $first_name; + /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + static $getters = array( + 'id' => 'getId', + 'username' => 'getUsername', + 'first_name' => 'getFirstName', + 'last_name' => 'getLastName', + 'email' => 'getEmail', + 'password' => 'getPassword', + 'phone' => 'getPhone', + 'user_status' => 'getUserStatus' + ); - /** @var string $last_name */ - protected $last_name; - - /** @var string $email */ - protected $email; - - /** @var string $password */ - protected $password; - - /** @var string $phone */ - protected $phone; - - /** @var int $user_status User Status */ - protected $user_status; - - public function __construct(array $data = null) { - if ($data != null) { - $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"]; + + /** @var int $id */ + protected $id; + + /** @var string $username */ + protected $username; + + /** @var string $first_name */ + protected $first_name; + + /** @var string $last_name */ + protected $last_name; + + /** @var string $email */ + protected $email; + + /** @var string $password */ + protected $password; + + /** @var string $phone */ + protected $phone; + + /** @var int $user_status User Status */ + protected $user_status; + + public function __construct(array $data = null) { + if ($data != null) { + $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"]; + } } - } - - /** - * get id - * @return int - */ - public function getId() { - return $this->id; - } - - /** - * set id - * @param int $id - * @return $this - */ - public function setId($id) { - $this->id = $id; - return $this; - } - - /** - * get username - * @return string - */ - public function getUsername() { - return $this->username; - } - - /** - * set username - * @param string $username - * @return $this - */ - public function setUsername($username) { - $this->username = $username; - return $this; - } - - /** - * get first_name - * @return string - */ - public function getFirstName() { - return $this->first_name; - } - - /** - * set first_name - * @param string $first_name - * @return $this - */ - public function setFirstName($first_name) { - $this->first_name = $first_name; - return $this; - } - - /** - * get last_name - * @return string - */ - public function getLastName() { - return $this->last_name; - } - - /** - * set last_name - * @param string $last_name - * @return $this - */ - public function setLastName($last_name) { - $this->last_name = $last_name; - return $this; - } - - /** - * get email - * @return string - */ - public function getEmail() { - return $this->email; - } - - /** - * set email - * @param string $email - * @return $this - */ - public function setEmail($email) { - $this->email = $email; - return $this; - } - - /** - * get password - * @return string - */ - public function getPassword() { - return $this->password; - } - - /** - * set password - * @param string $password - * @return $this - */ - public function setPassword($password) { - $this->password = $password; - return $this; - } - - /** - * get phone - * @return string - */ - public function getPhone() { - return $this->phone; - } - - /** - * set phone - * @param string $phone - * @return $this - */ - public function setPhone($phone) { - $this->phone = $phone; - return $this; - } - - /** - * get user_status - * @return int - */ - public function getUserStatus() { - return $this->user_status; - } - - /** - * set user_status - * @param int $user_status - * @return $this - */ - public function setUserStatus($user_status) { - $this->user_status = $user_status; - return $this; - } - - 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); - } - - public function __toString() { - if (defined('JSON_PRETTY_PRINT')) { - return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); - } else { - return json_encode(get_object_vars($this)); + + /** + * get id + * @return int + */ + public function getId() { + return $this->id; + } + + /** + * set id + * @param int $id + * @return $this + */ + public function setId($id) { + $this->id = $id; + return $this; + } + + /** + * get username + * @return string + */ + public function getUsername() { + return $this->username; + } + + /** + * set username + * @param string $username + * @return $this + */ + public function setUsername($username) { + $this->username = $username; + return $this; + } + + /** + * get first_name + * @return string + */ + public function getFirstName() { + return $this->first_name; + } + + /** + * set first_name + * @param string $first_name + * @return $this + */ + public function setFirstName($first_name) { + $this->first_name = $first_name; + return $this; + } + + /** + * get last_name + * @return string + */ + public function getLastName() { + return $this->last_name; + } + + /** + * set last_name + * @param string $last_name + * @return $this + */ + public function setLastName($last_name) { + $this->last_name = $last_name; + return $this; + } + + /** + * get email + * @return string + */ + public function getEmail() { + return $this->email; + } + + /** + * set email + * @param string $email + * @return $this + */ + public function setEmail($email) { + $this->email = $email; + return $this; + } + + /** + * get password + * @return string + */ + public function getPassword() { + return $this->password; + } + + /** + * set password + * @param string $password + * @return $this + */ + public function setPassword($password) { + $this->password = $password; + return $this; + } + + /** + * get phone + * @return string + */ + public function getPhone() { + return $this->phone; + } + + /** + * set phone + * @param string $phone + * @return $this + */ + public function setPhone($phone) { + $this->phone = $phone; + return $this; + } + + /** + * get user_status + * @return int + */ + public function getUserStatus() { + return $this->user_status; + } + + /** + * set user_status + * @param int $user_status + * @return $this + */ + public function setUserStatus($user_status) { + $this->user_status = $user_status; + return $this; + } + + 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); + } + + public function __toString() { + if (defined('JSON_PRETTY_PRINT')) { + return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); + } else { + return json_encode(get_object_vars($this)); + } } - } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 59b7601d1407..dd68d067c6aa 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -9,29 +9,29 @@ class ObjectSerializer { * @return string serialized form of $data */ public 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); + 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) { + $getter = $data::$getters[$property]; + if ($data->$getter() !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); + } + } + $sanitized = $values; + } else { + $sanitized = (string)$data; } - $sanitized = $data; - } else if (is_object($data)) { - $values = array(); - foreach (array_keys($data::$swaggerTypes) as $property) { - $getter = $data::$getters[$property]; - if ($data->$getter() !== null) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$getter()); - } - } - $sanitized = $values; - } else { - $sanitized = (string)$data; - } - return $sanitized; + return $sanitized; } /** @@ -41,7 +41,7 @@ class ObjectSerializer { * @return string the serialized object */ public function toPathValue($value) { - return rawurlencode($this->toString($value)); + return rawurlencode($this->toString($value)); } /** @@ -53,11 +53,11 @@ class ObjectSerializer { * @return string the serialized object */ public function toQueryValue($object) { - if (is_array($object)) { - return implode(',', $object); - } else { - return $this->toString($object); - } + if (is_array($object)) { + return implode(',', $object); + } else { + return $this->toString($object); + } } /** @@ -68,7 +68,7 @@ class ObjectSerializer { * @return string the header string */ public function toHeaderValue($value) { - return $this->toString($value); + return $this->toString($value); } /** @@ -79,11 +79,11 @@ class ObjectSerializer { * @return string the form string */ public function toFormValue($value) { - if ($value instanceof SplFileObject) { - return $value->getRealPath(); - } else { - return $this->toString($value); - } + if ($value instanceof SplFileObject) { + return $value->getRealPath(); + } else { + return $this->toString($value); + } } /** @@ -94,11 +94,11 @@ class ObjectSerializer { * @return string the header string */ public function toString($value) { - if ($value instanceof \DateTime) { // datetime in ISO8601 format - return $value->format(\DateTime::ISO8601); - } else { - return $value; - } + if ($value instanceof \DateTime) { // datetime in ISO8601 format + return $value->format(\DateTime::ISO8601); + } else { + return $value; + } } /** @@ -109,65 +109,63 @@ class ObjectSerializer { * @return object an instance of $class */ public function deserialize($data, $class, $httpHeader=null) { - if (null === $data) { - $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] - $inner = substr($class, 4, -1); - $deserialized = array(); - if(strrpos($inner, ",") !== false) { - $subClass_array = explode(',', $inner, 2); - $subClass = $subClass_array[1]; - foreach ($data as $key => $value) { - $deserialized[$key] = $this->deserialize($value, $subClass); - } + if (null === $data) { + $deserialized = null; + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + $inner = substr($class, 4, -1); + $deserialized = array(); + if(strrpos($inner, ",") !== false) { + $subClass_array = explode(',', $inner, 2); + $subClass = $subClass_array[1]; + foreach ($data as $key => $value) { + $deserialized[$key] = $this->deserialize($value, $subClass); + } + } + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); + $values = array(); + foreach ($data as $key => $value) { + $values[] = $this->deserialize($value, $subClass); + } + $deserialized = $values; + } elseif ($class == 'DateTime') { + $deserialized = new \DateTime($data); + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { + settype($data, $class); + $deserialized = $data; + } elseif ($class === '\SplFileObject') { + # determine temp folder path + $tmpFolderPath = Configuration::getDefaultConfiguration()->getTempFolderPath(); + print_r($tmpFolderPath); + + # determine file name + if (preg_match('/Content-Disposition: inline; filename=(.*)$/i', $httpHeader, $match)) { + $filename = $tmpFolderPath.$match[1]; + } else { + print_r($tmpFolderPath); + $filename = tempnam($tmpFolderPath, ''); + } + $deserialized = new \SplFileObject($filename, "w"); + $byte_written = $deserialized->fwrite($data); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + + } else { + $instance = new $class(); + foreach ($instance::$swaggerTypes as $property => $type) { + $propertySetter = $instance::$setters[$property]; + + if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { + continue; + } + + $propertyValue = $data->{$instance::$attributeMap[$property]}; + if (isset($propertyValue)) { + $instance->$propertySetter($this->deserialize($propertyValue, $type)); + } + } + $deserialized = $instance; } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { - $subClass = substr($class, 0, -2); - $values = array(); - foreach ($data as $key => $value) { - $values[] = $this->deserialize($value, $subClass); - } - $deserialized = $values; - } elseif ($class == 'DateTime') { - $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { - settype($data, $class); - $deserialized = $data; - } elseif ($class === '\SplFileObject') { - # determine temp folder path - if (!isset(Configuration::$tempFolderPath) || '' === Configuration::$tempFolderPath) { - $tmpFolderPath = sys_get_temp_dir(); - } else { - $tmpFolderPath = Configuration::tempFolderPath; - } - - # determine file name - if (preg_match('/Content-Disposition: inline; filename=(.*)/i', $httpHeader, $match)) { - $filename = $tmpFolderPath.$match[1]; - } else { - $filename = tempnam($tmpFolderPath, ''); - } - $deserialized = new \SplFileObject($filename, "w"); - $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); - - } else { - $instance = new $class(); - foreach ($instance::$swaggerTypes as $property => $type) { - $propertySetter = $instance::$setters[$property]; - - if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { - continue; - } - - $propertyValue = $data->{$instance::$attributeMap[$property]}; - if (isset($propertyValue)) { - $instance->$propertySetter($this->deserialize($propertyValue, $type)); - } - } - $deserialized = $instance; - } - - return $deserialized; + + return $deserialized; } } diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 55aae557a234..bec9f4e6e79b 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -12,12 +12,15 @@ require_once(__DIR__ . '/SwaggerClient-php/autoload.php'); // to enable logging //SwaggerClient\Configuration::$debug = true; //SwaggerClient\Configuration::$debug_file = '/var/tmp/php_debug.log'; +Swagger\Client\Configuration::getDefaultConfiguration()->setTempFolderPath('/var/tmp/php/'); $petId = 10005; // ID of pet that needs to be fetched try { // get pet by id //$pet_api = new SwaggerClient\PetAPI($api_client); $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setTempFolderPath('/var/tmp/php/'); + print_r($pet_api->getApiClient()->getConfig()->getTempFolderPath()); // test default header //$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); // return Pet (model) From 2258a4632d4f032f1e1a0d6af2f6f6aa7230370a Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 27 Jun 2015 22:54:37 +0800 Subject: [PATCH 56/62] fix test.php, fix default configuration --- .../resources/php/ObjectSerializer.mustache | 15 +++------ .../main/resources/php/configuration.mustache | 32 +++++++++++++++++-- .../SwaggerClient-php/lib/Configuration.php | 17 +++++----- .../lib/ObjectSerializer.php | 13 +++----- samples/client/petstore/php/test.php | 24 +++++++------- 5 files changed, 60 insertions(+), 41 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 4463236063a9..930313865c76 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -134,22 +134,15 @@ class ObjectSerializer { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { - # determine temp folder path - if (!isset(Configuration::getDefaultConfig->$tempFolderPath) || '' === Configuration::$tempFolderPath) { - $tmpFolderPath = sys_get_temp_dir(); - } else { - $tmpFolderPath = Configuration::tempFolderPath; - } - # determine file name - if (preg_match('/Content-Disposition: inline; filename=(.*)/i', $httpHeader, $match)) { - $filename = $tmpFolderPath.$match[1]; + if (preg_match('/Content-Disposition: inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader, $match)) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { - $filename = tempnam($tmpFolderPath, ''); + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n" , 3, Configuration::getDefaultConfiguration()->getDebugFile()); } else { $instance = new $class(); diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 94e0165b4a83..710edab55b63 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -50,6 +50,16 @@ class Configuration { /** @var string Debug file location (log to STDOUT by default) */ protected $debugFile = 'php://output'; + + /** @var string Debug file location (log to STDOUT by default) */ + protected $tempFolderPath; + + /** + * @param string $tempFolderPath + */ + public function __construct() { + $this->tempFolderPath = sys_get_temp_dir(); + } /** * @param string $key @@ -248,13 +258,30 @@ class Configuration { public function getDebugFile() { return $this->debugFile; } - + + /** + * @param string $tempFolderPath + * @return Configuration + */ + public function setTempFolderPath($tempFolderPath) { + $this->tempFolderPath = $tempFolderPath; + return $this; + } + + /** + * @return string + */ + public function getTempFolderPath() { + return $this->tempFolderPath; + } + + /** * @return Configuration */ public static function getDefaultConfiguration() { if (self::$defaultConfiguration == null) { - return new Configuration(); + self::$defaultConfiguration = new Configuration(); } return self::$defaultConfiguration; @@ -276,6 +303,7 @@ class Configuration { $report .= " PHP Version: ".phpversion()."\n"; $report .= " Swagger Spec Version: {{version}}\n"; $report .= " SDK Package Version: {{version}}\n"; + $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; return $report; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 5f40dcfe3bdd..664293f1a13c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -50,18 +50,17 @@ class Configuration { /** @var string Debug file location (log to STDOUT by default) */ protected $debugFile = 'php://output'; - + /** @var string Debug file location (log to STDOUT by default) */ protected $tempFolderPath; /** * @param string $tempFolderPath - */ + */ public function __construct() { $this->tempFolderPath = sys_get_temp_dir(); } - - + /** * @param string $key * @param string $value @@ -259,16 +258,16 @@ class Configuration { public function getDebugFile() { return $this->debugFile; } - + /** - * @param string $debugFile + * @param string $tempFolderPath * @return Configuration */ public function setTempFolderPath($tempFolderPath) { $this->tempFolderPath = $tempFolderPath; return $this; } - + /** * @return string */ @@ -276,12 +275,13 @@ class Configuration { return $this->tempFolderPath; } + /** * @return Configuration */ public static function getDefaultConfiguration() { if (self::$defaultConfiguration == null) { - return new Configuration(); + self::$defaultConfiguration = new Configuration(); } return self::$defaultConfiguration; @@ -303,6 +303,7 @@ class Configuration { $report .= " PHP Version: ".phpversion()."\n"; $report .= " Swagger Spec Version: 1.0.0\n"; $report .= " SDK Package Version: 1.0.0\n"; + $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; return $report; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index dd68d067c6aa..3f78ea55bb93 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -134,20 +134,15 @@ class ObjectSerializer { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { - # determine temp folder path - $tmpFolderPath = Configuration::getDefaultConfiguration()->getTempFolderPath(); - print_r($tmpFolderPath); - # determine file name - if (preg_match('/Content-Disposition: inline; filename=(.*)$/i', $httpHeader, $match)) { - $filename = $tmpFolderPath.$match[1]; + if (preg_match('/Content-Disposition: inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader, $match)) { + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { - print_r($tmpFolderPath); - $filename = tempnam($tmpFolderPath, ''); + $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file afterwards", 3, Configuration::getDefaultConfiguration()->getDebugFile()); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n" , 3, Configuration::getDefaultConfiguration()->getDebugFile()); } else { $instance = new $class(); diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index bec9f4e6e79b..79cc4ca4ad75 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -5,22 +5,24 @@ require_once(__DIR__ . '/SwaggerClient-php/autoload.php'); //ini_set('display_errors', 1); //error_reporting(~0); -// initialize the API client -//$api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); -//$api_client->addDefaultHeader("test1", "value1"); - // to enable logging -//SwaggerClient\Configuration::$debug = true; -//SwaggerClient\Configuration::$debug_file = '/var/tmp/php_debug.log'; +//Swagger\Client\Configuration::$debug = true; +//Swagger\Client\Configuration::$debug_file = '/var/tmp/php_debug.log'; + +// to debug report +print Swagger\Client\Configuration::toDebugReport(); + +// to change temp folder path Swagger\Client\Configuration::getDefaultConfiguration()->setTempFolderPath('/var/tmp/php/'); $petId = 10005; // ID of pet that needs to be fetched try { // get pet by id - //$pet_api = new SwaggerClient\PetAPI($api_client); + //$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + //$api_client->getConfig()->addDefaultHeader("test1", "value1"); + //$pet_api = new Swagger\Client\PetAPI($api_client); $pet_api = new Swagger\Client\Api\PetAPI(); $pet_api->getApiClient()->getConfig()->setTempFolderPath('/var/tmp/php/'); - print_r($pet_api->getApiClient()->getConfig()->getTempFolderPath()); // test default header //$pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); // return Pet (model) @@ -49,10 +51,10 @@ try { // add a new pet (model) $add_response = $pet_api->addPet($new_pet); - // test upload file (exception) - //$upload_response = $pet_api->uploadFile($petId, "test meta", NULL); + // test upload file (should return exception) + $upload_response = $pet_api->uploadFile($petId, "test meta", NULL); -} catch (Swagger\Client\Exception $e) { +} catch (Swagger\Client\ApiException $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; echo 'HTTP response headers: ', $e->getResponseHeaders(), "\n"; echo 'HTTP response body: ', $e->getResponseBody(), "\n"; From 38149173ff15b6aece68e03e68043165d4d3de35 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 27 Jun 2015 23:26:59 +0800 Subject: [PATCH 57/62] revert petstore json, fixed test case --- .../swagger-codegen/src/test/resources/2_0/petstore.json | 2 +- .../petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 8 ++++---- .../petstore/php/SwaggerClient-php/tests/PetApiTest.php | 6 ++++-- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index df781a90c494..66762d74b2bc 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -235,7 +235,7 @@ "200": { "description": "successful operation", "schema": { - "type": "file" + "$ref": "#/definitions/Pet" } }, "400": { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 54926f3c9f74..6971e0904652 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -329,7 +329,7 @@ class PetApi { * Find pet by ID * * @param int $pet_id ID of pet that needs to be fetched (required) - * @return \SplFileObject + * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { @@ -387,11 +387,11 @@ class PetApi { try { list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, $queryParams, $httpBody, - $headerParams, '\SplFileObject'); + $headerParams, '\Swagger\Client\Model\Pet'); } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\SplFileObject', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $httpHeader); $e->setResponseObject($data); break; } @@ -403,7 +403,7 @@ class PetApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\SplFileObject'); + return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet'); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 76c88d20c4e9..fe818069dac5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -70,9 +70,11 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertFalse(isset($defaultHeader['test2'])); $pet_api2 = new Swagger\Client\Api\PetAPI(); - $apiClient3 = new Swagger\Client\ApiClient(); + $config3 = new Swagger\Client\Configuration(); + $apiClient3 = new Swagger\Client\ApiClient($config3); $apiClient3->getConfig()->setUserAgent('api client 3'); - $apiClient4 = new Swagger\Client\ApiClient(); + $config4 = new Swagger\Client\Configuration(); + $apiClient4 = new Swagger\Client\ApiClient($config4); $apiClient4->getConfig()->setUserAgent('api client 4'); $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); From 71a22141bfc4491c8812047283db2912709f677c Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 2 Jul 2015 16:17:36 +0800 Subject: [PATCH 58/62] add enum support for model property --- .../src/main/resources/php/api.mustache | 4 +- .../src/main/resources/php/model.mustache | 4 ++ .../php/SwaggerClient-php/lib/Api/PetApi.php | 24 ++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 12 ++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 22 ++++------- .../SwaggerClient-php/lib/Model/Category.php | 2 + .../php/SwaggerClient-php/lib/Model/Order.php | 9 +++++ .../php/SwaggerClient-php/lib/Model/Pet.php | 9 +++++ .../php/SwaggerClient-php/lib/Model/Tag.php | 2 + .../php/SwaggerClient-php/lib/Model/User.php | 8 ++++ .../SwaggerClient-php/tests/OrderApiTest.php | 38 +++++++++++++++++++ 11 files changed, 93 insertions(+), 41 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 5a97244bfe88..6255a59d8e02 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -76,9 +76,7 @@ class {{classname}} { // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); ->>>>>>> temporary folder setting - } - {{/required}}{{/allParams}} + }{{/required}}{{/allParams}} // parse inputs $resourcePath = "{{path}}"; diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 9b8307f6ec47..df4ddc0b4f06 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -78,6 +78,10 @@ class {{classname}} implements ArrayAccess { * @return $this */ public function {{setter}}(${{name}}) { + {{#isEnum}}$allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); + if (!in_array(${{{name}}}, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for '{{name}}', must be one of {{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"); + }{{/isEnum}} $this->{{name}} = ${{name}}; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 6971e0904652..3620252ea513 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -72,7 +72,7 @@ class PetApi { */ public function updatePet($body) { - + // parse inputs $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -133,7 +133,7 @@ class PetApi { */ public function addPet($body) { - + // parse inputs $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -194,7 +194,7 @@ class PetApi { */ public function findPetsByStatus($status) { - + // parse inputs $resourcePath = "/pet/findByStatus"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -264,7 +264,7 @@ class PetApi { */ public function findPetsByTags($tags) { - + // parse inputs $resourcePath = "/pet/findByTags"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -333,13 +333,11 @@ class PetApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { - // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - - + // parse inputs $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -419,13 +417,11 @@ class PetApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function updatePetWithForm($pet_id, $name, $status) { - // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - - + // parse inputs $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -493,13 +489,11 @@ class PetApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function deletePet($api_key, $pet_id) { - // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - - + // parse inputs $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -565,13 +559,11 @@ class PetApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function uploadFile($pet_id, $additional_metadata, $file) { - // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - - + // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; $resourcePath = str_replace("{format}", "json", $resourcePath); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index a132b3e3ef5d..9947628fdf68 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -71,7 +71,7 @@ class StoreApi { */ public function getInventory() { - + // parse inputs $resourcePath = "/store/inventory"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -142,7 +142,7 @@ class StoreApi { */ public function placeOrder($body) { - + // parse inputs $resourcePath = "/store/order"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -209,13 +209,11 @@ class StoreApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { - // verify the required parameter 'order_id' is set if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } - - + // parse inputs $resourcePath = "/store/order/{orderId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -283,13 +281,11 @@ class StoreApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { - // verify the required parameter 'order_id' is set if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } - - + // parse inputs $resourcePath = "/store/order/{orderId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 62204e182e79..d0b98f348e31 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -72,7 +72,7 @@ class UserApi { */ public function createUser($body) { - + // parse inputs $resourcePath = "/user"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -130,7 +130,7 @@ class UserApi { */ public function createUsersWithArrayInput($body) { - + // parse inputs $resourcePath = "/user/createWithArray"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -188,7 +188,7 @@ class UserApi { */ public function createUsersWithListInput($body) { - + // parse inputs $resourcePath = "/user/createWithList"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -247,7 +247,7 @@ class UserApi { */ public function loginUser($username, $password) { - + // parse inputs $resourcePath = "/user/login"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -316,7 +316,7 @@ class UserApi { */ public function logoutUser() { - + // parse inputs $resourcePath = "/user/logout"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -369,13 +369,11 @@ class UserApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { - // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - - + // parse inputs $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -444,13 +442,11 @@ class UserApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function updateUser($username, $body) { - // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); } - - + // parse inputs $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -512,13 +508,11 @@ class UserApi { * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { - // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - - + // parse inputs $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index eb6603043df1..02b3d3cde0f6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -79,6 +79,7 @@ class Category implements ArrayAccess { * @return $this */ public function setId($id) { + $this->id = $id; return $this; } @@ -97,6 +98,7 @@ class Category implements ArrayAccess { * @return $this */ public function setName($name) { + $this->name = $name; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index bcea02d96862..9b20b159ab9f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -111,6 +111,7 @@ class Order implements ArrayAccess { * @return $this */ public function setId($id) { + $this->id = $id; return $this; } @@ -129,6 +130,7 @@ class Order implements ArrayAccess { * @return $this */ public function setPetId($pet_id) { + $this->pet_id = $pet_id; return $this; } @@ -147,6 +149,7 @@ class Order implements ArrayAccess { * @return $this */ public function setQuantity($quantity) { + $this->quantity = $quantity; return $this; } @@ -165,6 +168,7 @@ class Order implements ArrayAccess { * @return $this */ public function setShipDate($ship_date) { + $this->ship_date = $ship_date; return $this; } @@ -183,6 +187,10 @@ class Order implements ArrayAccess { * @return $this */ public function setStatus($status) { + $allowed_values = array("placed", "approved", "delivered"); + if (!in_array($status, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'placed', 'approved', 'delivered'"); + } $this->status = $status; return $this; } @@ -201,6 +209,7 @@ class Order implements ArrayAccess { * @return $this */ public function setComplete($complete) { + $this->complete = $complete; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 2e6947144c97..03c5b173532f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -111,6 +111,7 @@ class Pet implements ArrayAccess { * @return $this */ public function setId($id) { + $this->id = $id; return $this; } @@ -129,6 +130,7 @@ class Pet implements ArrayAccess { * @return $this */ public function setCategory($category) { + $this->category = $category; return $this; } @@ -147,6 +149,7 @@ class Pet implements ArrayAccess { * @return $this */ public function setName($name) { + $this->name = $name; return $this; } @@ -165,6 +168,7 @@ class Pet implements ArrayAccess { * @return $this */ public function setPhotoUrls($photo_urls) { + $this->photo_urls = $photo_urls; return $this; } @@ -183,6 +187,7 @@ class Pet implements ArrayAccess { * @return $this */ public function setTags($tags) { + $this->tags = $tags; return $this; } @@ -201,6 +206,10 @@ class Pet implements ArrayAccess { * @return $this */ public function setStatus($status) { + $allowed_values = array("available", "pending", "sold"); + if (!in_array($status, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'available', 'pending', 'sold'"); + } $this->status = $status; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index bdd133810c57..279618ac3bea 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -79,6 +79,7 @@ class Tag implements ArrayAccess { * @return $this */ public function setId($id) { + $this->id = $id; return $this; } @@ -97,6 +98,7 @@ class Tag implements ArrayAccess { * @return $this */ public function setName($name) { + $this->name = $name; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 160d93e8f58d..7dd45220cf93 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -127,6 +127,7 @@ class User implements ArrayAccess { * @return $this */ public function setId($id) { + $this->id = $id; return $this; } @@ -145,6 +146,7 @@ class User implements ArrayAccess { * @return $this */ public function setUsername($username) { + $this->username = $username; return $this; } @@ -163,6 +165,7 @@ class User implements ArrayAccess { * @return $this */ public function setFirstName($first_name) { + $this->first_name = $first_name; return $this; } @@ -181,6 +184,7 @@ class User implements ArrayAccess { * @return $this */ public function setLastName($last_name) { + $this->last_name = $last_name; return $this; } @@ -199,6 +203,7 @@ class User implements ArrayAccess { * @return $this */ public function setEmail($email) { + $this->email = $email; return $this; } @@ -217,6 +222,7 @@ class User implements ArrayAccess { * @return $this */ public function setPassword($password) { + $this->password = $password; return $this; } @@ -235,6 +241,7 @@ class User implements ArrayAccess { * @return $this */ public function setPhone($phone) { + $this->phone = $phone; return $this; } @@ -253,6 +260,7 @@ class User implements ArrayAccess { * @return $this */ public function setUserStatus($user_status) { + $this->user_status = $user_status; return $this; } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php new file mode 100644 index 000000000000..7672667a2358 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -0,0 +1,38 @@ +setStatus("placed"); + $this->assertSame("placed", $order->getStatus()); + } + + /** + * @expectedException InvalidArgumentException + */ + public function testOrderException() + { + // initialize the API client + $order = new Swagger\Client\Model\Order(); + $order->setStatus("invalid_value"); + } + +} + +?> + From 44705b566d9d1b210532c8b2f8f646c177728b06 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 6 Jul 2015 15:21:24 +0800 Subject: [PATCH 59/62] add default version for package --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 2 +- .../src/main/resources/php/configuration.mustache | 2 +- samples/client/petstore/php/SwaggerClient-php/composer.json | 1 + 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java index c6e6d65596c3..4034b966cb6b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PhpClientCodegen.java @@ -20,7 +20,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { protected String groupId = "swagger"; protected String artifactId = "swagger-client"; protected String packagePath = "SwaggerClient-php"; - protected String artifactVersion = null; + protected String artifactVersion = "1.0.0"; protected String srcBasePath = "lib"; public PhpClientCodegen() { diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 710edab55b63..a1d8c78c40eb 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -302,7 +302,7 @@ class Configuration { $report .= " OS: ".php_uname()."\n"; $report .= " PHP Version: ".phpversion()."\n"; $report .= " Swagger Spec Version: {{version}}\n"; - $report .= " SDK Package Version: {{version}}\n"; + $report .= " SDK Package Version: {{artifactVersion}}\n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; return $report; diff --git a/samples/client/petstore/php/SwaggerClient-php/composer.json b/samples/client/petstore/php/SwaggerClient-php/composer.json index 5a76d804876b..3b432d83b92b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/composer.json +++ b/samples/client/petstore/php/SwaggerClient-php/composer.json @@ -1,5 +1,6 @@ { "name": "swagger/swagger-client", + "version": "1.0.0", "description": "", "keywords": [ "swagger", From f154e407d2e8cd06f2b798c53788301dddea5bc0 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 13 Jul 2015 00:53:32 +0800 Subject: [PATCH 60/62] update coding style based on CodeSniffer --- .../src/main/resources/php/ApiClient.mustache | 106 +++- .../main/resources/php/ApiException.mustache | 78 ++- .../resources/php/ObjectSerializer.mustache | 97 +++- .../src/main/resources/php/api.mustache | 88 ++- .../main/resources/php/configuration.mustache | 333 ++++++++--- .../src/main/resources/php/model.mustache | 122 +++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 266 +++++---- .../SwaggerClient-php/lib/Api/StoreApi.php | 168 ++++-- .../php/SwaggerClient-php/lib/Api/UserApi.php | 244 +++++--- .../php/SwaggerClient-php/lib/ApiClient.php | 106 +++- .../SwaggerClient-php/lib/ApiException.php | 78 ++- .../SwaggerClient-php/lib/Configuration.php | 333 ++++++++--- .../SwaggerClient-php/lib/Model/Category.php | 135 ++++- .../php/SwaggerClient-php/lib/Model/Order.php | 203 +++++-- .../php/SwaggerClient-php/lib/Model/Pet.php | 203 +++++-- .../php/SwaggerClient-php/lib/Model/Tag.php | 135 ++++- .../php/SwaggerClient-php/lib/Model/User.php | 237 +++++--- .../lib/ObjectSerializer.php | 97 +++- .../php/SwaggerClient-php/lib/PetApi.php | 543 ------------------ .../php/SwaggerClient-php/lib/StoreApi.php | 294 ---------- .../php/SwaggerClient-php/lib/UserApi.php | 518 ----------------- 21 files changed, 2203 insertions(+), 2181 deletions(-) delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php delete mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 158c9c662c00..3c6819ab73be 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -1,4 +1,15 @@ config; } /** - * get the serializer + * Get the serializer * @return ObjectSerializer */ - public function getSerializer() { + public function getSerializer() + { return $this->serializer; } /** * Get API key (with prefix if set) - * @param string $apiKey name of apikey + * @param string $apiKeyIdentifier name of apikey * @return string API key with the prefix */ - public function getApiKeyWithPrefix($apiKeyIdentifier) { + public function getApiKeyWithPrefix($apiKeyIdentifier) + { $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); @@ -82,20 +119,26 @@ class ApiClient { } /** + * Make the HTTP call (Sync) * @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 + * @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 + * @param string $responseType expected response type of the endpoint * @throws \{{invokerPackage}}\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) + { $headers = array(); - # construct the http header - $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); + // construct the http header + $headerParams = array_merge( + (array)$this->config->getDefaultHeaders(), + (array)$headerParams + ); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -104,8 +147,7 @@ class ApiClient { // 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 + } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } @@ -184,21 +226,25 @@ class ApiClient { $data = $http_body; } } else { - throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body); + throw new ApiException( + "[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body + ); } return array($data, $http_header); } - /* - * return the header 'Accept' based on an array of Accept provided + /** + * Return the header 'Accept' based on an array of Accept provided * * @param string[] $accept Array of header + * * @return string Accept (e.g. application/json) */ - public static function selectHeaderAccept($accept) { + public static function selectHeaderAccept($accept) + { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { - return NULL; + return null; } elseif (preg_grep("/application\/json/i", $accept)) { return 'application/json'; } else { @@ -206,13 +252,15 @@ class ApiClient { } } - /* - * return the content type based on an array of content-type provided + /** + * Return the content type based on an array of content-type provided + * + * @param string[] $content_type Array fo content-type * - * @param string[] content_type_array Array fo content-type * @return string Content-Type (e.g. application/json) */ - public static function selectHeaderContentType($content_type) { + public static function selectHeaderContentType($content_type) + { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; } elseif (preg_grep("/application\/json/i", $content_type)) { diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index c57310ccece4..79d1b4fe0a15 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -1,4 +1,14 @@ responseHeaders = $responseHeaders; $this->responseBody = $responseBody; } /** - * Get the HTTP response header + * Gets the HTTP response header * * @return string HTTP response header */ - public function getResponseHeaders() { + public function getResponseHeaders() + { return $this->responseHeaders; } /** - * Get the HTTP response body + * Gets the HTTP response body * * @return string HTTP response body */ - public function getResponseBody() { + public function getResponseBody() + { return $this->responseBody; } /** - * sets the deseralized response object (during deserialization) - * @param mixed $obj + * Sets the deseralized response object (during deserialization) + * @param mixed $obj Deserialized response object + * @return void */ - public function setResponseObject($obj) { + public function setResponseObject($obj) + { $this->responseObject = $obj; } - - public function getResponseObject() { + + /** + * Gets the deseralized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { return $this->responseObject; } } diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 930313865c76..1d63440b66fd 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -1,14 +1,59 @@ toString($value)); } @@ -49,10 +97,13 @@ class ObjectSerializer { * 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 function toQueryValue($object) { + public function toQueryValue($object) + { if (is_array($object)) { return implode(',', $object); } else { @@ -64,10 +115,13 @@ class ObjectSerializer { * 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 function toHeaderValue($value) { + public function toHeaderValue($value) + { return $this->toString($value); } @@ -75,10 +129,13 @@ class ObjectSerializer { * 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 function toFormValue($value) { + public function toFormValue($value) + { if ($value instanceof SplFileObject) { return $value->getRealPath(); } else { @@ -90,10 +147,13 @@ class ObjectSerializer { * 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 function toString($value) { + public function toString($value) + { if ($value instanceof \DateTime) { // datetime in ISO8601 format return $value->format(\DateTime::ISO8601); } else { @@ -104,37 +164,40 @@ class ObjectSerializer { /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string $httpHeader HTTP headers + * * @return object an instance of $class */ - public function deserialize($data, $class, $httpHeader=null) { + public function deserialize($data, $class, $httpHeader=null) + { if (null === $data) { $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); $deserialized = array(); - if(strrpos($inner, ",") !== false) { + if (strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { $deserialized[$key] = $this->deserialize($value, $subClass); } } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + } elseif (strcasecmp(substr($class, -2), '[]') == 0) { $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; - } elseif ($class == 'DateTime') { + } elseif ($class === 'DateTime') { $deserialized = new \DateTime($data); } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { - # determine file name + // determine file name if (preg_match('/Content-Disposition: inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader, $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { @@ -142,7 +205,7 @@ class ObjectSerializer { } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n" , 3, Configuration::getDefaultConfiguration()->getDebugFile()); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); } else { $instance = new $class(); @@ -150,7 +213,7 @@ class ObjectSerializer { $propertySetter = $instance::$setters[$property]; if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { - continue; + continue; } $propertyValue = $data->{$instance::$attributeMap[$property]}; diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 6255a59d8e02..bb40ae7a98d6 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -1,4 +1,14 @@ getConfig()->setHost('{{basePath}}'); @@ -46,17 +71,21 @@ class {{classname}} { } /** + * Get API client * @return \{{invokerPackage}}\ApiClient get the API client */ - public function getApiClient() { + public function getApiClient() + { return $this->apiClient; } /** + * Set the API client * @param \{{invokerPackage}}\ApiClient $apiClient set the API client * @return {{classname}} */ - public function setApiClient(ApiClient $apiClient) { + public function setApiClient(ApiClient $apiClient) + { $this->apiClient = $apiClient; return $this; } @@ -71,7 +100,8 @@ class {{classname}} { {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} * @throws \{{invokerPackage}}\ApiException on non-2xx response */ - public function {{nickname}}({{#allParams}}${{paramName}}{{^required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + public function {{nickname}}({{#allParams}}${{paramName}}{{^required}}=null{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { @@ -93,18 +123,20 @@ class {{classname}} { $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); {{#queryParams}}// query params - if(${{paramName}} !== null) { + if (${{paramName}} !== null) { $queryParams['{{baseName}}'] = $this->apiClient->getSerializer()->toQueryValue(${{paramName}}); }{{/queryParams}} {{#headerParams}}// header params - if(${{paramName}} !== null) { + if (${{paramName}} !== null) { $headerParams['{{baseName}}'] = $this->apiClient->getSerializer()->toHeaderValue(${{paramName}}); }{{/headerParams}} {{#pathParams}}// path params - if(${{paramName}} !== null) { - $resourcePath = str_replace("{" . "{{baseName}}" . "}", - $this->apiClient->getSerializer()->toPathValue(${{paramName}}), - $resourcePath); + if (${{paramName}} !== null) { + $resourcePath = str_replace( + "{" . "{{baseName}}" . "}", + $this->apiClient->getSerializer()->toPathValue(${{paramName}}), + $resourcePath + ); }{{/pathParams}} {{#formParams}}// form params if (${{paramName}} !== null) { @@ -120,8 +152,7 @@ class {{classname}} { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } {{#authMethods}}{{#isApiKey}} $apiKey = $this->apiClient->getApiKeyWithPrefix('{{keyParamName}}'); @@ -132,16 +163,19 @@ class {{classname}} { {{#isOAuth}}//TODO support oauth{{/isOAuth}} {{/authMethods}} // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}}); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} + ); } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} - case {{code}}: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $httpHeader); - $e->setResponseObject($data); - break;{{/dataType}}{{/responses}} + case {{code}}: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $httpHeader); + $e->setResponseObject($data); + break;{{/dataType}}{{/responses}} } throw $e; @@ -151,7 +185,7 @@ class {{classname}} { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'{{returnType}}'); + return $this->apiClient->getSerializer()->deserialize($response, '{{returnType}}'); {{/returnType}} } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index a1d8c78c40eb..73d4000d950f 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -1,4 +1,15 @@ tempFolderPath = sys_get_temp_dir(); } /** - * @param string $key - * @param string $value + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * * @return Configuration */ - public function setApiKey($key, $value) { - $this->apiKeys[$key] = $value; - return $this; + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; } /** - * @param $key + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return Configuration + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * * @return string */ - public function getApiKey($key) { - return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; } /** - * @param string $key - * @param string $value + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * * @return Configuration */ - public function setApiKeyPrefix($key, $value) { - $this->apiKeyPrefixes[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKeyPrefix($key) { - return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; - } - - /** - * @param string $username - * @return Configuration - */ - public function setUsername($username) { + public function setUsername($username) + { $this->username = $username; return $this; } /** - * @return string + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication */ - public function getUsername() { + public function getUsername() + { return $this->username; } /** - * @param string $password + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * * @return Configuration */ - public function setPassword($password) { + public function setPassword($password) + { $this->password = $password; return $this; } /** - * @return string + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication */ - public function getPassword() { + public function getPassword() + { return $this->password; } /** - * add default header + * Adds a default header * - * @param string $headerName header name (e.g. Token) + * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) + * * @return ApiClient */ - public function addDefaultHeader($headerName, $headerValue) { + public function addDefaultHeader($headerName, $headerValue) + { if (!is_string($headerName)) { throw new \InvalidArgumentException('Header name must be a string.'); } @@ -146,46 +251,59 @@ class Configuration { } /** - * get the default header + * Gets the default header * - * @return array default header + * @return array An array of default header(s) */ - public function getDefaultHeaders() { + public function getDefaultHeaders() + { return $this->defaultHeaders; } /** - * delete a default header + * Deletes a default header + * * @param string $headerName the header to delete + * * @return Configuration */ - public function deleteDefaultHeader($headerName) { + public function deleteDefaultHeader($headerName) + { unset($this->defaultHeaders[$headerName]); } /** - * @param string $host + * Sets the host + * + * @param string $host Host + * * @return Configuration */ - public function setHost($host) { + public function setHost($host) + { $this->host = $host; return $this; } /** - * @return string + * Gets the host + * + * @return string Host */ - public function getHost() { + public function getHost() + { return $this->host; } /** - * set the user agent of the api client + * Sets the user agent of the api client * * @param string $userAgent the user agent of the api client + * * @return ApiClient */ - public function setUserAgent($userAgent) { + public function setUserAgent($userAgent) + { if (!is_string($userAgent)) { throw new \InvalidArgumentException('User-agent must be a string.'); } @@ -195,21 +313,24 @@ class Configuration { } /** - * get the user agent of the api client + * Gets the user agent of the api client * * @return string user agent */ - public function getUserAgent() { + public function getUserAgent() + { return $this->userAgent; } /** - * set the HTTP timeout value + * Sets the HTTP timeout value * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * * @return ApiClient */ - public function setCurlTimeout($seconds) { + public function setCurlTimeout($seconds) + { if (!is_numeric($seconds) || $seconds < 0) { throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); } @@ -219,85 +340,117 @@ class Configuration { } /** - * get the HTTP timeout value + * Gets the HTTP timeout value * * @return string HTTP timeout value */ - public function getCurlTimeout() { + public function getCurlTimeout() + { return $this->curlTimeout; } /** - * @param bool $debug + * Sets debug flag + * + * @param bool $debug Debug flag + * * @return Configuration */ - public function setDebug($debug) { + public function setDebug($debug) + { $this->debug = $debug; return $this; } /** + * Gets the debug flag + * * @return bool */ - public function getDebug() { + public function getDebug() + { return $this->debug; } /** - * @param string $debugFile + * Sets the debug file + * + * @param string $debugFile Debug file + * * @return Configuration */ - public function setDebugFile($debugFile) { + public function setDebugFile($debugFile) + { $this->debugFile = $debugFile; return $this; } /** + * Gets the debug file + * * @return string */ - public function getDebugFile() { + public function getDebugFile() + { return $this->debugFile; } /** - * @param string $tempFolderPath + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * * @return Configuration */ - public function setTempFolderPath($tempFolderPath) { + public function setTempFolderPath($tempFolderPath) + { $this->tempFolderPath = $tempFolderPath; return $this; } /** - * @return string + * Gets the temp folder path + * + * @return string Temp folder path */ - public function getTempFolderPath() { + public function getTempFolderPath() + { return $this->tempFolderPath; } - /** + * Gets the default configuration instance + * * @return Configuration */ - public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { - self::$defaultConfiguration = new Configuration(); + public static function getDefaultConfiguration() + { + if (self::$_defaultConfiguration == null) { + self::$_defaultConfiguration = new Configuration(); } - return self::$defaultConfiguration; + return self::$_defaultConfiguration; } /** - * @param Configuration $config + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void */ - public static function setDefaultConfiguration(Configuration $config) { - self::$defaultConfiguration = $config; + public static function setDefaultConfiguration(Configuration $config) + { + self::$_defaultConfiguration = $config; } - /* - * return the report for debugging + /** + * Gets the essential information for debugging + * + * @return string The report for debugging */ - public static function toDebugReport() { + public static function toDebugReport() + { $report = "PHP SDK ({{invokerPackage}}) Debug Report:\n"; $report .= " OS: ".php_uname()."\n"; $report .= " PHP Version: ".phpversion()."\n"; diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index df4ddc0b4f06..861673982f22 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -1,4 +1,17 @@ '{{{datatype}}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ static $attributeMap = array( {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ static $setters = array( {{#vars}}'{{name}}' => '{{setter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ static $getters = array( {{#vars}}'{{name}}' => '{{getter}}'{{#hasMore}}, {{/hasMore}}{{/vars}} ); {{#vars}} - /** @var {{datatype}} ${{name}} {{#description}}{{{description}}} {{/description}}*/ + /** + * ${{name}} {{#description}}{{{description}}}{{/description}} + * @var {{datatype}} + */ protected ${{name}}; {{/vars}} - public function __construct(array $data = null) { + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { if ($data != null) { {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} {{/hasMore}}{{/vars}} @@ -65,19 +105,21 @@ class {{classname}} implements ArrayAccess { } {{#vars}} /** - * get {{name}} + * Gets {{name}} * @return {{datatype}} */ - public function {{getter}}() { + public function {{getter}}() + { return $this->{{name}}; } /** - * set {{name}} - * @param {{datatype}} ${{name}} + * Sets {{name}} + * @param {{datatype}} ${{name}} {{#description}}{{{description}}}{{/description}} * @return $this */ - public function {{setter}}(${{name}}) { + public function {{setter}}(${{name}}) + { {{#isEnum}}$allowed_values = array({{#allowableValues}}{{#values}}"{{{this}}}"{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}); if (!in_array(${{{name}}}, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for '{{name}}', must be one of {{#allowableValues}}{{#values}}'{{{this}}}'{{^-last}}, {{/-last}}{{/values}}{{/allowableValues}}"); @@ -86,23 +128,53 @@ class {{classname}} implements ArrayAccess { return $this; } {{/vars}} - public function offsetExists($offset) { + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { return isset($this->$offset); } - public function offsetGet($offset) { + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { return $this->$offset; } - public function offsetSet($offset, $value) { + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { $this->$offset = $value; } - public function offsetUnset($offset) { + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { unset($this->$offset); } - public function __toString() { + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { if (defined('JSON_PRETTY_PRINT')) { return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 3620252ea513..e9fef44a3ba1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -1,4 +1,14 @@ getConfig()->setHost('http://petstore.swagger.io/v2'); @@ -45,17 +71,21 @@ class PetApi { } /** + * Get API client * @return \Swagger\Client\ApiClient get the API client */ - public function getApiClient() { + public function getApiClient() + { return $this->apiClient; } /** + * Set the API client * @param \Swagger\Client\ApiClient $apiClient set the API client * @return PetApi */ - public function setApiClient(ApiClient $apiClient) { + public function setApiClient(ApiClient $apiClient) + { $this->apiClient = $apiClient; return $this; } @@ -67,10 +97,12 @@ class PetApi { * Update an existing pet * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updatePet($body) { + public function updatePet($body) + { // parse inputs @@ -101,18 +133,20 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -128,10 +162,12 @@ class PetApi { * Add a new pet to the store * * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function addPet($body) { + public function addPet($body) + { // parse inputs @@ -162,18 +198,20 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -189,10 +227,12 @@ class PetApi { * Finds Pets by status * * @param string[] $status Status values that need to be considered for filter (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function findPetsByStatus($status) { + public function findPetsByStatus($status) + { // parse inputs @@ -210,7 +250,7 @@ class PetApi { $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params - if($status !== null) { + if ($status !== null) { $queryParams['status'] = $this->apiClient->getSerializer()->toQueryValue($status); } @@ -222,24 +262,26 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Pet[]' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -249,7 +291,7 @@ class PetApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]'); } @@ -259,10 +301,12 @@ class PetApi { * Finds Pets by tags * * @param string[] $tags Tags to filter by (required) + * * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function findPetsByTags($tags) { + public function findPetsByTags($tags) + { // parse inputs @@ -280,7 +324,7 @@ class PetApi { $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params - if($tags !== null) { + if ($tags !== null) { $queryParams['tags'] = $this->apiClient->getSerializer()->toQueryValue($tags); } @@ -292,24 +336,26 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet[]'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Pet[]' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -319,7 +365,7 @@ class PetApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet[]'); + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]'); } @@ -329,10 +375,12 @@ class PetApi { * Find pet by ID * * @param int $pet_id ID of pet that needs to be fetched (required) + * * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response */ - public function getPetById($pet_id) { + public function getPetById($pet_id) + { // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); @@ -355,10 +403,12 @@ class PetApi { // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); } @@ -367,8 +417,7 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); @@ -382,16 +431,19 @@ class PetApi { //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Pet'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Pet' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -401,7 +453,7 @@ class PetApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Pet'); + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet'); } @@ -413,10 +465,12 @@ class PetApi { * @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 * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updatePetWithForm($pet_id, $name, $status) { + public function updatePetWithForm($pet_id, $name, $status) + { // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); @@ -439,10 +493,12 @@ class PetApi { // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); } // form params if ($name !== null) { @@ -457,18 +513,20 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -485,10 +543,12 @@ class PetApi { * * @param string $api_key (required) * @param int $pet_id Pet id to delete (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function deletePet($api_key, $pet_id) { + public function deletePet($api_key, $pet_id) + { // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); @@ -510,14 +570,16 @@ class PetApi { // header params - if($api_key !== null) { + if ($api_key !== null) { $headerParams['api_key'] = $this->apiClient->getSerializer()->toHeaderValue($api_key); } // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); } @@ -526,18 +588,20 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -555,10 +619,12 @@ class PetApi { * @param int $pet_id ID of pet to update (required) * @param string $additional_metadata Additional data to pass to server (required) * @param \SplFileObject $file file to upload (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function uploadFile($pet_id, $additional_metadata, $file) { + public function uploadFile($pet_id, $additional_metadata, $file) + { // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); @@ -581,10 +647,12 @@ class PetApi { // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->getSerializer()->toPathValue($pet_id), - $resourcePath); + if ($pet_id !== null) { + $resourcePath = str_replace( + "{" . "petId" . "}", + $this->apiClient->getSerializer()->toPathValue($pet_id), + $resourcePath + ); } // form params if ($additional_metadata !== null) { @@ -599,18 +667,20 @@ class PetApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } //TODO support oauth // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 9947628fdf68..5ad1da9e887c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -1,4 +1,14 @@ getConfig()->setHost('http://petstore.swagger.io/v2'); @@ -45,17 +71,21 @@ class StoreApi { } /** + * Get API client * @return \Swagger\Client\ApiClient get the API client */ - public function getApiClient() { + public function getApiClient() + { return $this->apiClient; } /** + * Set the API client * @param \Swagger\Client\ApiClient $apiClient set the API client * @return StoreApi */ - public function setApiClient(ApiClient $apiClient) { + public function setApiClient(ApiClient $apiClient) + { $this->apiClient = $apiClient; return $this; } @@ -66,10 +96,12 @@ class StoreApi { * * Returns pet inventories by status * + * * @return map[string,int] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function getInventory() { + public function getInventory() + { // parse inputs @@ -96,8 +128,7 @@ class StoreApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); @@ -108,16 +139,19 @@ class StoreApi { // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, 'map[string,int]'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, 'map[string,int]' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -127,7 +161,7 @@ class StoreApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'map[string,int]'); + return $this->apiClient->getSerializer()->deserialize($response, 'map[string,int]'); } @@ -137,10 +171,12 @@ class StoreApi { * Place an order for a pet * * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ - public function placeOrder($body) { + public function placeOrder($body) + { // parse inputs @@ -171,21 +207,23 @@ class StoreApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Order' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -195,7 +233,7 @@ class StoreApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order'); } @@ -205,10 +243,12 @@ class StoreApi { * Find purchase order by ID * * @param string $order_id ID of pet that needs to be fetched (required) + * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ - public function getOrderById($order_id) { + public function getOrderById($order_id) + { // verify the required parameter 'order_id' is set if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); @@ -231,10 +271,12 @@ class StoreApi { // path params - if($order_id !== null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath); + if ($order_id !== null) { + $resourcePath = str_replace( + "{" . "orderId" . "}", + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath + ); } @@ -243,21 +285,23 @@ class StoreApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\Order'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\Order' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -267,7 +311,7 @@ class StoreApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\Order'); + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order'); } @@ -277,10 +321,12 @@ class StoreApi { * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function deleteOrder($order_id) { + public function deleteOrder($order_id) + { // verify the required parameter 'order_id' is set if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); @@ -303,10 +349,12 @@ class StoreApi { // path params - if($order_id !== null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->getSerializer()->toPathValue($order_id), - $resourcePath); + if ($order_id !== null) { + $resourcePath = str_replace( + "{" . "orderId" . "}", + $this->apiClient->getSerializer()->toPathValue($order_id), + $resourcePath + ); } @@ -315,15 +363,17 @@ class StoreApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index d0b98f348e31..37f739c50eaf 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -1,4 +1,14 @@ getConfig()->setHost('http://petstore.swagger.io/v2'); @@ -45,17 +71,21 @@ class UserApi { } /** + * Get API client * @return \Swagger\Client\ApiClient get the API client */ - public function getApiClient() { + public function getApiClient() + { return $this->apiClient; } /** + * Set the API client * @param \Swagger\Client\ApiClient $apiClient set the API client * @return UserApi */ - public function setApiClient(ApiClient $apiClient) { + public function setApiClient(ApiClient $apiClient) + { $this->apiClient = $apiClient; return $this; } @@ -67,10 +97,12 @@ class UserApi { * Create user * * @param \Swagger\Client\Model\User $body Created user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUser($body) { + public function createUser($body) + { // parse inputs @@ -101,15 +133,17 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -125,10 +159,12 @@ class UserApi { * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUsersWithArrayInput($body) { + public function createUsersWithArrayInput($body) + { // parse inputs @@ -159,15 +195,17 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -183,10 +221,12 @@ class UserApi { * Creates list of users with given input array * * @param \Swagger\Client\Model\User[] $body List of user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUsersWithListInput($body) { + public function createUsersWithListInput($body) + { // parse inputs @@ -217,15 +257,17 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -242,10 +284,12 @@ class UserApi { * * @param string $username The user name for login (required) * @param string $password The password for login in clear text (required) + * * @return string * @throws \Swagger\Client\ApiException on non-2xx response */ - public function loginUser($username, $password) { + public function loginUser($username, $password) + { // parse inputs @@ -263,10 +307,10 @@ class UserApi { $headerParams['Content-Type'] = ApiClient::selectHeaderContentType(array()); // query params - if($username !== null) { + if ($username !== null) { $queryParams['username'] = $this->apiClient->getSerializer()->toQueryValue($username); }// query params - if($password !== null) { + if ($password !== null) { $queryParams['password'] = $this->apiClient->getSerializer()->toQueryValue($password); } @@ -278,21 +322,23 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, 'string'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, 'string' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -302,7 +348,7 @@ class UserApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'string'); + return $this->apiClient->getSerializer()->deserialize($response, 'string'); } @@ -311,10 +357,12 @@ class UserApi { * * Logs out current logged in user session * + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function logoutUser() { + public function logoutUser() + { // parse inputs @@ -341,15 +389,17 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -365,10 +415,12 @@ class UserApi { * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response */ - public function getUserByName($username) { + public function getUserByName($username) + { // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); @@ -391,10 +443,12 @@ class UserApi { // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath); + if ($username !== null) { + $resourcePath = str_replace( + "{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath + ); } @@ -403,21 +457,23 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, '\Swagger\Client\Model\User'); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams, '\Swagger\Client\Model\User' + ); } catch (ApiException $e) { switch ($e->getCode()) { - case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $httpHeader); - $e->setResponseObject($data); - break; + case 200: + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $httpHeader); + $e->setResponseObject($data); + break; } throw $e; @@ -427,7 +483,7 @@ class UserApi { return null; } - return $this->apiClient->getSerializer()->deserialize($response,'\Swagger\Client\Model\User'); + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User'); } @@ -438,10 +494,12 @@ class UserApi { * * @param string $username name that need to be deleted (required) * @param \Swagger\Client\Model\User $body Updated user object (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updateUser($username, $body) { + public function updateUser($username, $body) + { // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); @@ -464,10 +522,12 @@ class UserApi { // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath); + if ($username !== null) { + $resourcePath = str_replace( + "{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath + ); } // body params @@ -480,15 +540,17 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } @@ -504,10 +566,12 @@ class UserApi { * Delete user * * @param string $username The name that needs to be deleted (required) + * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function deleteUser($username) { + public function deleteUser($username) + { // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); @@ -530,10 +594,12 @@ class UserApi { // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->getSerializer()->toPathValue($username), - $resourcePath); + if ($username !== null) { + $resourcePath = str_replace( + "{" . "username" . "}", + $this->apiClient->getSerializer()->toPathValue($username), + $resourcePath + ); } @@ -542,15 +608,17 @@ class UserApi { if (isset($_tempBody)) { $httpBody = $_tempBody; // $_tempBody is the method argument, if present } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; + $httpBody = $formParams; // for HTTP post (form) } // make the API Call - try { - list($response, $httpHeader) = $this->apiClient->callApi($resourcePath, $method, - $queryParams, $httpBody, - $headerParams); + try + { + list($response, $httpHeader) = $this->apiClient->callApi( + $resourcePath, $method, + $queryParams, $httpBody, + $headerParams + ); } catch (ApiException $e) { switch ($e->getCode()) { } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 1f466389cfdb..bf4f4e482bf6 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -1,4 +1,15 @@ config; } /** - * get the serializer + * Get the serializer * @return ObjectSerializer */ - public function getSerializer() { + public function getSerializer() + { return $this->serializer; } /** * Get API key (with prefix if set) - * @param string $apiKey name of apikey + * @param string $apiKeyIdentifier name of apikey * @return string API key with the prefix */ - public function getApiKeyWithPrefix($apiKeyIdentifier) { + public function getApiKeyWithPrefix($apiKeyIdentifier) + { $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); @@ -82,20 +119,26 @@ class ApiClient { } /** + * Make the HTTP call (Sync) * @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 + * @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 + * @param string $responseType expected response type of the endpoint * @throws \Swagger\Client\ApiException on a non 2xx response * @return mixed */ - public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { + public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) + { $headers = array(); - # construct the http header - $headerParams = array_merge((array)$this->config->getDefaultHeaders(), (array)$headerParams); + // construct the http header + $headerParams = array_merge( + (array)$this->config->getDefaultHeaders(), + (array)$headerParams + ); foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; @@ -104,8 +147,7 @@ class ApiClient { // 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 + } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } @@ -184,21 +226,25 @@ class ApiClient { $data = $http_body; } } else { - throw new ApiException("[".$response_info['http_code']."] Error connecting to the API ($url)", - $response_info['http_code'], $http_header, $http_body); + throw new ApiException( + "[".$response_info['http_code']."] Error connecting to the API ($url)", + $response_info['http_code'], $http_header, $http_body + ); } return array($data, $http_header); } - /* - * return the header 'Accept' based on an array of Accept provided + /** + * Return the header 'Accept' based on an array of Accept provided * * @param string[] $accept Array of header + * * @return string Accept (e.g. application/json) */ - public static function selectHeaderAccept($accept) { + public static function selectHeaderAccept($accept) + { if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { - return NULL; + return null; } elseif (preg_grep("/application\/json/i", $accept)) { return 'application/json'; } else { @@ -206,13 +252,15 @@ class ApiClient { } } - /* - * return the content type based on an array of content-type provided + /** + * Return the content type based on an array of content-type provided + * + * @param string[] $content_type Array fo content-type * - * @param string[] content_type_array Array fo content-type * @return string Content-Type (e.g. application/json) */ - public static function selectHeaderContentType($content_type) { + public static function selectHeaderContentType($content_type) + { if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { return 'application/json'; } elseif (preg_grep("/application\/json/i", $content_type)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index b1342921a0a1..ce6c19e245f1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -1,4 +1,14 @@ responseHeaders = $responseHeaders; $this->responseBody = $responseBody; } /** - * Get the HTTP response header + * Gets the HTTP response header * * @return string HTTP response header */ - public function getResponseHeaders() { + public function getResponseHeaders() + { return $this->responseHeaders; } /** - * Get the HTTP response body + * Gets the HTTP response body * * @return string HTTP response body */ - public function getResponseBody() { + public function getResponseBody() + { return $this->responseBody; } /** - * sets the deseralized response object (during deserialization) - * @param mixed $obj + * Sets the deseralized response object (during deserialization) + * @param mixed $obj Deserialized response object + * @return void */ - public function setResponseObject($obj) { + public function setResponseObject($obj) + { $this->responseObject = $obj; } - - public function getResponseObject() { + + /** + * Gets the deseralized response object (during deserialization) + * + * @return mixed the deserialized response object + */ + public function getResponseObject() + { return $this->responseObject; } } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 664293f1a13c..002df7fc7133 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -1,4 +1,15 @@ tempFolderPath = sys_get_temp_dir(); } /** - * @param string $key - * @param string $value + * Sets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $key API key or token + * * @return Configuration */ - public function setApiKey($key, $value) { - $this->apiKeys[$key] = $value; - return $this; + public function setApiKey($apiKeyIdentifier, $key) + { + $this->apiKeys[$apiKeyIdentifier] = $key; + return $this; } /** - * @param $key + * Gets API key + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * + * @return string API key or token + */ + public function getApiKey($apiKeyIdentifier) + { + return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; + } + + /** + * Sets the prefix for API key (e.g. Bearer) + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * @param string $prefix API key prefix, e.g. Bearer + * + * @return Configuration + */ + public function setApiKeyPrefix($apiKeyIdentifier, $prefix) + { + $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; + return $this; + } + + /** + * Gets API key prefix + * + * @param string $apiKeyIdentifier API key identifier (authentication scheme) + * * @return string */ - public function getApiKey($key) { - return isset($this->apiKeys[$key]) ? $this->apiKeys[$key] : null; + public function getApiKeyPrefix($apiKeyIdentifier) + { + return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; } /** - * @param string $key - * @param string $value + * Sets the username for HTTP basic authentication + * + * @param string $username Username for HTTP basic authentication + * * @return Configuration */ - public function setApiKeyPrefix($key, $value) { - $this->apiKeyPrefixes[$key] = $value; - return $this; - } - - /** - * @param $key - * @return string - */ - public function getApiKeyPrefix($key) { - return isset($this->apiKeyPrefixes[$key]) ? $this->apiKeyPrefixes[$key] : null; - } - - /** - * @param string $username - * @return Configuration - */ - public function setUsername($username) { + public function setUsername($username) + { $this->username = $username; return $this; } /** - * @return string + * Gets the username for HTTP basic authentication + * + * @return string Username for HTTP basic authentication */ - public function getUsername() { + public function getUsername() + { return $this->username; } /** - * @param string $password + * Sets the password for HTTP basic authentication + * + * @param string $password Password for HTTP basic authentication + * * @return Configuration */ - public function setPassword($password) { + public function setPassword($password) + { $this->password = $password; return $this; } /** - * @return string + * Gets the password for HTTP basic authentication + * + * @return string Password for HTTP basic authentication */ - public function getPassword() { + public function getPassword() + { return $this->password; } /** - * add default header + * Adds a default header * - * @param string $headerName header name (e.g. Token) + * @param string $headerName header name (e.g. Token) * @param string $headerValue header value (e.g. 1z8wp3) + * * @return ApiClient */ - public function addDefaultHeader($headerName, $headerValue) { + public function addDefaultHeader($headerName, $headerValue) + { if (!is_string($headerName)) { throw new \InvalidArgumentException('Header name must be a string.'); } @@ -146,46 +251,59 @@ class Configuration { } /** - * get the default header + * Gets the default header * - * @return array default header + * @return array An array of default header(s) */ - public function getDefaultHeaders() { + public function getDefaultHeaders() + { return $this->defaultHeaders; } /** - * delete a default header + * Deletes a default header + * * @param string $headerName the header to delete + * * @return Configuration */ - public function deleteDefaultHeader($headerName) { + public function deleteDefaultHeader($headerName) + { unset($this->defaultHeaders[$headerName]); } /** - * @param string $host + * Sets the host + * + * @param string $host Host + * * @return Configuration */ - public function setHost($host) { + public function setHost($host) + { $this->host = $host; return $this; } /** - * @return string + * Gets the host + * + * @return string Host */ - public function getHost() { + public function getHost() + { return $this->host; } /** - * set the user agent of the api client + * Sets the user agent of the api client * * @param string $userAgent the user agent of the api client + * * @return ApiClient */ - public function setUserAgent($userAgent) { + public function setUserAgent($userAgent) + { if (!is_string($userAgent)) { throw new \InvalidArgumentException('User-agent must be a string.'); } @@ -195,21 +313,24 @@ class Configuration { } /** - * get the user agent of the api client + * Gets the user agent of the api client * * @return string user agent */ - public function getUserAgent() { + public function getUserAgent() + { return $this->userAgent; } /** - * set the HTTP timeout value + * Sets the HTTP timeout value * * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] + * * @return ApiClient */ - public function setCurlTimeout($seconds) { + public function setCurlTimeout($seconds) + { if (!is_numeric($seconds) || $seconds < 0) { throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); } @@ -219,85 +340,117 @@ class Configuration { } /** - * get the HTTP timeout value + * Gets the HTTP timeout value * * @return string HTTP timeout value */ - public function getCurlTimeout() { + public function getCurlTimeout() + { return $this->curlTimeout; } /** - * @param bool $debug + * Sets debug flag + * + * @param bool $debug Debug flag + * * @return Configuration */ - public function setDebug($debug) { + public function setDebug($debug) + { $this->debug = $debug; return $this; } /** + * Gets the debug flag + * * @return bool */ - public function getDebug() { + public function getDebug() + { return $this->debug; } /** - * @param string $debugFile + * Sets the debug file + * + * @param string $debugFile Debug file + * * @return Configuration */ - public function setDebugFile($debugFile) { + public function setDebugFile($debugFile) + { $this->debugFile = $debugFile; return $this; } /** + * Gets the debug file + * * @return string */ - public function getDebugFile() { + public function getDebugFile() + { return $this->debugFile; } /** - * @param string $tempFolderPath + * Sets the temp folder path + * + * @param string $tempFolderPath Temp folder path + * * @return Configuration */ - public function setTempFolderPath($tempFolderPath) { + public function setTempFolderPath($tempFolderPath) + { $this->tempFolderPath = $tempFolderPath; return $this; } /** - * @return string + * Gets the temp folder path + * + * @return string Temp folder path */ - public function getTempFolderPath() { + public function getTempFolderPath() + { return $this->tempFolderPath; } - /** + * Gets the default configuration instance + * * @return Configuration */ - public static function getDefaultConfiguration() { - if (self::$defaultConfiguration == null) { - self::$defaultConfiguration = new Configuration(); + public static function getDefaultConfiguration() + { + if (self::$_defaultConfiguration == null) { + self::$_defaultConfiguration = new Configuration(); } - return self::$defaultConfiguration; + return self::$_defaultConfiguration; } /** - * @param Configuration $config + * Sets the detault configuration instance + * + * @param Configuration $config An instance of the Configuration Object + * + * @return void */ - public static function setDefaultConfiguration(Configuration $config) { - self::$defaultConfiguration = $config; + public static function setDefaultConfiguration(Configuration $config) + { + self::$_defaultConfiguration = $config; } - /* - * return the report for debugging + /** + * Gets the essential information for debugging + * + * @return string The report for debugging */ - public static function toDebugReport() { + public static function toDebugReport() + { $report = "PHP SDK (Swagger\Client) Debug Report:\n"; $report .= " OS: ".php_uname()."\n"; $report .= " PHP Version: ".phpversion()."\n"; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 02b3d3cde0f6..444c3c1ed7e1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -1,4 +1,15 @@ 'int', 'name' => 'string' ); - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - /** @var int $id */ + /** + * $id + * @var int + */ protected $id; - /** @var string $name */ + /** + * $name + * @var string + */ protected $name; - public function __construct(array $data = null) { + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { if ($data != null) { $this->id = $data["id"]; $this->name = $data["name"]; @@ -66,60 +109,94 @@ class Category implements ArrayAccess { } /** - * get id + * Gets id * @return int */ - public function getId() { + public function getId() + { return $this->id; } /** - * set id - * @param int $id + * Sets id + * @param int $id * @return $this */ - public function setId($id) { + public function setId($id) + { $this->id = $id; return $this; } /** - * get name + * Gets name * @return string */ - public function getName() { + public function getName() + { return $this->name; } /** - * set name - * @param string $name + * Sets name + * @param string $name * @return $this */ - public function setName($name) { + public function setName($name) + { $this->name = $name; return $this; } - public function offsetExists($offset) { + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { return isset($this->$offset); } - public function offsetGet($offset) { + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { return $this->$offset; } - public function offsetSet($offset, $value) { + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { $this->$offset = $value; } - public function offsetUnset($offset) { + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { unset($this->$offset); } - public function __toString() { + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { if (defined('JSON_PRETTY_PRINT')) { return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index 9b20b159ab9f..b803bd7325e7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -1,4 +1,15 @@ 'int', 'pet_id' => 'int', @@ -37,7 +59,10 @@ class Order implements ArrayAccess { 'complete' => 'bool' ); - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ static $attributeMap = array( 'id' => 'id', 'pet_id' => 'petId', @@ -47,7 +72,10 @@ class Order implements ArrayAccess { 'complete' => 'complete' ); - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ static $setters = array( 'id' => 'setId', 'pet_id' => 'setPetId', @@ -57,7 +85,10 @@ class Order implements ArrayAccess { 'complete' => 'setComplete' ); - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ static $getters = array( 'id' => 'getId', 'pet_id' => 'getPetId', @@ -68,25 +99,49 @@ class Order implements ArrayAccess { ); - /** @var int $id */ + /** + * $id + * @var int + */ protected $id; - /** @var int $pet_id */ + /** + * $pet_id + * @var int + */ protected $pet_id; - /** @var int $quantity */ + /** + * $quantity + * @var int + */ protected $quantity; - /** @var \DateTime $ship_date */ + /** + * $ship_date + * @var \DateTime + */ protected $ship_date; - /** @var string $status Order Status */ + /** + * $status Order Status + * @var string + */ protected $status; - /** @var bool $complete */ + /** + * $complete + * @var bool + */ protected $complete; - public function __construct(array $data = null) { + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { if ($data != null) { $this->id = $data["id"]; $this->pet_id = $data["pet_id"]; @@ -98,95 +153,105 @@ class Order implements ArrayAccess { } /** - * get id + * Gets id * @return int */ - public function getId() { + public function getId() + { return $this->id; } /** - * set id - * @param int $id + * Sets id + * @param int $id * @return $this */ - public function setId($id) { + public function setId($id) + { $this->id = $id; return $this; } /** - * get pet_id + * Gets pet_id * @return int */ - public function getPetId() { + public function getPetId() + { return $this->pet_id; } /** - * set pet_id - * @param int $pet_id + * Sets pet_id + * @param int $pet_id * @return $this */ - public function setPetId($pet_id) { + public function setPetId($pet_id) + { $this->pet_id = $pet_id; return $this; } /** - * get quantity + * Gets quantity * @return int */ - public function getQuantity() { + public function getQuantity() + { return $this->quantity; } /** - * set quantity - * @param int $quantity + * Sets quantity + * @param int $quantity * @return $this */ - public function setQuantity($quantity) { + public function setQuantity($quantity) + { $this->quantity = $quantity; return $this; } /** - * get ship_date + * Gets ship_date * @return \DateTime */ - public function getShipDate() { + public function getShipDate() + { return $this->ship_date; } /** - * set ship_date - * @param \DateTime $ship_date + * Sets ship_date + * @param \DateTime $ship_date * @return $this */ - public function setShipDate($ship_date) { + public function setShipDate($ship_date) + { $this->ship_date = $ship_date; return $this; } /** - * get status + * Gets status * @return string */ - public function getStatus() { + public function getStatus() + { return $this->status; } /** - * set status - * @param string $status + * Sets status + * @param string $status Order Status * @return $this */ - public function setStatus($status) { + public function setStatus($status) + { $allowed_values = array("placed", "approved", "delivered"); if (!in_array($status, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'placed', 'approved', 'delivered'"); @@ -196,41 +261,73 @@ class Order implements ArrayAccess { } /** - * get complete + * Gets complete * @return bool */ - public function getComplete() { + public function getComplete() + { return $this->complete; } /** - * set complete - * @param bool $complete + * Sets complete + * @param bool $complete * @return $this */ - public function setComplete($complete) { + public function setComplete($complete) + { $this->complete = $complete; return $this; } - public function offsetExists($offset) { + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { return isset($this->$offset); } - public function offsetGet($offset) { + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { return $this->$offset; } - public function offsetSet($offset, $value) { + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { $this->$offset = $value; } - public function offsetUnset($offset) { + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { unset($this->$offset); } - public function __toString() { + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { if (defined('JSON_PRETTY_PRINT')) { return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 03c5b173532f..6871ea9d9be5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -1,4 +1,15 @@ 'int', 'category' => '\Swagger\Client\Model\Category', @@ -37,7 +59,10 @@ class Pet implements ArrayAccess { 'status' => 'string' ); - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ static $attributeMap = array( 'id' => 'id', 'category' => 'category', @@ -47,7 +72,10 @@ class Pet implements ArrayAccess { 'status' => 'status' ); - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ static $setters = array( 'id' => 'setId', 'category' => 'setCategory', @@ -57,7 +85,10 @@ class Pet implements ArrayAccess { 'status' => 'setStatus' ); - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ static $getters = array( 'id' => 'getId', 'category' => 'getCategory', @@ -68,25 +99,49 @@ class Pet implements ArrayAccess { ); - /** @var int $id */ + /** + * $id + * @var int + */ protected $id; - /** @var \Swagger\Client\Model\Category $category */ + /** + * $category + * @var \Swagger\Client\Model\Category + */ protected $category; - /** @var string $name */ + /** + * $name + * @var string + */ protected $name; - /** @var string[] $photo_urls */ + /** + * $photo_urls + * @var string[] + */ protected $photo_urls; - /** @var \Swagger\Client\Model\Tag[] $tags */ + /** + * $tags + * @var \Swagger\Client\Model\Tag[] + */ protected $tags; - /** @var string $status pet status in the store */ + /** + * $status pet status in the store + * @var string + */ protected $status; - public function __construct(array $data = null) { + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { if ($data != null) { $this->id = $data["id"]; $this->category = $data["category"]; @@ -98,114 +153,126 @@ class Pet implements ArrayAccess { } /** - * get id + * Gets id * @return int */ - public function getId() { + public function getId() + { return $this->id; } /** - * set id - * @param int $id + * Sets id + * @param int $id * @return $this */ - public function setId($id) { + public function setId($id) + { $this->id = $id; return $this; } /** - * get category + * Gets category * @return \Swagger\Client\Model\Category */ - public function getCategory() { + public function getCategory() + { return $this->category; } /** - * set category - * @param \Swagger\Client\Model\Category $category + * Sets category + * @param \Swagger\Client\Model\Category $category * @return $this */ - public function setCategory($category) { + public function setCategory($category) + { $this->category = $category; return $this; } /** - * get name + * Gets name * @return string */ - public function getName() { + public function getName() + { return $this->name; } /** - * set name - * @param string $name + * Sets name + * @param string $name * @return $this */ - public function setName($name) { + public function setName($name) + { $this->name = $name; return $this; } /** - * get photo_urls + * Gets photo_urls * @return string[] */ - public function getPhotoUrls() { + public function getPhotoUrls() + { return $this->photo_urls; } /** - * set photo_urls - * @param string[] $photo_urls + * Sets photo_urls + * @param string[] $photo_urls * @return $this */ - public function setPhotoUrls($photo_urls) { + public function setPhotoUrls($photo_urls) + { $this->photo_urls = $photo_urls; return $this; } /** - * get tags + * Gets tags * @return \Swagger\Client\Model\Tag[] */ - public function getTags() { + public function getTags() + { return $this->tags; } /** - * set tags - * @param \Swagger\Client\Model\Tag[] $tags + * Sets tags + * @param \Swagger\Client\Model\Tag[] $tags * @return $this */ - public function setTags($tags) { + public function setTags($tags) + { $this->tags = $tags; return $this; } /** - * get status + * Gets status * @return string */ - public function getStatus() { + public function getStatus() + { return $this->status; } /** - * set status - * @param string $status + * Sets status + * @param string $status pet status in the store * @return $this */ - public function setStatus($status) { + public function setStatus($status) + { $allowed_values = array("available", "pending", "sold"); if (!in_array($status, $allowed_values)) { throw new \InvalidArgumentException("Invalid value for 'status', must be one of 'available', 'pending', 'sold'"); @@ -214,23 +281,53 @@ class Pet implements ArrayAccess { return $this; } - public function offsetExists($offset) { + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { return isset($this->$offset); } - public function offsetGet($offset) { + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { return $this->$offset; } - public function offsetSet($offset, $value) { + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { $this->$offset = $value; } - public function offsetUnset($offset) { + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { unset($this->$offset); } - public function __toString() { + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { if (defined('JSON_PRETTY_PRINT')) { return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 279618ac3bea..bcecb32fa7e2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -1,4 +1,15 @@ 'int', 'name' => 'string' ); - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ static $attributeMap = array( 'id' => 'id', 'name' => 'name' ); - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ static $setters = array( 'id' => 'setId', 'name' => 'setName' ); - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ static $getters = array( 'id' => 'getId', 'name' => 'getName' ); - /** @var int $id */ + /** + * $id + * @var int + */ protected $id; - /** @var string $name */ + /** + * $name + * @var string + */ protected $name; - public function __construct(array $data = null) { + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { if ($data != null) { $this->id = $data["id"]; $this->name = $data["name"]; @@ -66,60 +109,94 @@ class Tag implements ArrayAccess { } /** - * get id + * Gets id * @return int */ - public function getId() { + public function getId() + { return $this->id; } /** - * set id - * @param int $id + * Sets id + * @param int $id * @return $this */ - public function setId($id) { + public function setId($id) + { $this->id = $id; return $this; } /** - * get name + * Gets name * @return string */ - public function getName() { + public function getName() + { return $this->name; } /** - * set name - * @param string $name + * Sets name + * @param string $name * @return $this */ - public function setName($name) { + public function setName($name) + { $this->name = $name; return $this; } - public function offsetExists($offset) { + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { return isset($this->$offset); } - public function offsetGet($offset) { + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { return $this->$offset; } - public function offsetSet($offset, $value) { + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { $this->$offset = $value; } - public function offsetUnset($offset) { + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { unset($this->$offset); } - public function __toString() { + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { if (defined('JSON_PRETTY_PRINT')) { return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 7dd45220cf93..1650635d8cec 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -1,4 +1,15 @@ 'int', 'username' => 'string', @@ -39,7 +61,10 @@ class User implements ArrayAccess { 'user_status' => 'int' ); - /** @var string[] Array of attributes where the key is the local name, and the value is the original name */ + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ static $attributeMap = array( 'id' => 'id', 'username' => 'username', @@ -51,7 +76,10 @@ class User implements ArrayAccess { 'user_status' => 'userStatus' ); - /** @var string[] Array of attributes to setter functions (for deserialization of responses) */ + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ static $setters = array( 'id' => 'setId', 'username' => 'setUsername', @@ -63,7 +91,10 @@ class User implements ArrayAccess { 'user_status' => 'setUserStatus' ); - /** @var string[] Array of attributes to getter functions (for serialization of requests) */ + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ static $getters = array( 'id' => 'getId', 'username' => 'getUsername', @@ -76,31 +107,61 @@ class User implements ArrayAccess { ); - /** @var int $id */ + /** + * $id + * @var int + */ protected $id; - /** @var string $username */ + /** + * $username + * @var string + */ protected $username; - /** @var string $first_name */ + /** + * $first_name + * @var string + */ protected $first_name; - /** @var string $last_name */ + /** + * $last_name + * @var string + */ protected $last_name; - /** @var string $email */ + /** + * $email + * @var string + */ protected $email; - /** @var string $password */ + /** + * $password + * @var string + */ protected $password; - /** @var string $phone */ + /** + * $phone + * @var string + */ protected $phone; - /** @var int $user_status User Status */ + /** + * $user_status User Status + * @var int + */ protected $user_status; - public function __construct(array $data = null) { + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { if ($data != null) { $this->id = $data["id"]; $this->username = $data["username"]; @@ -114,174 +175,220 @@ class User implements ArrayAccess { } /** - * get id + * Gets id * @return int */ - public function getId() { + public function getId() + { return $this->id; } /** - * set id - * @param int $id + * Sets id + * @param int $id * @return $this */ - public function setId($id) { + public function setId($id) + { $this->id = $id; return $this; } /** - * get username + * Gets username * @return string */ - public function getUsername() { + public function getUsername() + { return $this->username; } /** - * set username - * @param string $username + * Sets username + * @param string $username * @return $this */ - public function setUsername($username) { + public function setUsername($username) + { $this->username = $username; return $this; } /** - * get first_name + * Gets first_name * @return string */ - public function getFirstName() { + public function getFirstName() + { return $this->first_name; } /** - * set first_name - * @param string $first_name + * Sets first_name + * @param string $first_name * @return $this */ - public function setFirstName($first_name) { + public function setFirstName($first_name) + { $this->first_name = $first_name; return $this; } /** - * get last_name + * Gets last_name * @return string */ - public function getLastName() { + public function getLastName() + { return $this->last_name; } /** - * set last_name - * @param string $last_name + * Sets last_name + * @param string $last_name * @return $this */ - public function setLastName($last_name) { + public function setLastName($last_name) + { $this->last_name = $last_name; return $this; } /** - * get email + * Gets email * @return string */ - public function getEmail() { + public function getEmail() + { return $this->email; } /** - * set email - * @param string $email + * Sets email + * @param string $email * @return $this */ - public function setEmail($email) { + public function setEmail($email) + { $this->email = $email; return $this; } /** - * get password + * Gets password * @return string */ - public function getPassword() { + public function getPassword() + { return $this->password; } /** - * set password - * @param string $password + * Sets password + * @param string $password * @return $this */ - public function setPassword($password) { + public function setPassword($password) + { $this->password = $password; return $this; } /** - * get phone + * Gets phone * @return string */ - public function getPhone() { + public function getPhone() + { return $this->phone; } /** - * set phone - * @param string $phone + * Sets phone + * @param string $phone * @return $this */ - public function setPhone($phone) { + public function setPhone($phone) + { $this->phone = $phone; return $this; } /** - * get user_status + * Gets user_status * @return int */ - public function getUserStatus() { + public function getUserStatus() + { return $this->user_status; } /** - * set user_status - * @param int $user_status + * Sets user_status + * @param int $user_status User Status * @return $this */ - public function setUserStatus($user_status) { + public function setUserStatus($user_status) + { $this->user_status = $user_status; return $this; } - public function offsetExists($offset) { + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { return isset($this->$offset); } - public function offsetGet($offset) { + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { return $this->$offset; } - public function offsetSet($offset, $value) { + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { $this->$offset = $value; } - public function offsetUnset($offset) { + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { unset($this->$offset); } - public function __toString() { + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { if (defined('JSON_PRETTY_PRINT')) { return json_encode(get_object_vars($this), JSON_PRETTY_PRINT); } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 3f78ea55bb93..535c623118ac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -1,14 +1,59 @@ toString($value)); } @@ -49,10 +97,13 @@ class ObjectSerializer { * 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 function toQueryValue($object) { + public function toQueryValue($object) + { if (is_array($object)) { return implode(',', $object); } else { @@ -64,10 +115,13 @@ class ObjectSerializer { * 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 function toHeaderValue($value) { + public function toHeaderValue($value) + { return $this->toString($value); } @@ -75,10 +129,13 @@ class ObjectSerializer { * 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 function toFormValue($value) { + public function toFormValue($value) + { if ($value instanceof SplFileObject) { return $value->getRealPath(); } else { @@ -90,10 +147,13 @@ class ObjectSerializer { * 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 function toString($value) { + public function toString($value) + { if ($value instanceof \DateTime) { // datetime in ISO8601 format return $value->format(\DateTime::ISO8601); } else { @@ -104,37 +164,40 @@ class ObjectSerializer { /** * Deserialize a JSON string into an object * - * @param mixed $data object or primitive to be deserialized - * @param string $class class name is passed as a string + * @param mixed $data object or primitive to be deserialized + * @param string $class class name is passed as a string + * @param string $httpHeader HTTP headers + * * @return object an instance of $class */ - public function deserialize($data, $class, $httpHeader=null) { + public function deserialize($data, $class, $httpHeader=null) + { if (null === $data) { $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] + } elseif (substr($class, 0, 4) === 'map[') { // for associative array e.g. map[string,int] $inner = substr($class, 4, -1); $deserialized = array(); - if(strrpos($inner, ",") !== false) { + if (strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { $deserialized[$key] = $this->deserialize($value, $subClass); } } - } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + } elseif (strcasecmp(substr($class, -2), '[]') == 0) { $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { $values[] = $this->deserialize($value, $subClass); } $deserialized = $values; - } elseif ($class == 'DateTime') { + } elseif ($class === 'DateTime') { $deserialized = new \DateTime($data); } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { - # determine file name + // determine file name if (preg_match('/Content-Disposition: inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader, $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { @@ -142,7 +205,7 @@ class ObjectSerializer { } $deserialized = new \SplFileObject($filename, "w"); $byte_written = $deserialized->fwrite($data); - error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n" , 3, Configuration::getDefaultConfiguration()->getDebugFile()); + error_log("[INFO] Written $byte_written byte to $filename. Please move the file to a proper folder or delete the temp file after processing.\n", 3, Configuration::getDefaultConfiguration()->getDebugFile()); } else { $instance = new $class(); @@ -150,7 +213,7 @@ class ObjectSerializer { $propertySetter = $instance::$setters[$property]; if (!isset($propertySetter) || !isset($data->{$instance::$attributeMap[$property]})) { - continue; + continue; } $propertyValue = $data->{$instance::$attributeMap[$property]}; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php deleted file mode 100644 index 4d1cba21c3e8..000000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ /dev/null @@ -1,543 +0,0 @@ -apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - - private $apiClient; // instance of the ApiClient - - /** - * get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * set the API client - */ - public function setApiClient($apiClient) { - $this->apiClient = $apiClient; - } - - - /** - * updatePet - * - * Update an existing pet - * - * @param Pet $body Pet object that needs to be added to the store (required) - * @return void - */ - public function updatePet($body) { - - - // parse inputs - $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * addPet - * - * Add a new pet to the store - * - * @param Pet $body Pet object that needs to be added to the store (required) - * @return void - */ - public function addPet($body) { - - - // parse inputs - $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml')); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * findPetsByStatus - * - * Finds Pets by status - * - * @param array[string] $status Status values that need to be considered for filter (required) - * @return array[Pet] - */ - public function findPetsByStatus($status) { - - - // parse inputs - $resourcePath = "/pet/findByStatus"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - // query params - if($status !== null) { - $queryParams['status'] = $this->apiClient->toQueryValue($status); - } - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->deserialize($response,'array[Pet]'); - return $responseObject; - } - - /** - * findPetsByTags - * - * Finds Pets by tags - * - * @param array[string] $tags Tags to filter by (required) - * @return array[Pet] - */ - public function findPetsByTags($tags) { - - - // parse inputs - $resourcePath = "/pet/findByTags"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - // query params - if($tags !== null) { - $queryParams['tags'] = $this->apiClient->toQueryValue($tags); - } - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->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 - */ - public function getPetById($pet_id) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('api_key', 'petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->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 - */ - public function updatePetWithForm($pet_id, $name, $status) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded')); - - - - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); - } - // form params - if ($name !== null) { - $formParams['name'] = $this->apiClient->toFormValue($name); - }// form params - if ($status !== null) { - $formParams['status'] = $this->apiClient->toFormValue($status); - } - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * deletePet - * - * Deletes a pet - * - * @param string $api_key (required) - * @param int $pet_id Pet id to delete (required) - * @return void - */ - public function deletePet($api_key, $pet_id) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - // header params - if($api_key !== null) { - $headerParams['api_key'] = $this->apiClient->toHeaderValue($api_key); - } - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * 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 string $file file to upload (required) - * @return void - */ - public function uploadFile($pet_id, $additional_metadata, $file) { - - // verify the required parameter 'pet_id' is set - if ($pet_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); - } - - - // parse inputs - $resourcePath = "/pet/{petId}/uploadImage"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data')); - - - - // path params - if($pet_id !== null) { - $resourcePath = str_replace("{" . "petId" . "}", - $this->apiClient->toPathValue($pet_id), $resourcePath); - } - // form params - if ($additional_metadata !== null) { - $formParams['additionalMetadata'] = $this->apiClient->toFormValue($additional_metadata); - }// form params - if ($file !== null) { - $formParams['file'] = '@'.$this->apiClient->toFormValue($file); - } - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('petstore_auth'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - -} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php deleted file mode 100644 index 87937a60283f..000000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ /dev/null @@ -1,294 +0,0 @@ -apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - - private $apiClient; // instance of the ApiClient - - /** - * get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * set the API client - */ - public function setApiClient($apiClient) { - $this->apiClient = $apiClient; - } - - - /** - * getInventory - * - * Returns pet inventories by status - * - * @return map[string,int] - */ - public function getInventory() { - - - // parse inputs - $resourcePath = "/store/inventory"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array('api_key'); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->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 - */ - public function placeOrder($body) { - - - // parse inputs - $resourcePath = "/store/order"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->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 - */ - public function getOrderById($order_id) { - - // verify the required parameter 'order_id' is set - if ($order_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); - } - - - // parse inputs - $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - // path params - if($order_id !== null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($order_id), $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->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 - */ - public function deleteOrder($order_id) { - - // verify the required parameter 'order_id' is set - if ($order_id === null) { - throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); - } - - - // parse inputs - $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - // path params - if($order_id !== null) { - $resourcePath = str_replace("{" . "orderId" . "}", - $this->apiClient->toPathValue($order_id), $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - -} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php deleted file mode 100644 index 2e16022f25a5..000000000000 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ /dev/null @@ -1,518 +0,0 @@ -apiClient = Configuration::$apiClient; - } - else - $this->apiClient = Configuration::$apiClient; // use the default one - } else { - $this->apiClient = $apiClient; // use the one provided by the user - } - } - - private $apiClient; // instance of the ApiClient - - /** - * get the API client - */ - public function getApiClient() { - return $this->apiClient; - } - - /** - * set the API client - */ - public function setApiClient($apiClient) { - $this->apiClient = $apiClient; - } - - - /** - * createUser - * - * Create user - * - * @param User $body Created user object (required) - * @return void - */ - public function createUser($body) { - - - // parse inputs - $resourcePath = "/user"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * createUsersWithArrayInput - * - * Creates list of users with given input array - * - * @param array[User] $body List of user object (required) - * @return void - */ - public function createUsersWithArrayInput($body) { - - - // parse inputs - $resourcePath = "/user/createWithArray"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * createUsersWithListInput - * - * Creates list of users with given input array - * - * @param array[User] $body List of user object (required) - * @return void - */ - public function createUsersWithListInput($body) { - - - // parse inputs - $resourcePath = "/user/createWithList"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * 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 - */ - public function loginUser($username, $password) { - - - // parse inputs - $resourcePath = "/user/login"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - // query params - if($username !== null) { - $queryParams['username'] = $this->apiClient->toQueryValue($username); - }// query params - if($password !== null) { - $queryParams['password'] = $this->apiClient->toQueryValue($password); - } - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->deserialize($response,'string'); - return $responseObject; - } - - /** - * logoutUser - * - * Logs out current logged in user session - * - * @return void - */ - public function logoutUser() { - - - // parse inputs - $resourcePath = "/user/logout"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * getUserByName - * - * Get user by user name - * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * @return User - */ - public function getUserByName($username) { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); - } - - - // parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - if(! $response) { - return null; - } - - $responseObject = $this->apiClient->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 - */ - public function updateUser($username, $body) { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); - } - - - // parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - - // body params - $_tempBody = null; - if (isset($body)) { - $_tempBody = $body; - } - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - /** - * deleteUser - * - * Delete user - * - * @param string $username The name that needs to be deleted (required) - * @return void - */ - public function deleteUser($username) { - - // verify the required parameter 'username' is set - if ($username === null) { - throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); - } - - - // parse inputs - $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; - $httpBody = ''; - $queryParams = array(); - $headerParams = array(); - $formParams = array(); - $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); - if (!is_null($_header_accept)) { - $headerParams['Accept'] = $_header_accept; - } - $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); - - - - // path params - if($username !== null) { - $resourcePath = str_replace("{" . "username" . "}", - $this->apiClient->toPathValue($username), $resourcePath); - } - - - - // for model (json/xml) - if (isset($_tempBody)) { - $httpBody = $_tempBody; // $_tempBody is the method argument, if present - } else if (count($formParams) > 0) { - // for HTTP post (form) - $httpBody = $formParams; - } - - // authentication setting, if any - $authSettings = array(); - - // make the API Call - $response = $this->apiClient->callAPI($resourcePath, $method, - $queryParams, $httpBody, - $headerParams, $authSettings); - - - } - - -} From 879c1b921cd80594bc13563d4c5249c3c729e133 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 13 Jul 2015 15:31:20 +0800 Subject: [PATCH 61/62] update php petstore sample --- .../php/SwaggerClient-php/lib/Api/PetApi.php | 60 +++++++++---------- .../SwaggerClient-php/lib/Api/StoreApi.php | 18 +++--- .../php/SwaggerClient-php/lib/Api/UserApi.php | 49 +++++++-------- 3 files changed, 58 insertions(+), 69 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index e9fef44a3ba1..8c0ce100d507 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -96,15 +96,14 @@ class PetApi * * Update an existing pet * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updatePet($body) + public function updatePet($body=null) { - + // parse inputs $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -161,15 +160,14 @@ class PetApi * * Add a new pet to the store * - * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (required) - * + * @param \Swagger\Client\Model\Pet $body Pet object that needs to be added to the store (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function addPet($body) + public function addPet($body=null) { - + // parse inputs $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -226,15 +224,14 @@ class PetApi * * Finds Pets by status * - * @param string[] $status Status values that need to be considered for filter (required) - * + * @param string[] $status Status values that need to be considered for filter (optional) * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function findPetsByStatus($status) + public function findPetsByStatus($status=null) { - + // parse inputs $resourcePath = "/pet/findByStatus"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -300,15 +297,14 @@ class PetApi * * Finds Pets by tags * - * @param string[] $tags Tags to filter by (required) - * + * @param string[] $tags Tags to filter by (optional) * @return \Swagger\Client\Model\Pet[] * @throws \Swagger\Client\ApiException on non-2xx response */ - public function findPetsByTags($tags) + public function findPetsByTags($tags=null) { - + // parse inputs $resourcePath = "/pet/findByTags"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -375,17 +371,17 @@ class PetApi * Find pet by ID * * @param int $pet_id ID of pet that needs to be fetched (required) - * * @return \Swagger\Client\Model\Pet * @throws \Swagger\Client\ApiException on non-2xx response */ public function getPetById($pet_id) { + // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -463,19 +459,19 @@ class PetApi * 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) - * + * @param string $name Updated name of the pet (optional) + * @param string $status Updated status of the pet (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updatePetWithForm($pet_id, $name, $status) + public function updatePetWithForm($pet_id, $name=null, $status=null) { + // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -541,19 +537,19 @@ class PetApi * * Deletes a pet * - * @param string $api_key (required) + * @param string $api_key (optional) * @param int $pet_id Pet id to delete (required) - * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function deletePet($api_key, $pet_id) + public function deletePet($api_key=null, $pet_id) { + // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } - + // parse inputs $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -617,19 +613,19 @@ class PetApi * 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 \SplFileObject $file file to upload (required) - * + * @param string $additional_metadata Additional data to pass to server (optional) + * @param \SplFileObject $file file to upload (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function uploadFile($pet_id, $additional_metadata, $file) + public function uploadFile($pet_id, $additional_metadata=null, $file=null) { + // verify the required parameter 'pet_id' is set if ($pet_id === null) { throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } - + // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; $resourcePath = str_replace("{format}", "json", $resourcePath); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index 5ad1da9e887c..ede8a3c14dad 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -96,14 +96,13 @@ class StoreApi * * Returns pet inventories by status * - * * @return map[string,int] * @throws \Swagger\Client\ApiException on non-2xx response */ public function getInventory() { - + // parse inputs $resourcePath = "/store/inventory"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -170,15 +169,14 @@ class StoreApi * * Place an order for a pet * - * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) - * + * @param \Swagger\Client\Model\Order $body order placed for purchasing the pet (optional) * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ - public function placeOrder($body) + public function placeOrder($body=null) { - + // parse inputs $resourcePath = "/store/order"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -243,17 +241,17 @@ class StoreApi * Find purchase order by ID * * @param string $order_id ID of pet that needs to be fetched (required) - * * @return \Swagger\Client\Model\Order * @throws \Swagger\Client\ApiException on non-2xx response */ public function getOrderById($order_id) { + // verify the required parameter 'order_id' is set if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -321,17 +319,17 @@ class StoreApi * Delete purchase order by ID * * @param string $order_id ID of the order that needs to be deleted (required) - * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteOrder($order_id) { + // verify the required parameter 'order_id' is set if ($order_id === null) { throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } - + // parse inputs $resourcePath = "/store/order/{orderId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index 37f739c50eaf..773181a52fc0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -96,15 +96,14 @@ class UserApi * * Create user * - * @param \Swagger\Client\Model\User $body Created user object (required) - * + * @param \Swagger\Client\Model\User $body Created user object (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUser($body) + public function createUser($body=null) { - + // parse inputs $resourcePath = "/user"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -158,15 +157,14 @@ class UserApi * * Creates list of users with given input array * - * @param \Swagger\Client\Model\User[] $body List of user object (required) - * + * @param \Swagger\Client\Model\User[] $body List of user object (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUsersWithArrayInput($body) + public function createUsersWithArrayInput($body=null) { - + // parse inputs $resourcePath = "/user/createWithArray"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -220,15 +218,14 @@ class UserApi * * Creates list of users with given input array * - * @param \Swagger\Client\Model\User[] $body List of user object (required) - * + * @param \Swagger\Client\Model\User[] $body List of user object (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function createUsersWithListInput($body) + public function createUsersWithListInput($body=null) { - + // parse inputs $resourcePath = "/user/createWithList"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -282,16 +279,15 @@ class UserApi * * 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) - * + * @param string $username The user name for login (optional) + * @param string $password The password for login in clear text (optional) * @return string * @throws \Swagger\Client\ApiException on non-2xx response */ - public function loginUser($username, $password) + public function loginUser($username=null, $password=null) { - + // parse inputs $resourcePath = "/user/login"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -357,14 +353,13 @@ class UserApi * * Logs out current logged in user session * - * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function logoutUser() { - + // parse inputs $resourcePath = "/user/logout"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -415,17 +410,17 @@ class UserApi * Get user by user name * * @param string $username The name that needs to be fetched. Use user1 for testing. (required) - * * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response */ public function getUserByName($username) { + // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } - + // parse inputs $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -493,18 +488,18 @@ class UserApi * Updated user * * @param string $username name that need to be deleted (required) - * @param \Swagger\Client\Model\User $body Updated user object (required) - * + * @param \Swagger\Client\Model\User $body Updated user object (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function updateUser($username, $body) + public function updateUser($username, $body=null) { + // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); @@ -566,17 +561,17 @@ class UserApi * Delete user * * @param string $username The name that needs to be deleted (required) - * * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ public function deleteUser($username) { + // verify the required parameter 'username' is set if ($username === null) { throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } - + // parse inputs $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); From 715c56afcc0e94499ecd865c4af2306ae071f416 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 13 Jul 2015 16:51:19 +0800 Subject: [PATCH 62/62] Rebuild petstore PHP sample with updated order on params --- .../client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php index 8c0ce100d507..8e75c360aeab 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -537,12 +537,12 @@ class PetApi * * Deletes a pet * - * @param string $api_key (optional) * @param int $pet_id Pet id to delete (required) + * @param string $api_key (optional) * @return void * @throws \Swagger\Client\ApiException on non-2xx response */ - public function deletePet($api_key=null, $pet_id) + public function deletePet($pet_id, $api_key=null) { // verify the required parameter 'pet_id' is set