From e38fc2c3daeb119235b5cf88d5389bd7fc2ae938 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 12 Jun 2015 20:15:48 +0800 Subject: [PATCH 01/30] Deserialize response for "object" type in Ruby client --- .../codegen/languages/RubyClientCodegen.java | 25 ++++--- .../src/main/resources/ruby/api.mustache | 4 +- .../main/resources/ruby/base_object.mustache | 10 +-- .../resources/ruby/swagger/response.mustache | 68 +++++++++++++++---- 4 files changed, 78 insertions(+), 29 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 01fe6c6eed4..2ee227fea29 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 @@ -48,12 +48,21 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { languageSpecificPrimitives.add("string"); languageSpecificPrimitives.add("DateTime"); - typeMapping.put("long", "int"); - typeMapping.put("integer", "int"); - typeMapping.put("Array", "array"); - typeMapping.put("String", "string"); - typeMapping.put("List", "array"); - typeMapping.put("map", "map"); + typeMapping.put("string", "String"); + typeMapping.put("char", "String"); + typeMapping.put("int", "Integer"); + typeMapping.put("integer", "Integer"); + typeMapping.put("long", "Integer"); + typeMapping.put("short", "Integer"); + typeMapping.put("float", "Float"); + typeMapping.put("double", "Float"); + typeMapping.put("number", "Float"); + typeMapping.put("DateTime", "DateTime"); + typeMapping.put("boolean", "BOOLEAN"); + typeMapping.put("array", "Array"); + typeMapping.put("List", "Array"); + typeMapping.put("map", "Hash"); + typeMapping.put("object", "Hash"); String baseFolder = "lib" + File.separatorChar + gemName; String swaggerFolder = baseFolder + File.separatorChar + "swagger"; @@ -107,11 +116,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + return getSwaggerType(p) + ""; } return super.getTypeDeclaration(p); } diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 3e1ac14014e..2b0f17c63f7 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -51,8 +51,8 @@ module {{moduleName}} {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body - {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('{{{returnType}}}'){{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make nil{{/returnType}} end {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index c0e563a0bb7..2f1e1064a5b 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -15,7 +15,7 @@ module {{moduleName}} def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i + if type =~ /^Array<(.*)>/i if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) else @@ -35,13 +35,13 @@ module {{moduleName}} case type.to_sym when :DateTime DateTime.parse(value) - when :string + when :String value.to_s - when :int + when :Integer value.to_i - when :double + when :Float value.to_f - when :boolean + when :BOOLEAN if value =~ /^(true|t|yes|y|1)$/i true else 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 e7bb482fb66..3abc7df40d7 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -2,6 +2,7 @@ module {{moduleName}} module Swagger class Response require 'json' + require 'date' attr_accessor :raw @@ -9,8 +10,8 @@ module {{moduleName}} self.raw = raw case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) + when 500..510 then raise(ServerError, self.body) + when 299..426 then raise(ClientError, self.body) end end @@ -18,19 +19,58 @@ module {{moduleName}} raw.code end - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body + def body + raw.body end - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body + # Deserialize the raw response body to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(return_type) + return nil if body.blank? + + # ensuring a default content type + content_type = raw.headers_hash['Content-Type'] || 'application/json' + + unless content_type.start_with?('application/json') + fail "Content-Type is not supported: #{content_type}" + end + + begin + data = JSON.parse(body, :symbolize_names => true) + rescue JSON::ParserError => e + if return_type == 'String' + return body + else + raise e + end + end + + build_models data, return_type + end + + # Build model(s) from Hash data for array/hash values of the response. + def build_models(data, return_type) + case return_type + when /\AArray<(.+)>\z/ + sub_type = $1 + data.map {|item| build_models(item, sub_type) } + when /\AHash\\z/ + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = build_models(v, sub_type) } + end + when 'String', 'Integer', 'Float', 'BOOLEAN' + # primitives, return directly + data + when 'DateTime' + DateTime.parse data + else + # models + {{moduleName}}.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end end # `headers_hash` is a Typhoeus-specific extension of Hash, @@ -58,7 +98,7 @@ module {{moduleName}} def pretty_body return unless body.present? case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') end end From 4c8c6c3880748ad9bcf3a692ba9c17b18ae93801 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 12 Jun 2015 20:18:50 +0800 Subject: [PATCH 02/30] Rebuild Ruby Petstore sample --- .../src/main/resources/ruby/api.mustache | 2 +- .../petstore/ruby/lib/swagger_client.rb | 2 +- .../ruby/lib/swagger_client/api/pet_api.rb | 30 ++++---- .../ruby/lib/swagger_client/api/store_api.rb | 14 ++-- .../ruby/lib/swagger_client/api/user_api.rb | 18 ++--- .../lib/swagger_client/models/base_object.rb | 10 +-- .../lib/swagger_client/models/category.rb | 4 +- .../ruby/lib/swagger_client/models/order.rb | 10 +-- .../ruby/lib/swagger_client/models/pet.rb | 10 +-- .../ruby/lib/swagger_client/models/tag.rb | 4 +- .../ruby/lib/swagger_client/models/user.rb | 16 ++--- .../lib/swagger_client/swagger/response.rb | 68 +++++++++++++++---- 12 files changed, 114 insertions(+), 74 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 2b0f17c63f7..531f8710e69 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -11,7 +11,7 @@ module {{moduleName}} # {{notes}} {{#allParams}}{{#required}} # @param {{paramName}} {{description}} {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters -{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} +{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) {{#allParams}}{{#required}} diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb index 998658c8b6e..6d239185005 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 2ce4fb04ecd..4a421faef86 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 @@ -82,8 +82,8 @@ module SwaggerClient # Finds Pets by status # Multiple status values can be provided with comma seperated strings # @param [Hash] opts the optional parameters - # @option opts [array[string]] :status Status values that need to be considered for filter - # @return [array[Pet]] + # @option opts [Array] :status Status values that need to be considered for filter + # @return [Array] def self.find_pets_by_status(opts = {}) @@ -113,15 +113,15 @@ module SwaggerClient auth_names = ['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 - response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('Array') end # Finds Pets by tags # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. # @param [Hash] opts the optional parameters - # @option opts [array[string]] :tags Tags to filter by - # @return [array[Pet]] + # @option opts [Array] :tags Tags to filter by + # @return [Array] def self.find_pets_by_tags(opts = {}) @@ -151,8 +151,8 @@ module SwaggerClient auth_names = ['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 - response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('Array') end # Find pet by ID @@ -190,17 +190,17 @@ module SwaggerClient post_body = nil - auth_names = ['petstore_auth', 'api_key'] - 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) + 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 + response.deserialize('Pet') end # Updates a pet in the store with form data # # @param pet_id ID of pet that needs to be updated # @param [Hash] opts the optional parameters - # @option opts [string] :name Updated name of the pet - # @option opts [string] :status Updated status of the pet + # @option opts [String] :name Updated name of the pet + # @option opts [String] :status Updated status of the pet # @return [nil] def self.update_pet_with_form(pet_id, opts = {}) @@ -243,7 +243,7 @@ module SwaggerClient # # @param pet_id Pet id to delete # @param [Hash] opts the optional parameters - # @option opts [string] :api_key + # @option opts [String] :api_key # @return [nil] def self.delete_pet(pet_id, opts = {}) @@ -285,7 +285,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 [String] :additional_metadata Additional data to pass to server # @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/api/store_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb index 010d170945b..a97f981f878 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb @@ -8,7 +8,7 @@ module SwaggerClient # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters - # @return [map[string,int]] + # @return [Hash] def self.get_inventory(opts = {}) @@ -37,8 +37,8 @@ module SwaggerClient auth_names = ['api_key'] - 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 - response.map {|response| obj = map.new() and obj.build_from_hash(response) } + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('Hash') end # Place an order for a pet @@ -74,8 +74,8 @@ module SwaggerClient auth_names = [] - response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body - obj = Order.new() and obj.build_from_hash(response) + response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('Order') end # Find purchase order by ID @@ -114,8 +114,8 @@ module SwaggerClient auth_names = [] - 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 = Order.new() and obj.build_from_hash(response) + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('Order') end # Delete purchase order by ID diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb index a3a57503b01..8337a8b9dd0 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb @@ -45,7 +45,7 @@ module SwaggerClient # Creates list of users with given input array # # @param [Hash] opts the optional parameters - # @option opts [array[User]] :body List of user object + # @option opts [Array] :body List of user object # @return [nil] def self.create_users_with_array_input(opts = {}) @@ -82,7 +82,7 @@ module SwaggerClient # Creates list of users with given input array # # @param [Hash] opts the optional parameters - # @option opts [array[User]] :body List of user object + # @option opts [Array] :body List of user object # @return [nil] def self.create_users_with_list_input(opts = {}) @@ -119,9 +119,9 @@ module SwaggerClient # Logs user into the system # # @param [Hash] opts the optional parameters - # @option opts [string] :username The user name for login - # @option opts [string] :password The password for login in clear text - # @return [string] + # @option opts [String] :username The user name for login + # @option opts [String] :password The password for login in clear text + # @return [String] def self.login_user(opts = {}) @@ -152,8 +152,8 @@ module SwaggerClient auth_names = [] - 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 = string.new() and obj.build_from_hash(response) + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('String') end # Logs out current logged in user session @@ -228,8 +228,8 @@ module SwaggerClient auth_names = [] - 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 = User.new() and obj.build_from_hash(response) + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + response.deserialize('User') end # Updated user diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb index 642e4769e55..a14e90350db 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb @@ -15,7 +15,7 @@ module SwaggerClient def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i + if type =~ /^Array<(.*)>/i if attributes[self.class.attribute_map[key]].is_a?(Array) self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) else @@ -35,13 +35,13 @@ module SwaggerClient case type.to_sym when :DateTime DateTime.parse(value) - when :string + when :String value.to_s - when :int + when :Integer value.to_i - when :double + when :Float value.to_f - when :boolean + when :BOOLEAN if value =~ /^(true|t|yes|y|1)$/i true else diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb index fe195c7ac87..d856563b11d 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb @@ -18,8 +18,8 @@ module SwaggerClient # attribute type def self.swagger_types { - :'id' => :'int', - :'name' => :'string' + :'id' => :'Integer', + :'name' => :'String' } end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb index 3fe0282ed9b..2cd1ff18f5d 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb @@ -30,12 +30,12 @@ module SwaggerClient # attribute type def self.swagger_types { - :'id' => :'int', - :'pet_id' => :'int', - :'quantity' => :'int', + :'id' => :'Integer', + :'pet_id' => :'Integer', + :'quantity' => :'Integer', :'ship_date' => :'DateTime', - :'status' => :'string', - :'complete' => :'boolean' + :'status' => :'String', + :'complete' => :'BOOLEAN' } end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb index 32f95646c72..f1f1d1434f4 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb @@ -30,12 +30,12 @@ module SwaggerClient # attribute type def self.swagger_types { - :'id' => :'int', + :'id' => :'Integer', :'category' => :'Category', - :'name' => :'string', - :'photo_urls' => :'array[string]', - :'tags' => :'array[Tag]', - :'status' => :'string' + :'name' => :'String', + :'photo_urls' => :'Array', + :'tags' => :'Array', + :'status' => :'String' } end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb index 9c5cdde1af6..677c828aede 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb @@ -18,8 +18,8 @@ module SwaggerClient # attribute type def self.swagger_types { - :'id' => :'int', - :'name' => :'string' + :'id' => :'Integer', + :'name' => :'String' } end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb index 2d723da54c4..ed7a21e167f 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb @@ -36,14 +36,14 @@ module SwaggerClient # attribute type def self.swagger_types { - :'id' => :'int', - :'username' => :'string', - :'first_name' => :'string', - :'last_name' => :'string', - :'email' => :'string', - :'password' => :'string', - :'phone' => :'string', - :'user_status' => :'int' + :'id' => :'Integer', + :'username' => :'String', + :'first_name' => :'String', + :'last_name' => :'String', + :'email' => :'String', + :'password' => :'String', + :'phone' => :'String', + :'user_status' => :'Integer' } end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb index 538821bea69..212f1fd15ab 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -2,6 +2,7 @@ module SwaggerClient module Swagger class Response require 'json' + require 'date' attr_accessor :raw @@ -9,8 +10,8 @@ module SwaggerClient self.raw = raw case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) + when 500..510 then raise(ServerError, self.body) + when 299..426 then raise(ClientError, self.body) end end @@ -18,19 +19,58 @@ module SwaggerClient raw.code end - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body + def body + raw.body end - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body + # Deserialize the raw response body to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(return_type) + return nil if body.blank? + + # ensuring a default content type + content_type = raw.headers_hash['Content-Type'] || 'application/json' + + unless content_type.start_with?('application/json') + fail "Content-Type is not supported: #{content_type}" + end + + begin + data = JSON.parse(body, :symbolize_names => true) + rescue JSON::ParserError => e + if return_type == 'String' + return body + else + raise e + end + end + + build_models data, return_type + end + + # Build model(s) from Hash data for array/hash values of the response. + def build_models(data, return_type) + case return_type + when /\AArray<(.+)>\z/ + sub_type = $1 + data.map {|item| build_models(item, sub_type) } + when /\AHash\\z/ + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = build_models(v, sub_type) } + end + when 'String', 'Integer', 'Float', 'BOOLEAN' + # primitives, return directly + data + when 'DateTime' + DateTime.parse data + else + # models + SwaggerClient.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end end # `headers_hash` is a Typhoeus-specific extension of Hash, @@ -58,7 +98,7 @@ module SwaggerClient def pretty_body return unless body.present? case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') end end From 36f0ed6d0c8fdcd3f773e01fbcca71a148a07588 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 12 Jun 2015 22:44:52 +0800 Subject: [PATCH 03/30] Add test cases for Response#deserialize --- .../petstore/ruby/spec/response_spec.rb | 35 ++++++++++++++----- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index 528b67e1fa7..8d75c6d1fae 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -8,7 +8,6 @@ describe SwaggerClient::Swagger::Response do end before(:each) do - VCR.use_cassette('pet_resource', :record => :new_episodes) do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") end @@ -18,8 +17,10 @@ describe SwaggerClient::Swagger::Response do describe "initialization" do it "sets body" do - @response.body.class.should == Hash - @response.body.has_key?(:'name').should == true + @response.body.should be_a(String) + data = JSON.parse(@response.body) + data.should be_a(Hash) + data['id'].should == 10002 end it "sets code" do @@ -30,9 +31,8 @@ describe SwaggerClient::Swagger::Response do @response.headers.class.should == Hash end end - - describe "format" do + describe "format" do it "recognizes json" do @response.format.should == 'json' @response.json?.should == true @@ -47,19 +47,36 @@ describe SwaggerClient::Swagger::Response do @response.format.should == 'xml' @response.xml?.should == true end - end - + describe "prettiness" do - it "has a pretty json body" do @response.pretty_body.should =~ /\{.*\}/ end - + it "has pretty headers" do @response.pretty_headers.should =~ /\{.*\}/ end + end + describe "deserialize" do + it "handles Hash" do + @response.stub(:body) { '{"message": "Hello"}' } + data = @response.deserialize('Hash') + data.should be_a(Hash) + data.should == {:message => 'Hello'} + end + + it "handles Hash" do + json = @response.body + @response.stub(:body) { "{\"pet\": #{json}}" } + data = @response.deserialize('Hash') + data.should be_a(Hash) + data.keys.should == [:pet] + pet = data[:pet] + pet.should be_a(SwaggerClient::Pet) + pet.id.should == 10002 + end end end From 80616b4c2baac0b6a4e45b634c27e0f52bb8518f Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 12 Jun 2015 23:03:17 +0800 Subject: [PATCH 04/30] Add test cases for StoreApi#get_inventory --- samples/client/petstore/ruby/spec/pet_spec.rb | 21 +++++++++++++------ .../client/petstore/ruby/spec/store_spec.rb | 10 +++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 68858c7b6cd..e05dd726f13 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -13,9 +13,14 @@ describe "Pet" do tag2 = SwaggerClient::Tag.new({'id' => 2, 'name'=> 'tag2'}) category1 = SwaggerClient::Category.new({:id => 1, :name => 'category unknown'}) # initalize using both string and symbol key - pet_hash = {:'id' => 10002, :'name' => "RUBY UNIT TESTING", :'status' => "pending", - :'photo_urls' => ["url1", "url2"], :'category' => category1, - :'tags' => [tag1, tag2]} + pet_hash = { + :id => 10002, + :name => "RUBY UNIT TESTING", + :status => "pending", + :photo_urls => ["url1", "url2"], + :category => category1, + :tags => [tag1, tag2] + } pet = SwaggerClient::Pet.new(pet_hash) # test new pet.name.should == "RUBY UNIT TESTING" @@ -48,6 +53,10 @@ describe "Pet" do it "should find pets by status" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available') pets.length.should >= 3 + pets.each do |pet| + pet.should be_a(SwaggerClient::Pet) + pet.status.should == 'available' + end end it "should not find a pet with invalid status" do @@ -57,11 +66,11 @@ describe "Pet" do it "should find a pet by status" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold") - pets.map {|pet| - if(pet.status != 'available' && pet.status != 'sold') + pets.each do |pet| + if pet.status != 'available' && pet.status != 'sold' raise "pet status wasn't right" end - } + end end it "should update a pet" do diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index 1b37400bc5c..3ad09f1ad61 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -10,4 +10,14 @@ describe "Store" do item = SwaggerClient::StoreApi.get_order_by_id(10002) item.id.should == 10002 end + + it "should featch the inventory" do + result = SwaggerClient::StoreApi.get_inventory + result.should be_a(Hash) + result.should_not be_empty + result.each do |k, v| + k.should be_a(Symbol) + v.should be_a(Integer) + end + end end From e9c1dd78428714bb94f907a7485501aaaa5bd57c Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 15 Jun 2015 12:49:17 +0800 Subject: [PATCH 05/30] Regard bare "object" type as Object, add comments The handling of base "object" type (without definions of "additionalProperties") is similar to Java generator now. --- .../codegen/languages/RubyClientCodegen.java | 2 +- .../resources/ruby/swagger/response.mustache | 27 ++++++++++++------- .../lib/swagger_client/swagger/response.rb | 27 ++++++++++++------- 3 files changed, 35 insertions(+), 21 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 2ee227fea29..46c0f70a4b6 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 @@ -62,7 +62,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("array", "Array"); typeMapping.put("List", "Array"); typeMapping.put("map", "Hash"); - typeMapping.put("object", "Hash"); + typeMapping.put("object", "Object"); String baseFolder = "lib" + File.separatorChar + gemName; String swaggerFolder = baseFolder + File.separatorChar + "swagger"; 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 3abc7df40d7..717ce49c3d5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -49,24 +49,31 @@ module {{moduleName}} build_models data, return_type end - # Build model(s) from Hash data for array/hash values of the response. + # Walk through the given data and, when necessary, build model(s) from + # Hash data for array/hash values of the response. def build_models(data, return_type) case return_type - when /\AArray<(.+)>\z/ - sub_type = $1 - data.map {|item| build_models(item, sub_type) } - when /\AHash\\z/ - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = build_models(v, sub_type) } - end when 'String', 'Integer', 'Float', 'BOOLEAN' # primitives, return directly data when 'DateTime' + # parse date time (expecting ISO 8601 format) DateTime.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| build_models(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = build_models(v, sub_type) } + end else - # models + # models, e.g. Pet {{moduleName}}.const_get(return_type).new.tap do |model| model.build_from_hash data end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb index 212f1fd15ab..53b60205a75 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -49,24 +49,31 @@ module SwaggerClient build_models data, return_type end - # Build model(s) from Hash data for array/hash values of the response. + # Walk through the given data and, when necessary, build model(s) from + # Hash data for array/hash values of the response. def build_models(data, return_type) case return_type - when /\AArray<(.+)>\z/ - sub_type = $1 - data.map {|item| build_models(item, sub_type) } - when /\AHash\\z/ - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = build_models(v, sub_type) } - end when 'String', 'Integer', 'Float', 'BOOLEAN' # primitives, return directly data when 'DateTime' + # parse date time (expecting ISO 8601 format) DateTime.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| build_models(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = build_models(v, sub_type) } + end else - # models + # models, e.g. Pet SwaggerClient.const_get(return_type).new.tap do |model| model.build_from_hash data end From 9d5928551bdcf49c62215a4285a0d1ce6553ff8f Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 15 Jun 2015 16:38:08 +0800 Subject: [PATCH 06/30] Unify ClientError and ServerError into ApiError in Ruby generator --- .../codegen/languages/RubyClientCodegen.java | 1 + .../src/main/resources/ruby/swagger.mustache | 8 +----- .../resources/ruby/swagger/api_error.mustache | 26 +++++++++++++++++++ .../resources/ruby/swagger/response.mustache | 8 +++--- .../resources/ruby/swagger_client.mustache | 1 + .../petstore/ruby/lib/swagger_client.rb | 1 + .../ruby/lib/swagger_client/swagger.rb | 8 +----- .../lib/swagger_client/swagger/api_error.rb | 26 +++++++++++++++++++ .../lib/swagger_client/swagger/response.rb | 8 +++--- 9 files changed, 67 insertions(+), 20 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache create mode 100644 samples/client/petstore/ruby/lib/swagger_client/swagger/api_error.rb 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 46c0f70a4b6..41d9f494a7c 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 @@ -73,6 +73,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "request.mustache", swaggerFolder, "request.rb")); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "response.mustache", swaggerFolder, "response.rb")); + supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "api_error.mustache", swaggerFolder, "api_error.rb")); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "version.mustache", swaggerFolder, "version.rb")); supportingFiles.add(new SupportingFile("swagger" + File.separatorChar + "configuration.mustache", swaggerFolder, "configuration.rb")); supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index dd2f630a8c9..239e3cfac26 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -52,7 +52,7 @@ module {{moduleName}} return if Swagger.authenticated? if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." + raise ApiError, "Username and password are required to authenticate." end request = Swagger::Request.new( @@ -69,10 +69,4 @@ module {{moduleName}} end end end - - class ServerError < StandardError - end - - class ClientError < StandardError - end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache new file mode 100644 index 00000000000..552161238a0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache @@ -0,0 +1,26 @@ +module {{moduleName}} + module Swagger + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + arg.each do |k, v| + if k.to_s == 'message' + super v + else + instance_variable_set "@#{k}", v + end + end + else + super arg + end + end + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache index 717ce49c3d5..b621110935a 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -9,9 +9,11 @@ module {{moduleName}} def initialize(raw) self.raw = raw - case self.code - when 500..510 then raise(ServerError, self.body) - when 299..426 then raise(ClientError, self.body) + unless raw.success? + fail ApiError.new(:code => code, + :response_headers => headers, + :response_body => body), + raw.status_message end 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 df675ddf26e..69454179283 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -2,6 +2,7 @@ require '{{gemName}}/monkey' require '{{gemName}}/swagger' require '{{gemName}}/swagger/configuration' +require '{{gemName}}/swagger/api_error' require '{{gemName}}/swagger/request' require '{{gemName}}/swagger/response' require '{{gemName}}/swagger/version' diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb index 6d239185005..42380927f82 100644 --- a/samples/client/petstore/ruby/lib/swagger_client.rb +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -2,6 +2,7 @@ require 'swagger_client/monkey' require 'swagger_client/swagger' require 'swagger_client/swagger/configuration' +require 'swagger_client/swagger/api_error' require 'swagger_client/swagger/request' require 'swagger_client/swagger/response' require 'swagger_client/swagger/version' diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb index 2e2632c169d..477ec89ba81 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb @@ -52,7 +52,7 @@ module SwaggerClient return if Swagger.authenticated? if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." + raise ApiError, "Username and password are required to authenticate." end request = Swagger::Request.new( @@ -69,10 +69,4 @@ module SwaggerClient end end end - - class ServerError < StandardError - end - - class ClientError < StandardError - end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/api_error.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/api_error.rb new file mode 100644 index 00000000000..12319927ace --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/api_error.rb @@ -0,0 +1,26 @@ +module SwaggerClient + module Swagger + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + arg.each do |k, v| + if k.to_s == 'message' + super v + else + instance_variable_set "@#{k}", v + end + end + else + super arg + end + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb index 53b60205a75..f560006de6d 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -9,9 +9,11 @@ module SwaggerClient def initialize(raw) self.raw = raw - case self.code - when 500..510 then raise(ServerError, self.body) - when 299..426 then raise(ClientError, self.body) + unless raw.success? + fail ApiError.new(:code => code, + :response_headers => headers, + :response_body => body), + raw.status_message end end From ec8e5179cbc487f3895ac6e79738cb707a779503 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 15 Jun 2015 16:46:30 +0800 Subject: [PATCH 07/30] Remove unused comments --- .../src/main/resources/ruby/monkey.mustache | 152 +++++++++--------- .../ruby/lib/swagger_client/monkey.rb | 152 +++++++++--------- 2 files changed, 144 insertions(+), 160 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache b/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache index 28932890af9..0751d42ce63 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/monkey.mustache @@ -1,90 +1,82 @@ -# module Swagger - class Object - - unless Object.method_defined? :blank? - def blank? - respond_to?(:empty?) ? empty? : !self - end +class Object + unless Object.method_defined? :blank? + def blank? + respond_to?(:empty?) ? empty? : !self end - - unless Object.method_defined? :present? - def present? - !blank? - end - end - end - class String - - unless String.method_defined? :underscore - def underscore - self.gsub(/::/, '/'). - gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). - gsub(/([a-z\d])([A-Z])/,'\1_\2'). - tr("-", "_"). - downcase - end - end - - unless String.method_defined? :camelize - def camelize(first_letter_in_uppercase = true) - if first_letter_in_uppercase != :lower - self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } - else - self.to_s[0].chr.downcase + camelize(self)[1..-1] - end - end + unless Object.method_defined? :present? + def present? + !blank? end + end +end +class String + unless String.method_defined? :underscore + def underscore + self.gsub(/::/, '/'). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr("-", "_"). + downcase + end end - class Hash - - unless Hash.method_defined? :stringify_keys - def stringify_keys - inject({}) do |options, (key, value)| - options[key.to_s] = value - options - end + unless String.method_defined? :camelize + def camelize(first_letter_in_uppercase = true) + if first_letter_in_uppercase != :lower + self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } + else + self.to_s[0].chr.downcase + camelize(self)[1..-1] end end - - unless Hash.method_defined? :stringify_keys! - def stringify_keys! - self.replace(self.stringify_keys) - end - end - - unless Hash.method_defined? :symbolize_keys - def symbolize_keys - inject({}) do |options, (key, value)| - options[(key.to_sym rescue key) || key] = value - options - end - end - end - - unless Hash.method_defined? :symbolize_keys! - def symbolize_keys! - self.replace(self.symbolize_keys) - end - end - - unless Hash.method_defined? :symbolize_and_underscore_keys - def symbolize_and_underscore_keys - inject({}) do |options, (key, value)| - options[(key.to_s.underscore.to_sym rescue key) || key] = value - options - end - end - end - - unless Hash.method_defined? :symbolize_and_underscore_keys! - def symbolize_and_underscore_keys! - self.replace(self.symbolize_and_underscore_keys) - end - end - end -# end \ No newline at end of file +end + +class Hash + unless Hash.method_defined? :stringify_keys + def stringify_keys + inject({}) do |options, (key, value)| + options[key.to_s] = value + options + end + end + end + + unless Hash.method_defined? :stringify_keys! + def stringify_keys! + self.replace(self.stringify_keys) + end + end + + unless Hash.method_defined? :symbolize_keys + def symbolize_keys + inject({}) do |options, (key, value)| + options[(key.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_keys! + def symbolize_keys! + self.replace(self.symbolize_keys) + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys + def symbolize_and_underscore_keys + inject({}) do |options, (key, value)| + options[(key.to_s.underscore.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys! + def symbolize_and_underscore_keys! + self.replace(self.symbolize_and_underscore_keys) + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/monkey.rb b/samples/client/petstore/ruby/lib/swagger_client/monkey.rb index 28932890af9..0751d42ce63 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/monkey.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/monkey.rb @@ -1,90 +1,82 @@ -# module Swagger - class Object - - unless Object.method_defined? :blank? - def blank? - respond_to?(:empty?) ? empty? : !self - end +class Object + unless Object.method_defined? :blank? + def blank? + respond_to?(:empty?) ? empty? : !self end - - unless Object.method_defined? :present? - def present? - !blank? - end - end - end - class String - - unless String.method_defined? :underscore - def underscore - self.gsub(/::/, '/'). - gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). - gsub(/([a-z\d])([A-Z])/,'\1_\2'). - tr("-", "_"). - downcase - end - end - - unless String.method_defined? :camelize - def camelize(first_letter_in_uppercase = true) - if first_letter_in_uppercase != :lower - self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } - else - self.to_s[0].chr.downcase + camelize(self)[1..-1] - end - end + unless Object.method_defined? :present? + def present? + !blank? end + end +end +class String + unless String.method_defined? :underscore + def underscore + self.gsub(/::/, '/'). + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr("-", "_"). + downcase + end end - class Hash - - unless Hash.method_defined? :stringify_keys - def stringify_keys - inject({}) do |options, (key, value)| - options[key.to_s] = value - options - end + unless String.method_defined? :camelize + def camelize(first_letter_in_uppercase = true) + if first_letter_in_uppercase != :lower + self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } + else + self.to_s[0].chr.downcase + camelize(self)[1..-1] end end - - unless Hash.method_defined? :stringify_keys! - def stringify_keys! - self.replace(self.stringify_keys) - end - end - - unless Hash.method_defined? :symbolize_keys - def symbolize_keys - inject({}) do |options, (key, value)| - options[(key.to_sym rescue key) || key] = value - options - end - end - end - - unless Hash.method_defined? :symbolize_keys! - def symbolize_keys! - self.replace(self.symbolize_keys) - end - end - - unless Hash.method_defined? :symbolize_and_underscore_keys - def symbolize_and_underscore_keys - inject({}) do |options, (key, value)| - options[(key.to_s.underscore.to_sym rescue key) || key] = value - options - end - end - end - - unless Hash.method_defined? :symbolize_and_underscore_keys! - def symbolize_and_underscore_keys! - self.replace(self.symbolize_and_underscore_keys) - end - end - end -# end \ No newline at end of file +end + +class Hash + unless Hash.method_defined? :stringify_keys + def stringify_keys + inject({}) do |options, (key, value)| + options[key.to_s] = value + options + end + end + end + + unless Hash.method_defined? :stringify_keys! + def stringify_keys! + self.replace(self.stringify_keys) + end + end + + unless Hash.method_defined? :symbolize_keys + def symbolize_keys + inject({}) do |options, (key, value)| + options[(key.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_keys! + def symbolize_keys! + self.replace(self.symbolize_keys) + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys + def symbolize_and_underscore_keys + inject({}) do |options, (key, value)| + options[(key.to_s.underscore.to_sym rescue key) || key] = value + options + end + end + end + + unless Hash.method_defined? :symbolize_and_underscore_keys! + def symbolize_and_underscore_keys! + self.replace(self.symbolize_and_underscore_keys) + end + end +end From a59d4ba346ebf40e46f0661e5a091e231d35ef05 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 15 Jun 2015 16:51:38 +0800 Subject: [PATCH 08/30] Add test case for finding nonexistent pet --- samples/client/petstore/ruby/spec/pet_spec.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index e05dd726f13..52030b7bf51 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -50,6 +50,19 @@ describe "Pet" do pet.category.name.should == "category test" end + it "should not find a pet that does not exist" do + begin + SwaggerClient::PetApi.get_pet_by_id(-1) + fail 'it should raise error' + rescue SwaggerClient::Swagger::ApiError => e + e.code.should == 404 + e.message.should == 'Not Found' + e.response_body.should == '{"code":1,"type":"error","message":"Pet not found"}' + e.response_headers.should be_a(Hash) + e.response_headers['Content-Type'].should == 'application/json' + end + end + it "should find pets by status" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available') pets.length.should >= 3 From 7c355030f47c827a6231d4dc1173fb7a452a283e Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 16 Jun 2015 18:41:51 +0800 Subject: [PATCH 09/30] Add to_s method for models --- .../main/resources/ruby/base_object.mustache | 20 +++++++++---------- .../lib/swagger_client/models/base_object.rb | 20 +++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index 2f1e1064a5b..eda92028f78 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -2,15 +2,6 @@ module {{moduleName}} # base class containing fundamental method such as to_hash, build_from_hash and more class BaseObject - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end - # build the object from hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) @@ -53,7 +44,16 @@ module {{moduleName}} end end - # to_body is an alias to to_body (backward compatibility) + def to_s + to_hash.to_s + end + + # to_body is an alias to to_body (backward compatibility)) + def to_body + to_hash + end + + # return the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |key, value| diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb index a14e90350db..b0fa43c8359 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb @@ -2,15 +2,6 @@ module SwaggerClient # base class containing fundamental method such as to_hash, build_from_hash and more class BaseObject - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end - # build the object from hash def build_from_hash(attributes) return nil unless attributes.is_a?(Hash) @@ -53,7 +44,16 @@ module SwaggerClient end end - # to_body is an alias to to_body (backward compatibility) + def to_s + to_hash.to_s + end + + # to_body is an alias to to_body (backward compatibility)) + def to_body + to_hash + end + + # return the object in the form of hash def to_hash hash = {} self.class.attribute_map.each_pair do |key, value| From 10e07eaf743dc6891163bd4014c4b7f2169fc295 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 15 Jun 2015 15:44:23 +0800 Subject: [PATCH 10/30] add support for cli (perl) --- .../codegen/languages/PerlClientCodegen.java | 49 +++++++++----- .../main/resources/perl/ApiClient.mustache | 18 +++--- .../main/resources/perl/BaseObject.mustache | 4 +- .../resources/perl/Configuration.mustache | 4 +- .../src/main/resources/perl/api.mustache | 8 +-- .../src/main/resources/perl/object.mustache | 4 +- .../csharp/io/swagger/Model/ApiResponse.cs | 61 ++++++++++++++++++ .../io/swagger/client/model/ApiResponse.java | 64 +++++++++++++++++++ .../petstore/objc/client/SWGApiResponse.h | 17 +++++ .../petstore/objc/client/SWGApiResponse.m | 22 +++++++ .../lib/WWW/SwaggerClient/Configuration.pm | 2 + 11 files changed, 219 insertions(+), 34 deletions(-) create mode 100644 samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java create mode 100644 samples/client/petstore/objc/client/SWGApiResponse.h create mode 100644 samples/client/petstore/objc/client/SWGApiResponse.m diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 1b0da2698e2..39218e9d8dc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -7,16 +7,16 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.codegen.CliOption; + import java.io.File; import java.util.Arrays; import java.util.HashSet; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "SwaggerClient"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String moduleName = "SwaggerClient"; + protected String moduleVersion = "1.0.0"; public PerlClientCodegen() { super(); @@ -26,8 +26,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { apiTemplateFiles.put("api.mustache", ".pm"); templateDir = "perl"; - typeMapping.clear(); - languageSpecificPrimitives.clear(); reservedWords = new HashSet( Arrays.asList( @@ -44,11 +42,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { ) ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - + languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("double"); languageSpecificPrimitives.add("string"); @@ -58,6 +52,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { languageSpecificPrimitives.add("HASH"); languageSpecificPrimitives.add("object"); + typeMapping.clear(); typeMapping.put("integer", "int"); typeMapping.put("long", "int"); typeMapping.put("float", "double"); @@ -71,9 +66,31 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("map", "HASH"); typeMapping.put("object", "object"); - supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "ApiClient.pm")); - supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Configuration.pm")); - supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm")); + cliOptions.clear(); + cliOptions.add(new CliOption("moduleName", "perl module name, default: SwaggerClient")); + cliOptions.add(new CliOption("moduleVersion", "perl module version, default: 1.0.0")); + } + + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("moduleVersion")) { + moduleVersion = (String) additionalProperties.get("moduleVersion"); + } else { + additionalProperties.put("moduleVersion", moduleVersion); + } + + if (additionalProperties.containsKey("moduleName")) { + moduleName = (String) additionalProperties.get("moduleName"); + } else { + additionalProperties.put("moduleName", moduleName); + } + + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiClient.pm")); + supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Configuration.pm")); + supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Object/BaseObject.pm")); } public CodegenType getTag() { @@ -95,11 +112,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/lib/WWW/" + invokerPackage + apiPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/WWW/" + moduleName + apiPackage()).replace('/', File.separatorChar); } public String modelFileFolder() { - return (outputFolder + "/lib/WWW/" + invokerPackage + modelPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/WWW/" + moduleName + modelPackage()).replace('/', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index f57642ff293..7124424baa6 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -1,4 +1,4 @@ -package WWW::{{invokerPackage}}::ApiClient; +package WWW::{{moduleName}}::ApiClient; use strict; use warnings; @@ -18,7 +18,7 @@ use Log::Any qw($log); use Carp; use Module::Runtime qw(use_module); -use WWW::{{invokerPackage}}::Configuration; +use WWW::{{moduleName}}::Configuration; sub new { @@ -115,8 +115,8 @@ sub call_api { else { } - $self->{ua}->timeout($self->{http_timeout} || $WWW::{{invokerPackage}}::Configuration::http_timeout); - $self->{ua}->agent($self->{http_user_agent} || $WWW::{{invokerPackage}}::Configuration::http_user_agent); + $self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout); + $self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent); my $_response = $self->{ua}->request($_request); @@ -237,7 +237,7 @@ sub deserialize } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { return $data; } else { # model - my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new; + my $_instance = use_module("WWW::{{moduleName}}::Object::$class")->new; if (ref $data eq "HASH") { return $_instance->from_hash($data); } else { # string, need to json decode first @@ -287,10 +287,10 @@ sub select_header_content_type sub get_api_key_with_prefix { my ($self, $api_key) = @_; - if ($WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}) { - return $WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{invokerPackage}}::Configuration::api_key->{$api_key}; + if ($WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}) { + return $WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{moduleName}}::Configuration::api_key->{$api_key}; } else { - return $WWW::{{invokerPackage}}::Configuration::api_key->{$api_key}; + return $WWW::{{moduleName}}::Configuration::api_key->{$api_key}; } } @@ -310,7 +310,7 @@ sub update_params_for_auth { if (!defined($auth)) { } {{#authMethods}}elsif ($auth eq '{{name}}') { - {{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{invokerPackage}}::Configuration::username.":".$WWW::{{invokerPackage}}::Configuration::password);{{/isBasic}} + {{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{moduleName}}::Configuration::username.":".$WWW::{{moduleName}}::Configuration::password);{{/isBasic}} {{#isOAuth}}# TODO support oauth{{/isOAuth}} } {{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index b4a7885a798..4be9f8408d6 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -1,4 +1,4 @@ -package WWW::{{invokerPackage}}::Object::BaseObject; +package WWW::{{moduleName}}::Object::BaseObject; require 5.6.0; use strict; @@ -68,7 +68,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) - my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()"; + my $_instance = eval "WWW::{{moduleName}}::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 38eb2ad8dae..0a097dda7bd 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -1,4 +1,4 @@ -package WWW::{{invokerPackage}}::Configuration; +package WWW::{{moduleName}}::Configuration; use strict; use warnings; @@ -7,6 +7,8 @@ use utf8; use Log::Any qw($log); use Carp; +use constant VERSION => '{{moduleVersion}}'; + # class/static variables our $api_client; our $http_timeout = 180; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index c67139ee33d..6fb3227a6e5 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -17,7 +17,7 @@ # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # -package WWW::{{invokerPackage}}::{{classname}}; +package WWW::{{moduleName}}::{{classname}}; require 5.6.0; use strict; @@ -27,8 +27,8 @@ use Exporter; use Carp qw( croak ); use Log::Any qw($log); -use WWW::{{invokerPackage}}::ApiClient; -use WWW::{{invokerPackage}}::Configuration; +use WWW::{{moduleName}}::ApiClient; +use WWW::{{moduleName}}::Configuration; {{#operations}} our @EXPORT_OK = qw( @@ -38,7 +38,7 @@ our @EXPORT_OK = qw( sub new { my $class = shift; - my $default_api_client = $WWW::{{invokerPackage}}::Configuration::api_client ? $WWW::{{invokerPackage}}::Configuration::api_client : WWW::{{invokerPackage}}::ApiClient->new; + my $default_api_client = $WWW::{{moduleName}}::Configuration::api_client ? $WWW::{{moduleName}}::Configuration::api_client : WWW::{{moduleName}}::ApiClient->new; my (%self) = ( 'api_client' => $default_api_client, @_ diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index c527957a9b1..c3a15b012bb 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -1,6 +1,6 @@ {{#models}} {{#model}} -package WWW::{{invokerPackage}}::Object::{{classname}}; +package WWW::{{moduleName}}::Object::{{classname}}; require 5.6.0; use strict; @@ -13,7 +13,7 @@ use Log::Any qw($log); use Date::Parse; use DateTime; -use base "WWW::{{invokerPackage}}::Object::BaseObject"; +use base "WWW::{{moduleName}}::Object::BaseObject"; # #{{description}} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs new file mode 100644 index 00000000000..7b23e25cb55 --- /dev/null +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs @@ -0,0 +1,61 @@ +using System; +using System.Text; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; +using Newtonsoft.Json; + +namespace IO.Swagger.Model { + + /// + /// + /// + [DataContract] + public class ApiResponse { + + + [DataMember(Name="code", EmitDefaultValue=false)] + public int? Code { get; set; } + + + + [DataMember(Name="type", EmitDefaultValue=false)] + public string Type { get; set; } + + + + [DataMember(Name="message", EmitDefaultValue=false)] + public string Message { get; set; } + + + + /// + /// Get the string presentation of the object + /// + /// String presentation of the object + public override string ToString() { + var sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + + sb.Append(" Code: ").Append(Code).Append("\n"); + + sb.Append(" Type: ").Append(Type).Append("\n"); + + sb.Append(" Message: ").Append(Message).Append("\n"); + + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Get the JSON string presentation of the object + /// + /// JSON string presentation of the object + public string ToJson() { + return JsonConvert.SerializeObject(this, Formatting.Indented); + } + +} + + +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java new file mode 100644 index 00000000000..802fa4743f7 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java @@ -0,0 +1,64 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + + +@ApiModel(description = "") +public class ApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/objc/client/SWGApiResponse.h b/samples/client/petstore/objc/client/SWGApiResponse.h new file mode 100644 index 00000000000..38525ad185d --- /dev/null +++ b/samples/client/petstore/objc/client/SWGApiResponse.h @@ -0,0 +1,17 @@ +#import +#import "SWGObject.h" + + +@protocol SWGApiResponse +@end + +@interface SWGApiResponse : SWGObject + + +@property(nonatomic) NSNumber* code; + +@property(nonatomic) NSString* type; + +@property(nonatomic) NSString* message; + +@end diff --git a/samples/client/petstore/objc/client/SWGApiResponse.m b/samples/client/petstore/objc/client/SWGApiResponse.m new file mode 100644 index 00000000000..08d8f7dae18 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGApiResponse.m @@ -0,0 +1,22 @@ +#import "SWGApiResponse.h" + +@implementation SWGApiResponse + ++ (JSONKeyMapper *)keyMapper +{ + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"code": @"code", @"type": @"type", @"message": @"message" }]; +} + ++ (BOOL)propertyIsOptional:(NSString *)propertyName +{ + NSArray *optionalProperties = @[@"code", @"type", @"message"]; + + if ([optionalProperties containsObject:propertyName]) { + return YES; + } + else { + return NO; + } +} + +@end diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm index bbce9d74759..aaa387236d9 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Configuration.pm @@ -7,6 +7,8 @@ use utf8; use Log::Any qw($log); use Carp; +use constant VERSION => '1.0.0'; + # class/static variables our $api_client; our $http_timeout = 180; From d7315b56dc720e26153eaa3b7b0641510ace2f34 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 15 Jun 2015 16:26:34 +0800 Subject: [PATCH 11/30] removed non-perl update --- .../csharp/io/swagger/Model/ApiResponse.cs | 61 ------------------ .../io/swagger/client/model/ApiResponse.java | 64 ------------------- .../petstore/objc/client/SWGApiResponse.h | 17 ----- .../petstore/objc/client/SWGApiResponse.m | 22 ------- 4 files changed, 164 deletions(-) delete mode 100644 samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs delete mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java delete mode 100644 samples/client/petstore/objc/client/SWGApiResponse.h delete mode 100644 samples/client/petstore/objc/client/SWGApiResponse.m diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs deleted file mode 100644 index 7b23e25cb55..00000000000 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/ApiResponse.cs +++ /dev/null @@ -1,61 +0,0 @@ -using System; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Runtime.Serialization; -using Newtonsoft.Json; - -namespace IO.Swagger.Model { - - /// - /// - /// - [DataContract] - public class ApiResponse { - - - [DataMember(Name="code", EmitDefaultValue=false)] - public int? Code { get; set; } - - - - [DataMember(Name="type", EmitDefaultValue=false)] - public string Type { get; set; } - - - - [DataMember(Name="message", EmitDefaultValue=false)] - public string Message { get; set; } - - - - /// - /// Get the string presentation of the object - /// - /// String presentation of the object - public override string ToString() { - var sb = new StringBuilder(); - sb.Append("class ApiResponse {\n"); - - sb.Append(" Code: ").Append(Code).Append("\n"); - - sb.Append(" Type: ").Append(Type).Append("\n"); - - sb.Append(" Message: ").Append(Message).Append("\n"); - - sb.Append("}\n"); - return sb.ToString(); - } - - /// - /// Get the JSON string presentation of the object - /// - /// JSON string presentation of the object - public string ToJson() { - return JsonConvert.SerializeObject(this, Formatting.Indented); - } - -} - - -} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java deleted file mode 100644 index 802fa4743f7..00000000000 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/model/ApiResponse.java +++ /dev/null @@ -1,64 +0,0 @@ -package io.swagger.client.model; - - -import io.swagger.annotations.*; -import com.fasterxml.jackson.annotation.JsonProperty; - - -@ApiModel(description = "") -public class ApiResponse { - - private Integer code = null; - private String type = null; - private String message = null; - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("code") - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("type") - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - - /** - **/ - @ApiModelProperty(value = "") - @JsonProperty("message") - public String getMessage() { - return message; - } - public void setMessage(String message) { - this.message = message; - } - - - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class ApiResponse {\n"); - - sb.append(" code: ").append(code).append("\n"); - sb.append(" type: ").append(type).append("\n"); - sb.append(" message: ").append(message).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} diff --git a/samples/client/petstore/objc/client/SWGApiResponse.h b/samples/client/petstore/objc/client/SWGApiResponse.h deleted file mode 100644 index 38525ad185d..00000000000 --- a/samples/client/petstore/objc/client/SWGApiResponse.h +++ /dev/null @@ -1,17 +0,0 @@ -#import -#import "SWGObject.h" - - -@protocol SWGApiResponse -@end - -@interface SWGApiResponse : SWGObject - - -@property(nonatomic) NSNumber* code; - -@property(nonatomic) NSString* type; - -@property(nonatomic) NSString* message; - -@end diff --git a/samples/client/petstore/objc/client/SWGApiResponse.m b/samples/client/petstore/objc/client/SWGApiResponse.m deleted file mode 100644 index 08d8f7dae18..00000000000 --- a/samples/client/petstore/objc/client/SWGApiResponse.m +++ /dev/null @@ -1,22 +0,0 @@ -#import "SWGApiResponse.h" - -@implementation SWGApiResponse - -+ (JSONKeyMapper *)keyMapper -{ - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"code": @"code", @"type": @"type", @"message": @"message" }]; -} - -+ (BOOL)propertyIsOptional:(NSString *)propertyName -{ - NSArray *optionalProperties = @[@"code", @"type", @"message"]; - - if ([optionalProperties containsObject:propertyName]) { - return YES; - } - else { - return NO; - } -} - -@end From 82baa7ce4b39cb9a41513c6548460fcc0ce99876 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 16 Jun 2015 11:25:23 +0800 Subject: [PATCH 12/30] update help text --- .../java/io/swagger/codegen/languages/PerlClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 39218e9d8dc..8c079973a1b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -67,7 +67,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); cliOptions.clear(); - cliOptions.add(new CliOption("moduleName", "perl module name, default: SwaggerClient")); + cliOptions.add(new CliOption("moduleName", "perl module name (convention: CamelCase), default: SwaggerClient")); cliOptions.add(new CliOption("moduleVersion", "perl module version, default: 1.0.0")); } From 64b46c2e15e0b1dd1d92afd2cc204dca48148b06 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 18 Jun 2015 02:40:15 +0800 Subject: [PATCH 13/30] update indentation, remove export --- .../main/resources/perl/ApiClient.mustache | 342 +++++++++--------- .../main/resources/perl/BaseObject.mustache | 72 ++-- .../src/main/resources/perl/api.mustache | 131 ++++--- .../src/main/resources/perl/object.mustache | 12 +- 4 files changed, 276 insertions(+), 281 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 7124424baa6..fa88dbd0333 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -22,14 +22,14 @@ use WWW::{{moduleName}}::Configuration; sub new { - my $class = shift; - my (%args) = ( - 'ua' => LWP::UserAgent->new, - 'base_url' => '{{basePath}}', - @_ - ); - - return bless \%args, $class; + my $class = shift; + my (%args) = ( + 'ua' => LWP::UserAgent->new, + 'base_url' => '{{basePath}}', + @_ + ); + + return bless \%args, $class; } # Set the user agent of the API client @@ -37,8 +37,8 @@ sub new # @param string $user_agent The user agent of the API client # sub set_user_agent { - my ($self, $user_agent) = @_; - $self->{http_user_agent}= $user_agent; + my ($self, $user_agent) = @_; + $self->{http_user_agent}= $user_agent; } # Set timeout @@ -46,11 +46,11 @@ sub set_user_agent { # @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] # sub set_timeout { - my ($self, $seconds) = @_; - if (!looks_like_number($seconds)) { - croak('Timeout variable must be numeric.'); - } - $self->{http_timeout} = $seconds; + my ($self, $seconds) = @_; + if (!looks_like_number($seconds)) { + croak('Timeout variable must be numeric.'); + } + $self->{http_timeout} = $seconds; } # make the HTTP request @@ -61,71 +61,71 @@ sub set_timeout { # @param array $headerParams parameters to be place in request header # @return mixed sub call_api { - my $self = shift; - my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; - - # update parameters based on authentication settings - $self->update_params_for_auth($header_params, $query_params, $auth_settings); - - - my $_url = $self->{base_url} . $resource_path; - - # build query - if (%$query_params) { - $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); - } - - - # body data - $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string - my $_body_data = %$post_params ? $post_params : $body_data; - - # Make the HTTP request - my $_request; - if ($method eq 'POST') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; - - $_request = POST($_url, %$header_params, Content => $_body_data); - - } - elsif ($method eq 'PUT') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; - - $_request = PUT($_url, %$header_params, Content => $_body_data); - - } - elsif ($method eq 'GET') { - my $headers = HTTP::Headers->new(%$header_params); - $_request = GET($_url, %$header_params); - } - elsif ($method eq 'HEAD') { - my $headers = HTTP::Headers->new(%$header_params); - $_request = HEAD($_url,%$header_params); - } - elsif ($method eq 'DELETE') { #TODO support form data - my $headers = HTTP::Headers->new(%$header_params); - $_request = DELETE($_url, %$headers); - } - elsif ($method eq 'PATCH') { #TODO - } - else { - } - - $self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout); - $self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent); + my $self = shift; + my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; + + # update parameters based on authentication settings + $self->update_params_for_auth($header_params, $query_params, $auth_settings); + + + my $_url = $self->{base_url} . $resource_path; + + # build query + if (%$query_params) { + $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); + } + + + # body data + $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string + my $_body_data = %$post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request; + if ($method eq 'POST') { + # multipart + $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + + $_request = POST($_url, %$header_params, Content => $_body_data); + + } + elsif ($method eq 'PUT') { + # multipart + $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + + $_request = PUT($_url, %$header_params, Content => $_body_data); + + } + elsif ($method eq 'GET') { + my $headers = HTTP::Headers->new(%$header_params); + $_request = GET($_url, %$header_params); + } + elsif ($method eq 'HEAD') { + my $headers = HTTP::Headers->new(%$header_params); + $_request = HEAD($_url,%$header_params); + } + elsif ($method eq 'DELETE') { #TODO support form data + my $headers = HTTP::Headers->new(%$header_params); + $_request = DELETE($_url, %$headers); + } + elsif ($method eq 'PATCH') { #TODO + } + else { + } + + $self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout); + $self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent); + + my $_response = $self->{ua}->request($_request); + + unless ($_response->is_success) { + croak("API Exception(".$_response->code."): ".$_response->message); + } + + return $_response->content; - my $_response = $self->{ua}->request($_request); - - unless ($_response->is_success) { - croak("API Exception(".$_response->code."): ".$_response->message); - } - - return $_response->content; - } # Take value and turn it into a string suitable for inclusion in @@ -180,13 +180,13 @@ sub to_form_value { # @param string $value the value of the parameter # @return string the header string sub to_string { - my ($self, $value) = @_; - if (ref($value) eq "DateTime") { # datetime in ISO8601 format - return $value->datetime(); - } - else { - return $value; - } + my ($self, $value) = @_; + if (ref($value) eq "DateTime") { # datetime in ISO8601 format + return $value->datetime(); + } + else { + return $value; + } } # Deserialize a JSON string into an object @@ -196,55 +196,55 @@ sub to_string { # @return object an instance of $class sub deserialize { - my ($self, $class, $data) = @_; - $log->debugf("deserializing %s for %s", $data, $class); - - if (not defined $data) { - return undef; - } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash - if ($class =~ /^HASH\[(.*),(.*)\]$/) { - my ($key_type, $type) = ($1, $2); - my %hash; - my $decoded_data = decode_json $data; - foreach my $key (keys %$decoded_data) { - if (ref $decoded_data->{$key} eq 'HASH') { - $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key}); + my ($self, $class, $data) = @_; + $log->debugf("deserializing %s for %s", $data, $class); + + if (not defined $data) { + return undef; + } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash + if ($class =~ /^HASH\[(.*),(.*)\]$/) { + my ($key_type, $type) = ($1, $2); + my %hash; + my $decoded_data = decode_json $data; + foreach my $key (keys %$decoded_data) { + if (ref $decoded_data->{$key} eq 'HASH') { + $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key}); + } else { + $hash{$key} = $self->deserialize($type, $decoded_data->{$key}); + } + } + return \%hash; } else { - $hash{$key} = $self->deserialize($type, $decoded_data->{$key}); + #TODO log error + } + + } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data + return $data if $data eq '[]'; # return if empty array + + my $_sub_class = substr($class, 6, -1); + my $_json_data = decode_json $data; + my @_values = (); + foreach my $_value (@$_json_data) { + if (ref $_value eq 'ARRAY') { + push @_values, $self->deserialize($_sub_class, encode_json $_value); + } else { + push @_values, $self->deserialize($_sub_class, $_value); + } + } + return \@_values; + } elsif ($class eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { + return $data; + } else { # model + my $_instance = use_module("WWW::{{moduleName}}::Object::$class")->new; + if (ref $data eq "HASH") { + return $_instance->from_hash($data); + } else { # string, need to json decode first + return $_instance->from_hash(decode_json $data); } - } - return \%hash; - } else { - #TODO log error } - - } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data - return $data if $data eq '[]'; # return if empty array - - my $_sub_class = substr($class, 6, -1); - my $_json_data = decode_json $data; - my @_values = (); - foreach my $_value (@$_json_data) { - if (ref $_value eq 'ARRAY') { - push @_values, $self->deserialize($_sub_class, encode_json $_value); - } else { - push @_values, $self->deserialize($_sub_class, $_value); - } - } - return \@_values; - } elsif ($class eq 'DateTime') { - return DateTime->from_epoch(epoch => str2time($data)); - } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { - return $data; - } else { # model - my $_instance = use_module("WWW::{{moduleName}}::Object::$class")->new; - if (ref $data eq "HASH") { - return $_instance->from_hash($data); - } else { # string, need to json decode first - return $_instance->from_hash(decode_json $data); - } - } - + } # return 'Accept' based on an array of accept provided @@ -252,16 +252,16 @@ sub deserialize # @return String Accept (e.g. application/json) sub select_header_accept { - my ($self, @header) = @_; - - if (@header == 0 || (@header == 1 && $header[0] eq '')) { - return undef; - } elsif (grep(/^application\/json$/i, @header)) { - return 'application/json'; - } else { - return join(',', @header); - } - + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return undef; + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + } # return the content type based on an array of content-type provided @@ -269,16 +269,16 @@ sub select_header_accept # @return String Content-Type (e.g. application/json) sub select_header_content_type { - my ($self, @header) = @_; - - if (@header == 0 || (@header == 1 && $header[0] eq '')) { - return 'application/json'; # default to application/json - } elsif (grep(/^application\/json$/i, @header)) { - return 'application/json'; - } else { - return join(',', @header); - } - + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return 'application/json'; # default to application/json + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + } # Get API key (with prefix if set) @@ -288,9 +288,9 @@ sub get_api_key_with_prefix { my ($self, $api_key) = @_; if ($WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}) { - return $WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{moduleName}}::Configuration::api_key->{$api_key}; + return $WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{moduleName}}::Configuration::api_key->{$api_key}; } else { - return $WWW::{{moduleName}}::Configuration::api_key->{$api_key}; + return $WWW::{{moduleName}}::Configuration::api_key->{$api_key}; } } @@ -300,24 +300,24 @@ sub get_api_key_with_prefix # @param array $queryParams query parameters (by ref) # @param array $authSettings array of authentication scheme (e.g ['api_key']) sub update_params_for_auth { - my ($self, $header_params, $query_params, $auth_settings) = @_; - - return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); - - # one endpoint can have more than 1 auth settings - foreach my $auth (@$auth_settings) { - # determine which one to use - if (!defined($auth)) { + my ($self, $header_params, $query_params, $auth_settings) = @_; + + return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); + + # one endpoint can have more than 1 auth settings + foreach my $auth (@$auth_settings) { + # determine which one to use + if (!defined($auth)) { + } + {{#authMethods}}elsif ($auth eq '{{name}}') { + {{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{moduleName}}::Configuration::username.":".$WWW::{{moduleName}}::Configuration::password);{{/isBasic}} + {{#isOAuth}}# TODO support oauth{{/isOAuth}} + } + {{/authMethods}} + else { + # TODO show warning about security definition not found + } } - {{#authMethods}}elsif ($auth eq '{{name}}') { - {{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{moduleName}}::Configuration::username.":".$WWW::{{moduleName}}::Configuration::password);{{/isBasic}} - {{#isOAuth}}# TODO support oauth{{/isOAuth}} - } - {{/authMethods}} - else { - # TODO show warning about security definition not found - } - } } diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index 4be9f8408d6..f3fca3f41a7 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -21,56 +21,56 @@ use DateTime; # return json string sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); + return decode_json(JSON->new->convert_blessed->encode( shift )); } # used by JSON for serialization sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $self->get_attribute_map) { - if (defined $self->{$_key}) { - $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + my $self = shift; + my $_data = {}; + foreach my $_key (keys $self->get_attribute_map) { + if (defined $self->{$_key}) { + $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + } } - } - return $_data; + return $_data; } # from json string sub from_hash { - my ($self, $hash) = @_; - # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->get_swagger_types ) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { - push @_array, $self->_deserialize($_subclass, $_element); - } - $self->{$_key} = \@_array; - } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime - $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); - } else { - $log->debugf("warning: %s not defined\n", $_key); + my ($self, $hash) = @_; + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each $self->get_swagger_types ) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); + } else { + $log->debugf("warning: %s not defined\n", $_key); + } } - } - - return $self; + + return $self; } # deserialize non-array data sub _deserialize { - my ($self, $type, $data) = @_; - $log->debugf("deserializing %s with %s",Dumper($data), $type); - - if ($type eq 'DateTime') { - return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { - return $data; - } else { # hash(model) - my $_instance = eval "WWW::{{moduleName}}::Object::$type->new()"; - return $_instance->from_hash($data); - } + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::{{moduleName}}::Object::$type->new()"; + return $_instance->from_hash($data); + } } 1; diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index 6fb3227a6e5..93848cf5af8 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -30,12 +30,6 @@ use Log::Any qw($log); use WWW::{{moduleName}}::ApiClient; use WWW::{{moduleName}}::Configuration; -{{#operations}} -our @EXPORT_OK = qw( - {{#operation}}{{{nickname}}} - {{/operation}} -); - sub new { my $class = shift; my $default_api_client = $WWW::{{moduleName}}::Configuration::api_client ? $WWW::{{moduleName}}::Configuration::api_client : WWW::{{moduleName}}::ApiClient->new; @@ -52,89 +46,90 @@ sub new { bless \%self, $class; } +{{#operations}} - {{#operation}} - # - # {{{nickname}}} - # - # {{{summary}}} - # - {{#allParams}} # @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} - {{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - # - sub {{nickname}} { - my ($self, %args) = @_; +{{#operation}} +# +# {{{nickname}}} +# +# {{{summary}}} +# +{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} +{{/allParams}}# @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +# +sub {{nickname}} { + my ($self, %args) = @_; - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - unless (exists $args{'{{paramName}}'}) { - croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); - } - {{/required}}{{/allParams}} + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + unless (exists $args{'{{paramName}}'}) { + croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} - # parse inputs - my $_resource_path = '{{path}}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '{{path}}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = '{{httpMethod}}'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = '{{httpMethod}}'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}); - {{#queryParams}}# query params - if ( exists $args{'{{paramName}}'}) { + {{#queryParams}}# query params + if ( exists $args{'{{paramName}}'}) { $query_params->{'{{baseName}}'} = $self->{api_client}->to_query_value($args{'{{paramName}}'}); - }{{/queryParams}} - {{#headerParams}}# header params - if ( exists $args{'{{paramName}}'}) { + }{{/queryParams}} + {{#headerParams}}# header params + if ( exists $args{'{{paramName}}'}) { $header_params->{'{{baseName}}'} = $self->{api_client}->to_header_value($args{'{{paramName}}'}); - }{{/headerParams}} - {{#pathParams}}# path params - if ( exists $args{'{{paramName}}'}) { + }{{/headerParams}} + {{#pathParams}}# path params + if ( exists $args{'{{paramName}}'}) { my $_base_variable = "{" . "{{baseName}}" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'{{paramName}}'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - }{{/pathParams}} - {{#formParams}}# form params - if ( exists $args{'{{paramName}}'} ) { + }{{/pathParams}} + {{#formParams}}# form params + if ( exists $args{'{{paramName}}'} ) { {{#isFile}}$form_params->{'{{baseName}}'} = [] unless defined $form_params->{'{{baseName}}'}; push $form_params->{'{{baseName}}'}, $args{'{{paramName}}'}; {{/isFile}} {{^isFile}}$form_params->{'{{baseName}}'} = $self->{api_client}->to_form_value($args{'{{paramName}}'}); {{/isFile}} - }{{/formParams}} - my $_body_data; - {{#bodyParams}}# body params - if ( exists $args{'{{paramName}}'}) { + }{{/formParams}} + my $_body_data; + {{#bodyParams}}# body params + if ( exists $args{'{{paramName}}'}) { $_body_data = $args{'{{paramName}}'}; - }{{/bodyParams}} + }{{/bodyParams}} - # authentication setting, if any - my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + # authentication setting, if any + my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - # make the API Call - {{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + {{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response); - return $_response_object;{{/returnType}} - {{^returnType}}$self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - {{/returnType}} - } - {{/operation}} + } + my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response); + return $_response_object;{{/returnType}} + {{^returnType}}$self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + {{/returnType}} +} +{{/operation}} {{newline}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/perl/object.mustache b/modules/swagger-codegen/src/main/resources/perl/object.mustache index c3a15b012bb..d4d6961c646 100644 --- a/modules/swagger-codegen/src/main/resources/perl/object.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/object.mustache @@ -22,13 +22,13 @@ use base "WWW::{{moduleName}}::Object::BaseObject"; # my $swagger_types = { - {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} + {{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} }; my $attribute_map = { - {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, - {{/hasMore}}{{/vars}} + {{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} }; # new object @@ -45,12 +45,12 @@ sub new { # get swagger type of the attribute sub get_swagger_types { - return $swagger_types; + return $swagger_types; } # get attribute mappping sub get_attribute_map { - return $attribute_map; + return $attribute_map; } 1; From 8858e7d7e3ea9ac72f9e31e587398bb120f04935 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 18 Jun 2015 02:44:40 +0800 Subject: [PATCH 14/30] update perl sample --- .../perl/lib/WWW/SwaggerClient/ApiClient.pm | 348 ++++---- .../WWW/SwaggerClient/Object/BaseObject.pm | 72 +- .../lib/WWW/SwaggerClient/Object/Category.pm | 12 +- .../lib/WWW/SwaggerClient/Object/Order.pm | 28 +- .../perl/lib/WWW/SwaggerClient/Object/Pet.pm | 28 +- .../perl/lib/WWW/SwaggerClient/Object/Tag.pm | 12 +- .../perl/lib/WWW/SwaggerClient/Object/User.pm | 36 +- .../perl/lib/WWW/SwaggerClient/PetApi.pm | 759 +++++++++--------- .../perl/lib/WWW/SwaggerClient/StoreApi.pm | 367 ++++----- .../perl/lib/WWW/SwaggerClient/UserApi.pm | 721 ++++++++--------- 10 files changed, 1164 insertions(+), 1219 deletions(-) diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm index 3a69adbad4d..9987a46ef76 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm @@ -22,14 +22,14 @@ use WWW::SwaggerClient::Configuration; sub new { - my $class = shift; - my (%args) = ( - 'ua' => LWP::UserAgent->new, - 'base_url' => 'http://petstore.swagger.io/v2', - @_ - ); - - return bless \%args, $class; + my $class = shift; + my (%args) = ( + 'ua' => LWP::UserAgent->new, + 'base_url' => 'http://petstore.swagger.io/v2', + @_ + ); + + return bless \%args, $class; } # Set the user agent of the API client @@ -37,8 +37,8 @@ sub new # @param string $user_agent The user agent of the API client # sub set_user_agent { - my ($self, $user_agent) = @_; - $self->{http_user_agent}= $user_agent; + my ($self, $user_agent) = @_; + $self->{http_user_agent}= $user_agent; } # Set timeout @@ -46,11 +46,11 @@ sub set_user_agent { # @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] # sub set_timeout { - my ($self, $seconds) = @_; - if (!looks_like_number($seconds)) { - croak('Timeout variable must be numeric.'); - } - $self->{http_timeout} = $seconds; + my ($self, $seconds) = @_; + if (!looks_like_number($seconds)) { + croak('Timeout variable must be numeric.'); + } + $self->{http_timeout} = $seconds; } # make the HTTP request @@ -61,71 +61,71 @@ sub set_timeout { # @param array $headerParams parameters to be place in request header # @return mixed sub call_api { - my $self = shift; - my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; - - # update parameters based on authentication settings - $self->update_params_for_auth($header_params, $query_params, $auth_settings); - - - my $_url = $self->{base_url} . $resource_path; - - # build query - if (%$query_params) { - $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); - } - - - # body data - $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string - my $_body_data = %$post_params ? $post_params : $body_data; - - # Make the HTTP request - my $_request; - if ($method eq 'POST') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; - - $_request = POST($_url, %$header_params, Content => $_body_data); - - } - elsif ($method eq 'PUT') { - # multipart - $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? - 'form-data' : $header_params->{'Content-Type'}; - - $_request = PUT($_url, %$header_params, Content => $_body_data); - - } - elsif ($method eq 'GET') { - my $headers = HTTP::Headers->new(%$header_params); - $_request = GET($_url, %$header_params); - } - elsif ($method eq 'HEAD') { - my $headers = HTTP::Headers->new(%$header_params); - $_request = HEAD($_url,%$header_params); - } - elsif ($method eq 'DELETE') { #TODO support form data - my $headers = HTTP::Headers->new(%$header_params); - $_request = DELETE($_url, %$headers); - } - elsif ($method eq 'PATCH') { #TODO - } - else { - } - - $self->{ua}->timeout($self->{http_timeout} || $WWW::SwaggerClient::Configuration::http_timeout); - $self->{ua}->agent($self->{http_user_agent} || $WWW::SwaggerClient::Configuration::http_user_agent); + my $self = shift; + my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_; + + # update parameters based on authentication settings + $self->update_params_for_auth($header_params, $query_params, $auth_settings); + + + my $_url = $self->{base_url} . $resource_path; + + # build query + if (%$query_params) { + $_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify }); + } + + + # body data + $body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string + my $_body_data = %$post_params ? $post_params : $body_data; + + # Make the HTTP request + my $_request; + if ($method eq 'POST') { + # multipart + $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + + $_request = POST($_url, %$header_params, Content => $_body_data); + + } + elsif ($method eq 'PUT') { + # multipart + $header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ? + 'form-data' : $header_params->{'Content-Type'}; + + $_request = PUT($_url, %$header_params, Content => $_body_data); + + } + elsif ($method eq 'GET') { + my $headers = HTTP::Headers->new(%$header_params); + $_request = GET($_url, %$header_params); + } + elsif ($method eq 'HEAD') { + my $headers = HTTP::Headers->new(%$header_params); + $_request = HEAD($_url,%$header_params); + } + elsif ($method eq 'DELETE') { #TODO support form data + my $headers = HTTP::Headers->new(%$header_params); + $_request = DELETE($_url, %$headers); + } + elsif ($method eq 'PATCH') { #TODO + } + else { + } + + $self->{ua}->timeout($self->{http_timeout} || $WWW::SwaggerClient::Configuration::http_timeout); + $self->{ua}->agent($self->{http_user_agent} || $WWW::SwaggerClient::Configuration::http_user_agent); + + my $_response = $self->{ua}->request($_request); + + unless ($_response->is_success) { + croak("API Exception(".$_response->code."): ".$_response->message); + } + + return $_response->content; - my $_response = $self->{ua}->request($_request); - - unless ($_response->is_success) { - croak("API Exception(".$_response->code."): ".$_response->message); - } - - return $_response->content; - } # Take value and turn it into a string suitable for inclusion in @@ -180,13 +180,13 @@ sub to_form_value { # @param string $value the value of the parameter # @return string the header string sub to_string { - my ($self, $value) = @_; - if (ref($value) eq "DateTime") { # datetime in ISO8601 format - return $value->datetime(); - } - else { - return $value; - } + my ($self, $value) = @_; + if (ref($value) eq "DateTime") { # datetime in ISO8601 format + return $value->datetime(); + } + else { + return $value; + } } # Deserialize a JSON string into an object @@ -196,55 +196,55 @@ sub to_string { # @return object an instance of $class sub deserialize { - my ($self, $class, $data) = @_; - $log->debugf("deserializing %s for %s", $data, $class); - - if (not defined $data) { - return undef; - } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash - if ($class =~ /^HASH\[(.*),(.*)\]$/) { - my ($key_type, $type) = ($1, $2); - my %hash; - my $decoded_data = decode_json $data; - foreach my $key (keys %$decoded_data) { - if (ref $decoded_data->{$key} eq 'HASH') { - $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key}); + my ($self, $class, $data) = @_; + $log->debugf("deserializing %s for %s", $data, $class); + + if (not defined $data) { + return undef; + } elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash + if ($class =~ /^HASH\[(.*),(.*)\]$/) { + my ($key_type, $type) = ($1, $2); + my %hash; + my $decoded_data = decode_json $data; + foreach my $key (keys %$decoded_data) { + if (ref $decoded_data->{$key} eq 'HASH') { + $hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key}); + } else { + $hash{$key} = $self->deserialize($type, $decoded_data->{$key}); + } + } + return \%hash; } else { - $hash{$key} = $self->deserialize($type, $decoded_data->{$key}); + #TODO log error + } + + } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data + return $data if $data eq '[]'; # return if empty array + + my $_sub_class = substr($class, 6, -1); + my $_json_data = decode_json $data; + my @_values = (); + foreach my $_value (@$_json_data) { + if (ref $_value eq 'ARRAY') { + push @_values, $self->deserialize($_sub_class, encode_json $_value); + } else { + push @_values, $self->deserialize($_sub_class, $_value); + } + } + return \@_values; + } elsif ($class eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { + return $data; + } else { # model + my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new; + if (ref $data eq "HASH") { + return $_instance->from_hash($data); + } else { # string, need to json decode first + return $_instance->from_hash(decode_json $data); } - } - return \%hash; - } else { - #TODO log error } - - } elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data - return $data if $data eq '[]'; # return if empty array - - my $_sub_class = substr($class, 6, -1); - my $_json_data = decode_json $data; - my @_values = (); - foreach my $_value (@$_json_data) { - if (ref $_value eq 'ARRAY') { - push @_values, $self->deserialize($_sub_class, encode_json $_value); - } else { - push @_values, $self->deserialize($_sub_class, $_value); - } - } - return \@_values; - } elsif ($class eq 'DateTime') { - return DateTime->from_epoch(epoch => str2time($data)); - } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { - return $data; - } else { # model - my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new; - if (ref $data eq "HASH") { - return $_instance->from_hash($data); - } else { # string, need to json decode first - return $_instance->from_hash(decode_json $data); - } - } - + } # return 'Accept' based on an array of accept provided @@ -252,16 +252,16 @@ sub deserialize # @return String Accept (e.g. application/json) sub select_header_accept { - my ($self, @header) = @_; - - if (@header == 0 || (@header == 1 && $header[0] eq '')) { - return undef; - } elsif (grep(/^application\/json$/i, @header)) { - return 'application/json'; - } else { - return join(',', @header); - } - + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return undef; + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + } # return the content type based on an array of content-type provided @@ -269,16 +269,16 @@ sub select_header_accept # @return String Content-Type (e.g. application/json) sub select_header_content_type { - my ($self, @header) = @_; - - if (@header == 0 || (@header == 1 && $header[0] eq '')) { - return 'application/json'; # default to application/json - } elsif (grep(/^application\/json$/i, @header)) { - return 'application/json'; - } else { - return join(',', @header); - } - + my ($self, @header) = @_; + + if (@header == 0 || (@header == 1 && $header[0] eq '')) { + return 'application/json'; # default to application/json + } elsif (grep(/^application\/json$/i, @header)) { + return 'application/json'; + } else { + return join(',', @header); + } + } # Get API key (with prefix if set) @@ -288,9 +288,9 @@ sub get_api_key_with_prefix { my ($self, $api_key) = @_; if ($WWW::SwaggerClient::Configuration::api_key_prefix->{$api_key}) { - return $WWW::SwaggerClient::Configuration::api_key_prefix->{$api_key}." ".$WWW::SwaggerClient::Configuration::api_key->{$api_key}; + return $WWW::SwaggerClient::Configuration::api_key_prefix->{$api_key}." ".$WWW::SwaggerClient::Configuration::api_key->{$api_key}; } else { - return $WWW::SwaggerClient::Configuration::api_key->{$api_key}; + return $WWW::SwaggerClient::Configuration::api_key->{$api_key}; } } @@ -300,28 +300,28 @@ sub get_api_key_with_prefix # @param array $queryParams query parameters (by ref) # @param array $authSettings array of authentication scheme (e.g ['api_key']) sub update_params_for_auth { - my ($self, $header_params, $query_params, $auth_settings) = @_; - - return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); - - # one endpoint can have more than 1 auth settings - foreach my $auth (@$auth_settings) { - # determine which one to use - if (!defined($auth)) { - } - elsif ($auth eq 'api_key') { - $header_params->{'api_key'} = $self->get_api_key_with_prefix('api_key'); + my ($self, $header_params, $query_params, $auth_settings) = @_; + + return if (!defined($auth_settings) || scalar(@$auth_settings) == 0); + + # one endpoint can have more than 1 auth settings + foreach my $auth (@$auth_settings) { + # determine which one to use + if (!defined($auth)) { + } + elsif ($auth eq 'api_key') { + $header_params->{'api_key'} = $self->get_api_key_with_prefix('api_key'); + + } + elsif ($auth eq 'petstore_auth') { + + # TODO support oauth + } + else { + # TODO show warning about security definition not found + } } - elsif ($auth eq 'petstore_auth') { - - # TODO support oauth - } - - else { - # TODO show warning about security definition not found - } - } } diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm index c4fd4e6aece..12088eb56cd 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/BaseObject.pm @@ -21,56 +21,56 @@ use DateTime; # return json string sub to_hash { - return decode_json(JSON->new->convert_blessed->encode( shift )); + return decode_json(JSON->new->convert_blessed->encode( shift )); } # used by JSON for serialization sub TO_JSON { - my $self = shift; - my $_data = {}; - foreach my $_key (keys $self->get_attribute_map) { - if (defined $self->{$_key}) { - $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + my $self = shift; + my $_data = {}; + foreach my $_key (keys $self->get_attribute_map) { + if (defined $self->{$_key}) { + $_data->{$self->get_attribute_map->{$_key}} = $self->{$_key}; + } } - } - return $_data; + return $_data; } # from json string sub from_hash { - my ($self, $hash) = @_; - # loop through attributes and use swagger_types to deserialize the data - while ( my ($_key, $_type) = each $self->get_swagger_types ) { - if ($_type =~ /^array\[/i) { # array - my $_subclass = substr($_type, 6, -1); - my @_array = (); - foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { - push @_array, $self->_deserialize($_subclass, $_element); - } - $self->{$_key} = \@_array; - } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime - $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); - } else { - $log->debugf("warning: %s not defined\n", $_key); + my ($self, $hash) = @_; + # loop through attributes and use swagger_types to deserialize the data + while ( my ($_key, $_type) = each $self->get_swagger_types ) { + if ($_type =~ /^array\[/i) { # array + my $_subclass = substr($_type, 6, -1); + my @_array = (); + foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) { + push @_array, $self->_deserialize($_subclass, $_element); + } + $self->{$_key} = \@_array; + } elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime + $self->{$_key} = $self->_deserialize($_type, $hash->{$_key}); + } else { + $log->debugf("warning: %s not defined\n", $_key); + } } - } - - return $self; + + return $self; } # deserialize non-array data sub _deserialize { - my ($self, $type, $data) = @_; - $log->debugf("deserializing %s with %s",Dumper($data), $type); - - if ($type eq 'DateTime') { - return DateTime->from_epoch(epoch => str2time($data)); - } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { - return $data; - } else { # hash(model) - my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; - return $_instance->from_hash($data); - } + my ($self, $type, $data) = @_; + $log->debugf("deserializing %s with %s",Dumper($data), $type); + + if ($type eq 'DateTime') { + return DateTime->from_epoch(epoch => str2time($data)); + } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { + return $data; + } else { # hash(model) + my $_instance = eval "WWW::SwaggerClient::Object::$type->new()"; + return $_instance->from_hash($data); + } } 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm index 857dccdce5a..2b2c0beceac 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Category.pm @@ -20,13 +20,13 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', - 'name' => 'string' + 'id' => 'int', + 'name' => 'string' }; my $attribute_map = { - 'id' => 'id', - 'name' => 'name' + 'id' => 'id', + 'name' => 'name' }; # new object @@ -44,12 +44,12 @@ sub new { # get swagger type of the attribute sub get_swagger_types { - return $swagger_types; + return $swagger_types; } # get attribute mappping sub get_attribute_map { - return $attribute_map; + return $attribute_map; } 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm index 35449647e13..14da4a5f3af 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Order.pm @@ -20,21 +20,21 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => 'DateTime', - 'status' => 'string', - 'complete' => 'boolean' + 'id' => 'int', + 'pet_id' => 'int', + 'quantity' => 'int', + 'ship_date' => 'DateTime', + 'status' => 'string', + 'complete' => 'boolean' }; my $attribute_map = { - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' + 'id' => 'id', + 'pet_id' => 'petId', + 'quantity' => 'quantity', + 'ship_date' => 'shipDate', + 'status' => 'status', + 'complete' => 'complete' }; # new object @@ -60,12 +60,12 @@ sub new { # get swagger type of the attribute sub get_swagger_types { - return $swagger_types; + return $swagger_types; } # get attribute mappping sub get_attribute_map { - return $attribute_map; + return $attribute_map; } 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm index df32665e826..eb74ad3f368 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Pet.pm @@ -20,21 +20,21 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', - 'category' => 'Category', - 'name' => 'string', - 'photo_urls' => 'ARRAY[string]', - 'tags' => 'ARRAY[Tag]', - 'status' => 'string' + 'id' => 'int', + 'category' => 'Category', + 'name' => 'string', + 'photo_urls' => 'ARRAY[string]', + 'tags' => 'ARRAY[Tag]', + 'status' => 'string' }; my $attribute_map = { - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' + 'id' => 'id', + 'category' => 'category', + 'name' => 'name', + 'photo_urls' => 'photoUrls', + 'tags' => 'tags', + 'status' => 'status' }; # new object @@ -60,12 +60,12 @@ sub new { # get swagger type of the attribute sub get_swagger_types { - return $swagger_types; + return $swagger_types; } # get attribute mappping sub get_attribute_map { - return $attribute_map; + return $attribute_map; } 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm index 35850032d5c..1b136d5fbfc 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/Tag.pm @@ -20,13 +20,13 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', - 'name' => 'string' + 'id' => 'int', + 'name' => 'string' }; my $attribute_map = { - 'id' => 'id', - 'name' => 'name' + 'id' => 'id', + 'name' => 'name' }; # new object @@ -44,12 +44,12 @@ sub new { # get swagger type of the attribute sub get_swagger_types { - return $swagger_types; + return $swagger_types; } # get attribute mappping sub get_attribute_map { - return $attribute_map; + return $attribute_map; } 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm index 88a396ece3a..1beb8f0b201 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Object/User.pm @@ -20,25 +20,25 @@ use base "WWW::SwaggerClient::Object::BaseObject"; # my $swagger_types = { - 'id' => 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' + 'id' => 'int', + 'username' => 'string', + 'first_name' => 'string', + 'last_name' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'user_status' => 'int' }; my $attribute_map = { - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' + 'id' => 'id', + 'username' => 'username', + 'first_name' => 'firstName', + 'last_name' => 'lastName', + 'email' => 'email', + 'password' => 'password', + 'phone' => 'phone', + 'user_status' => 'userStatus' }; # new object @@ -68,12 +68,12 @@ sub new { # get swagger type of the attribute sub get_swagger_types { - return $swagger_types; + return $swagger_types; } # get attribute mappping sub get_attribute_map { - return $attribute_map; + return $attribute_map; } 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 0a926625b74..7fe640aaea4 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -30,18 +30,6 @@ use Log::Any qw($log); use WWW::SwaggerClient::ApiClient; use WWW::SwaggerClient::Configuration; -our @EXPORT_OK = qw( - update_pet - add_pet - find_pets_by_status - find_pets_by_tags - get_pet_by_id - update_pet_with_form - delete_pet - upload_file - -); - sub new { my $class = shift; my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new; @@ -59,481 +47,472 @@ sub new { } +# +# update_pet +# +# Update an existing pet +# +# @param Pet $body Pet object that needs to be added to the store (required) +# @return void +# +sub update_pet { + my ($self, %args) = @_; + - # - # update_pet - # - # Update an existing pet - # - # @param Pet $body Pet object that needs to be added to the store (required) - # @return void - # - sub update_pet { - my ($self, %args) = @_; - + # parse inputs + my $_resource_path = '/pet'; + $_resource_path =~ s/{format}/json/; # default format to json - # parse inputs - my $_resource_path = '/pet'; - $_resource_path =~ s/{format}/json/; # default format to json + my $_method = 'PUT'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - my $_method = 'PUT'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml'); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml'); - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # add_pet - # - # Add a new pet to the store - # - # @param Pet $body Pet object that needs to be added to the store (required) - # @return void - # - sub add_pet { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# add_pet +# +# Add a new pet to the store +# +# @param Pet $body Pet object that needs to be added to the store (required) +# @return void +# +sub add_pet { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/pet'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml'); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json', 'application/xml'); - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # find_pets_by_status - # - # Finds Pets by status - # - # @param ARRAY[string] $status Status values that need to be considered for filter (required) - # @return ARRAY[Pet] - # - sub find_pets_by_status { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# find_pets_by_status +# +# Finds Pets by status +# +# @param ARRAY[string] $status Status values that need to be considered for filter (required) +# @return ARRAY[Pet] +# +sub find_pets_by_status { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/pet/findByStatus'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet/findByStatus'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - # query params - if ( exists $args{'status'}) { + # query params + if ( exists $args{'status'}) { $query_params->{'status'} = $self->{api_client}->to_query_value($args{'status'}); - } - - - - my $_body_data; - + } + + + + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); - return $_response_object; - - } - - # - # find_pets_by_tags - # - # Finds Pets by tags - # - # @param ARRAY[string] $tags Tags to filter by (required) - # @return ARRAY[Pet] - # - sub find_pets_by_tags { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); + return $_response_object; + +} +# +# find_pets_by_tags +# +# Finds Pets by tags +# +# @param ARRAY[string] $tags Tags to filter by (required) +# @return ARRAY[Pet] +# +sub find_pets_by_tags { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/pet/findByTags'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet/findByTags'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - # query params - if ( exists $args{'tags'}) { + # query params + if ( exists $args{'tags'}) { $query_params->{'tags'} = $self->{api_client}->to_query_value($args{'tags'}); - } - - - - my $_body_data; - + } + + + + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); - return $_response_object; - - } - - # - # get_pet_by_id - # - # Find pet by ID - # - # @param int $pet_id ID of pet that needs to be fetched (required) - # @return Pet - # - sub get_pet_by_id { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('ARRAY[Pet]', $response); + return $_response_object; + +} +# +# get_pet_by_id +# +# Find pet by ID +# +# @param int $pet_id ID of pet that needs to be fetched (required) +# @return Pet +# +sub get_pet_by_id { + my ($self, %args) = @_; - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling get_pet_by_id"); - } - + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling get_pet_by_id"); + } + - # parse inputs - my $_resource_path = '/pet/{petId}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # path params - if ( exists $args{'pet_id'}) { + + + # path params + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - + } + + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['api_key', 'petstore_auth']; + # authentication setting, if any + my $auth_settings = ['api_key', 'petstore_auth']; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('Pet', $response); - return $_response_object; - - } - - # - # update_pet_with_form - # - # Updates a pet in the store with form data - # - # @param string $pet_id ID of pet that needs to be updated (required) - # @param string $name Updated name of the pet (required) - # @param string $status Updated status of the pet (required) - # @return void - # - sub update_pet_with_form { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('Pet', $response); + return $_response_object; + +} +# +# update_pet_with_form +# +# Updates a pet in the store with form data +# +# @param string $pet_id ID of pet that needs to be updated (required) +# @param string $name Updated name of the pet (required) +# @param string $status Updated status of the pet (required) +# @return void +# +sub update_pet_with_form { + my ($self, %args) = @_; - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling update_pet_with_form"); - } - + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling update_pet_with_form"); + } + - # parse inputs - my $_resource_path = '/pet/{petId}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/x-www-form-urlencoded'); - - - # path params - if ( exists $args{'pet_id'}) { + + + # path params + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - # form params - if ( exists $args{'name'} ) { + } + # form params + if ( exists $args{'name'} ) { $form_params->{'name'} = $self->{api_client}->to_form_value($args{'name'}); - }# form params - if ( exists $args{'status'} ) { + }# form params + if ( exists $args{'status'} ) { $form_params->{'status'} = $self->{api_client}->to_form_value($args{'status'}); - } - my $_body_data; - + } + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # delete_pet - # - # Deletes a pet - # - # @param string $api_key (required) - # @param int $pet_id Pet id to delete (required) - # @return void - # - sub delete_pet { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# delete_pet +# +# Deletes a pet +# +# @param string $api_key (required) +# @param int $pet_id Pet id to delete (required) +# @return void +# +sub delete_pet { + my ($self, %args) = @_; - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling delete_pet"); - } - + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling delete_pet"); + } + - # parse inputs - my $_resource_path = '/pet/{petId}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet/{petId}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'DELETE'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'DELETE'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - # header params - if ( exists $args{'api_key'}) { + + # header params + if ( exists $args{'api_key'}) { $header_params->{'api_key'} = $self->{api_client}->to_header_value($args{'api_key'}); - } - # path params - if ( exists $args{'pet_id'}) { + } + # path params + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - + } + + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # upload_file - # - # uploads an image - # - # @param int $pet_id ID of pet to update (required) - # @param string $additional_metadata Additional data to pass to server (required) - # @param file $file file to upload (required) - # @return void - # - sub upload_file { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# upload_file +# +# uploads an image +# +# @param int $pet_id ID of pet to update (required) +# @param string $additional_metadata Additional data to pass to server (required) +# @param file $file file to upload (required) +# @return void +# +sub upload_file { + my ($self, %args) = @_; - - # verify the required parameter 'pet_id' is set - unless (exists $args{'pet_id'}) { - croak("Missing the required parameter 'pet_id' when calling upload_file"); - } - + + # verify the required parameter 'pet_id' is set + unless (exists $args{'pet_id'}) { + croak("Missing the required parameter 'pet_id' when calling upload_file"); + } + - # parse inputs - my $_resource_path = '/pet/{petId}/uploadImage'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/pet/{petId}/uploadImage'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('multipart/form-data'); - - - # path params - if ( exists $args{'pet_id'}) { + + + # path params + if ( exists $args{'pet_id'}) { my $_base_variable = "{" . "petId" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'pet_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - # form params - if ( exists $args{'additional_metadata'} ) { + } + # form params + if ( exists $args{'additional_metadata'} ) { $form_params->{'additionalMetadata'} = $self->{api_client}->to_form_value($args{'additional_metadata'}); - }# form params - if ( exists $args{'file'} ) { + }# form params + if ( exists $args{'file'} ) { $form_params->{'file'} = [] unless defined $form_params->{'file'}; push $form_params->{'file'}, $args{'file'}; - } - my $_body_data; - + } + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['petstore_auth']; + # authentication setting, if any + my $auth_settings = ['petstore_auth']; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index c27d241cb76..6072f61518c 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -30,14 +30,6 @@ use Log::Any qw($log); use WWW::SwaggerClient::ApiClient; use WWW::SwaggerClient::Configuration; -our @EXPORT_OK = qw( - get_inventory - place_order - get_order_by_id - delete_order - -); - sub new { my $class = shift; my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new; @@ -55,230 +47,225 @@ sub new { } +# +# get_inventory +# +# Returns pet inventories by status +# +# @return HASH[string,int] +# +sub get_inventory { + my ($self, %args) = @_; + - # - # get_inventory - # - # Returns pet inventories by status - # - # @return HASH[string,int] - # - sub get_inventory { - my ($self, %args) = @_; - + # parse inputs + my $_resource_path = '/store/inventory'; + $_resource_path =~ s/{format}/json/; # default format to json - # parse inputs - my $_resource_path = '/store/inventory'; - $_resource_path =~ s/{format}/json/; # default format to json + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - my $_body_data; - + + + + + my $_body_data; + - # authentication setting, if any - my $auth_settings = ['api_key']; + # authentication setting, if any + my $auth_settings = ['api_key']; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('HASH[string,int]', $response); - return $_response_object; - - } - - # - # place_order - # - # Place an order for a pet - # - # @param Order $body order placed for purchasing the pet (required) - # @return Order - # - sub place_order { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('HASH[string,int]', $response); + return $_response_object; + +} +# +# place_order +# +# Place an order for a pet +# +# @param Order $body order placed for purchasing the pet (required) +# @return Order +# +sub place_order { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/store/order'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/store/order'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('Order', $response); - return $_response_object; - - } - - # - # get_order_by_id - # - # Find purchase order by ID - # - # @param string $order_id ID of pet that needs to be fetched (required) - # @return Order - # - sub get_order_by_id { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('Order', $response); + return $_response_object; + +} +# +# get_order_by_id +# +# Find purchase order by ID +# +# @param string $order_id ID of pet that needs to be fetched (required) +# @return Order +# +sub get_order_by_id { + my ($self, %args) = @_; - - # verify the required parameter 'order_id' is set - unless (exists $args{'order_id'}) { - croak("Missing the required parameter 'order_id' when calling get_order_by_id"); - } - + + # verify the required parameter 'order_id' is set + unless (exists $args{'order_id'}) { + croak("Missing the required parameter 'order_id' when calling get_order_by_id"); + } + - # parse inputs - my $_resource_path = '/store/order/{orderId}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/store/order/{orderId}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # path params - if ( exists $args{'order_id'}) { + + + # path params + if ( exists $args{'order_id'}) { my $_base_variable = "{" . "orderId" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'order_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - + } + + my $_body_data; + - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('Order', $response); - return $_response_object; - - } - - # - # delete_order - # - # Delete purchase order by ID - # - # @param string $order_id ID of the order that needs to be deleted (required) - # @return void - # - sub delete_order { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('Order', $response); + return $_response_object; + +} +# +# delete_order +# +# Delete purchase order by ID +# +# @param string $order_id ID of the order that needs to be deleted (required) +# @return void +# +sub delete_order { + my ($self, %args) = @_; - - # verify the required parameter 'order_id' is set - unless (exists $args{'order_id'}) { - croak("Missing the required parameter 'order_id' when calling delete_order"); - } - + + # verify the required parameter 'order_id' is set + unless (exists $args{'order_id'}) { + croak("Missing the required parameter 'order_id' when calling delete_order"); + } + - # parse inputs - my $_resource_path = '/store/order/{orderId}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/store/order/{orderId}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'DELETE'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'DELETE'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # path params - if ( exists $args{'order_id'}) { + + + # path params + if ( exists $args{'order_id'}) { my $_base_variable = "{" . "orderId" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'order_id'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - + } + + my $_body_data; + - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} 1; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index ffb9d4b732b..f588f1bb410 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -30,18 +30,6 @@ use Log::Any qw($log); use WWW::SwaggerClient::ApiClient; use WWW::SwaggerClient::Configuration; -our @EXPORT_OK = qw( - create_user - create_users_with_array_input - create_users_with_list_input - login_user - logout_user - get_user_by_name - update_user - delete_user - -); - sub new { my $class = shift; my $default_api_client = $WWW::SwaggerClient::Configuration::api_client ? $WWW::SwaggerClient::Configuration::api_client : WWW::SwaggerClient::ApiClient->new; @@ -59,446 +47,437 @@ sub new { } +# +# create_user +# +# Create user +# +# @param User $body Created user object (required) +# @return void +# +sub create_user { + my ($self, %args) = @_; + - # - # create_user - # - # Create user - # - # @param User $body Created user object (required) - # @return void - # - sub create_user { - my ($self, %args) = @_; - + # parse inputs + my $_resource_path = '/user'; + $_resource_path =~ s/{format}/json/; # default format to json - # parse inputs - my $_resource_path = '/user'; - $_resource_path =~ s/{format}/json/; # default format to json + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; - - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # create_users_with_array_input - # - # Creates list of users with given input array - # - # @param ARRAY[User] $body List of user object (required) - # @return void - # - sub create_users_with_array_input { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# create_users_with_array_input +# +# Creates list of users with given input array +# +# @param ARRAY[User] $body List of user object (required) +# @return void +# +sub create_users_with_array_input { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/user/createWithArray'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/createWithArray'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # create_users_with_list_input - # - # Creates list of users with given input array - # - # @param ARRAY[User] $body List of user object (required) - # @return void - # - sub create_users_with_list_input { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# create_users_with_list_input +# +# Creates list of users with given input array +# +# @param ARRAY[User] $body List of user object (required) +# @return void +# +sub create_users_with_list_input { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/user/createWithList'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/createWithList'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'POST'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - my $_body_data; - # body params - if ( exists $args{'body'}) { + + + + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # login_user - # - # Logs user into the system - # - # @param string $username The user name for login (required) - # @param string $password The password for login in clear text (required) - # @return string - # - sub login_user { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# login_user +# +# Logs user into the system +# +# @param string $username The user name for login (required) +# @param string $password The password for login in clear text (required) +# @return string +# +sub login_user { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/user/login'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/login'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - # query params - if ( exists $args{'username'}) { + # query params + if ( exists $args{'username'}) { $query_params->{'username'} = $self->{api_client}->to_query_value($args{'username'}); - }# query params - if ( exists $args{'password'}) { + }# query params + if ( exists $args{'password'}) { $query_params->{'password'} = $self->{api_client}->to_query_value($args{'password'}); - } - - - - my $_body_data; - + } + + + + my $_body_data; + - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('string', $response); - return $_response_object; - - } - - # - # logout_user - # - # Logs out current logged in user session - # - # @return void - # - sub logout_user { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('string', $response); + return $_response_object; + +} +# +# logout_user +# +# Logs out current logged in user session +# +# @return void +# +sub logout_user { + my ($self, %args) = @_; - + - # parse inputs - my $_resource_path = '/user/logout'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/logout'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - - - my $_body_data; - + + + + + my $_body_data; + - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # get_user_by_name - # - # Get user by user name - # - # @param string $username The name that needs to be fetched. Use user1 for testing. (required) - # @return User - # - sub get_user_by_name { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# get_user_by_name +# +# Get user by user name +# +# @param string $username The name that needs to be fetched. Use user1 for testing. (required) +# @return User +# +sub get_user_by_name { + my ($self, %args) = @_; - - # verify the required parameter 'username' is set - unless (exists $args{'username'}) { - croak("Missing the required parameter 'username' when calling get_user_by_name"); - } - + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling get_user_by_name"); + } + - # parse inputs - my $_resource_path = '/user/{username}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'GET'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'GET'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # path params - if ( exists $args{'username'}) { + + + # path params + if ( exists $args{'username'}) { my $_base_variable = "{" . "username" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'username'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - + } + + my $_body_data; + - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - my $response = $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - if (!$response) { + # make the API Call + my $response = $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + if (!$response) { return; - } - my $_response_object = $self->{api_client}->deserialize('User', $response); - return $_response_object; - - } - - # - # update_user - # - # Updated user - # - # @param string $username name that need to be deleted (required) - # @param User $body Updated user object (required) - # @return void - # - sub update_user { - my ($self, %args) = @_; + } + my $_response_object = $self->{api_client}->deserialize('User', $response); + return $_response_object; + +} +# +# update_user +# +# Updated user +# +# @param string $username name that need to be deleted (required) +# @param User $body Updated user object (required) +# @return void +# +sub update_user { + my ($self, %args) = @_; - - # verify the required parameter 'username' is set - unless (exists $args{'username'}) { - croak("Missing the required parameter 'username' when calling update_user"); - } - + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling update_user"); + } + - # parse inputs - my $_resource_path = '/user/{username}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'PUT'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'PUT'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # path params - if ( exists $args{'username'}) { + + + # path params + if ( exists $args{'username'}) { my $_base_variable = "{" . "username" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'username'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - # body params - if ( exists $args{'body'}) { + } + + my $_body_data; + # body params + if ( exists $args{'body'}) { $_body_data = $args{'body'}; - } + } - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - - # - # delete_user - # - # Delete user - # - # @param string $username The name that needs to be deleted (required) - # @return void - # - sub delete_user { - my ($self, %args) = @_; + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} +# +# delete_user +# +# Delete user +# +# @param string $username The name that needs to be deleted (required) +# @return void +# +sub delete_user { + my ($self, %args) = @_; - - # verify the required parameter 'username' is set - unless (exists $args{'username'}) { - croak("Missing the required parameter 'username' when calling delete_user"); - } - + + # verify the required parameter 'username' is set + unless (exists $args{'username'}) { + croak("Missing the required parameter 'username' when calling delete_user"); + } + - # parse inputs - my $_resource_path = '/user/{username}'; - $_resource_path =~ s/{format}/json/; # default format to json + # parse inputs + my $_resource_path = '/user/{username}'; + $_resource_path =~ s/{format}/json/; # default format to json - my $_method = 'DELETE'; - my $query_params = {}; - my $header_params = {}; - my $form_params = {}; + my $_method = 'DELETE'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; - # 'Accept' and 'Content-Type' header - my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); - if ($_header_accept) { + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept('application/json', 'application/xml'); + if ($_header_accept) { $header_params->{'Accept'} = $_header_accept; - } - $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type(); - - - # path params - if ( exists $args{'username'}) { + + + # path params + if ( exists $args{'username'}) { my $_base_variable = "{" . "username" . "}"; my $_base_value = $self->{api_client}->to_path_value($args{'username'}); $_resource_path =~ s/$_base_variable/$_base_value/g; - } - - my $_body_data; - + } + + my $_body_data; + - # authentication setting, if any - my $auth_settings = []; + # authentication setting, if any + my $auth_settings = []; - # make the API Call - - $self->{api_client}->call_api($_resource_path, $_method, - $query_params, $form_params, - $header_params, $_body_data, $auth_settings); - return; - - } - + # make the API Call + + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; + +} 1; From 0da3e58fffb324e5821978c85d6a6d3b962f71dd Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 12 Jun 2015 14:48:02 +0800 Subject: [PATCH 15/30] Support map response for objc client. not completed --- .../codegen/languages/ObjcClientCodegen.java | 16 +- ...ApiClient.m => SWGApiClient-body.mustache} | 260 +++++--------- ...iClient.h => SWGApiClient-header.mustache} | 54 ++- .../src/main/resources/objc/api-body.mustache | 34 +- .../apiBodyResponseWithContainer.mustache | 7 + .../src/test/scala/Objc/ObjcModelTest.scala | 4 +- .../petstore/objc/client/SWGApiClient.h | 58 ++- .../petstore/objc/client/SWGApiClient.m | 260 +++++--------- .../client/petstore/objc/client/SWGPetApi.m | 338 ++++++------------ .../client/petstore/objc/client/SWGStoreApi.h | 4 +- .../client/petstore/objc/client/SWGStoreApi.m | 187 +++------- .../client/petstore/objc/client/SWGUserApi.m | 323 ++++++----------- 12 files changed, 539 insertions(+), 1006 deletions(-) rename modules/swagger-codegen/src/main/resources/objc/{SWGApiClient.m => SWGApiClient-body.mustache} (70%) rename modules/swagger-codegen/src/main/resources/objc/{SWGApiClient.h => SWGApiClient-header.mustache} (72%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 01f72040bf5..ce3ec065012 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -143,15 +143,15 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m")); supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h")); supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m")); - supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h")); - supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m")); + supportingFiles.add(new SupportingFile("SWGApiClient-header.mustache", sourceFolder, "SWGApiClient.h")); + supportingFiles.add(new SupportingFile("SWGApiClient-body.mustache", sourceFolder, "SWGApiClient.m")); supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m")); supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h")); - supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); + // supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); } @Override @@ -215,6 +215,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { } return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */"; } else { String swaggerType = getSwaggerType(p); diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache similarity index 70% rename from modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m rename to modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache index 5e2985bbe79..ee8be40e2ab 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache @@ -351,179 +351,114 @@ static bool loggingEnabled = true; *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -#pragma mark - Perform Request Methods --(NSNumber*) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [AFJSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - NSAssert(false, @"unsupport request type %@", requestContentType); +- (id) deserialize:(id) data class:(NSString *) class { + NSRegularExpression *regexp = nil; + NSTextCheckingResult *match = nil; + NSMutableArray *resultArray = nil; + NSMutableDictionary *resultDict = nil; + + // list of models + NSString *arrayOfModelsPat = @"NSArray<(.+)>"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + } + ]; + + return resultArray; } - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [AFJSONResponseSerializer serializer]; + // list of primitives + NSString *arrayOfPrimitivesPet = @"NSArray"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]]; + }]; + + return resultArray; } - else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; + + // map + NSString *dictPat = @"NSDictionary /\\* (.+), (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:dictPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; + + resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; + }]; + + return resultDict; } - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + // primitives + NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"]; - NSMutableURLRequest * request = nil; - if (body != nil && [body isKindOfClass:[NSArray class]]){ - SWGFile * file; - NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; - for(id obj in body) { - if([obj isKindOfClass:[SWGFile class]]) { - file = (SWGFile*) obj; - requestContentType = @"multipart/form-data"; - } - else if([obj isKindOfClass:[NSDictionary class]]) { - for(NSString * key in obj) { - params[key] = obj[key]; - } - } + if ([primitiveTypes containsObject:class]) { + if ([class isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; } - NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; - - // request with multipart form - if([requestContentType isEqualToString:@"multipart/form-data"]) { - request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" - URLString: urlString - parameters: nil - constructingBodyWithBlock: ^(id formData) { - - for(NSString * key in params) { - NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData: data name: key]; - } - - if (file) { - [formData appendPartWithFileData: [file data] - name: [file paramName] - fileName: [file name] - mimeType: [file mimeType]]; - } - - } - error:nil]; + else if ([class isEqualToString:@"NSDate"]) { + return [NSDate dateWithISO8601String:data]; } - // request with form parameters or json - else { - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:params - error:nil]; + else if ([class isEqualToString:@"BOOL"]) { + // Returns YES on encountering one of "Y", "y", "T", "t", or a + // digit 1-9—the method ignores any trailing characters + // NSString => BOOL => NSNumber + return [NSNumber numberWithBool:[data boolValue]]; + } + else if ([class isEqualToString:@"NSNumber"]) { + return [data numberFromString:data]; } } - else { - NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) - hasHeaderParams = true; - if(offlineState) { - NSLog(@"%@ cache forced", path); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - NSLog(@"%@ cache disabled", path); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + + // model + Class ModelClass = NSClassFromString(class); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [[ModelClass alloc] initWithDictionary:data error:nil]; } - if(body != nil) { - if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ - [self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; - } - else if ([body isKindOfClass:[SWGFile class]]) {} - else { - NSAssert(false, @"unsupported post type!"); - } - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; - - - if (self.logRequests) { - [self logRequest:request]; - } - - NSNumber* requestId = [SWGApiClient queueRequest]; - AFHTTPRequestOperation *op = - [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id JSON) { - if([self executeRequestWithId:requestId]) { - if(self.logServerResponses) - [self logResponse:JSON forRequest:request error:nil]; - completionBlock(JSON, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { - // Add in the (parsed) response body. - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if(self.logServerResponses) - [self logResponse:nil forRequest:request error:augmentedError]; - completionBlock(nil, augmentedError); - } - } - ]; - - [self.operationQueue addOperation:op]; - return requestId; + return nil; } --(NSNumber*) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - completionBlock: (void (^)(NSString*, NSError *))completionBlock { +#pragma mark - Perform Request Methods + +-(NSNumber*) requestWithCompletionBlock: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + completionBlock: (void (^)(id, NSError *))completionBlock { // setting request serializer if ([requestContentType isEqualToString:@"application/json"]) { self.requestSerializer = [AFJSONRequestSerializer serializer]; @@ -648,11 +583,11 @@ static bool loggingEnabled = true; NSNumber* requestId = [SWGApiClient queueRequest]; AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSString *response = [operation responseString]; + success:^(AFHTTPRequestOperation *operation, id response) { if([self executeRequestWithId:requestId]) { - if(self.logServerResponses) - [self logResponse:responseObject forRequest:request error:nil]; + if(self.logServerResponses) { + [self logResponse:response forRequest:request error:nil]; + } completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { @@ -683,3 +618,4 @@ static bool loggingEnabled = true; + diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache similarity index 72% rename from modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h rename to modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache index 250811c4016..09cb6fe57bd 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache @@ -1,6 +1,10 @@ #import +#import #import "AFHTTPRequestOperationManager.h" +{{#models}}{{#model}}#import "{{classname}}.h" +{{/model}}{{/models}} + /** * A key for `NSError` user info dictionaries. * @@ -159,37 +163,16 @@ extern NSString *const SWGResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Perform request + * Deserialize the given data to Objective-C object. * - * Request with non-empty response - * - * @param path Request url. - * @param method Request method. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The request id. + * @param data The data will be deserialized. + * @param class The type of objective-c object. */ --(NSNumber*) dictionary:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; +- (id) deserialize:(id) data class:(NSString *) class; /** * Perform request * - * Request with empty response - * * @param path Request url. * @param method Request method. * @param queryParams Request query parameters. @@ -202,15 +185,18 @@ extern NSString *const SWGResponseObjectErrorKey; * * @return The request id. */ --(NSNumber*) stringWithCompletionBlock:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSString*, NSError *))completionBlock; +-(NSNumber*) requestWithCompletionBlock:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(id, NSError *))completionBlock; + + @end + diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 40d75bd806b..ba61a8b2c7c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -195,27 +195,19 @@ static NSString * basePath = @"{{basePath}}"; } {{/requiredParams}} {{/requiredParamCount}} - - {{#returnContainer}} - // response is in a container - {{>apiBodyResponseWithContainer}}{{/returnContainer}} - - {{#returnSimpleType}} - // non container response - - {{#returnTypeIsPrimitive}} - // primitive response - {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} - - {{#returnBaseType}} - // complex response - {{>apiNonPrimitiveResponse}}{{/returnBaseType}} - {{/returnSimpleType}} - - {{^returnSimpleType}}{{^returnContainer}} - // it's void - {{>voidResponse}} - {{/returnContainer}}{{/returnSimpleType}} + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + {{^returnType}}completionBlock(error);{{/returnType}} + {{#returnType}}completionBlock([self.apiClient deserialize: data class:@"{{{returnType}}}"], error);{{/returnType}} + } + ]; } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache index acaeaf2ddf5..7d178353d52 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache @@ -36,3 +36,10 @@ {{/isListContainer}} }]; + + + + + + + diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala index 6cfac9a0eff..6747b94d4f8 100644 --- a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala @@ -118,7 +118,7 @@ class ObjcModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("translations") - vars.get(0).datatype should be("NSDictionary*") + vars.get(0).datatype should be("NSDictionary* /* NSString, NSString */") vars.get(0).name should be("translations") vars.get(0).baseType should be("NSDictionary") vars.get(0).containerType should be("map") @@ -192,7 +192,7 @@ class ObjcModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") vars.get(0).complexType should be("SWGChildren") - vars.get(0).datatype should be("NSDictionary*") + vars.get(0).datatype should be("NSDictionary* /* NSString, SWGChildren */") vars.get(0).name should be("children") vars.get(0).baseType should be("NSDictionary") vars.get(0).containerType should be("map") diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index 250811c4016..829aec58b96 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -1,6 +1,14 @@ #import +#import #import "AFHTTPRequestOperationManager.h" +#import "SWGUser.h" +#import "SWGCategory.h" +#import "SWGPet.h" +#import "SWGTag.h" +#import "SWGOrder.h" + + /** * A key for `NSError` user info dictionaries. * @@ -159,37 +167,16 @@ extern NSString *const SWGResponseObjectErrorKey; WithAuthSettings:(NSArray *)authSettings; /** - * Perform request + * Deserialize the given data to Objective-C object. * - * Request with non-empty response - * - * @param path Request url. - * @param method Request method. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The request id. + * @param data The data will be deserialized. + * @param class The type of objective-c object. */ --(NSNumber*) dictionary:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; +- (id) deserialize:(id) data class:(NSString *) class; /** * Perform request * - * Request with empty response - * * @param path Request url. * @param method Request method. * @param queryParams Request query parameters. @@ -202,15 +189,18 @@ extern NSString *const SWGResponseObjectErrorKey; * * @return The request id. */ --(NSNumber*) stringWithCompletionBlock:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSString*, NSError *))completionBlock; +-(NSNumber*) requestWithCompletionBlock:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(id, NSError *))completionBlock; + + @end + diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index 5e2985bbe79..ee8be40e2ab 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -351,179 +351,114 @@ static bool loggingEnabled = true; *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -#pragma mark - Perform Request Methods --(NSNumber*) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [AFJSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - NSAssert(false, @"unsupport request type %@", requestContentType); +- (id) deserialize:(id) data class:(NSString *) class { + NSRegularExpression *regexp = nil; + NSTextCheckingResult *match = nil; + NSMutableArray *resultArray = nil; + NSMutableDictionary *resultDict = nil; + + // list of models + NSString *arrayOfModelsPat = @"NSArray<(.+)>"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + } + ]; + + return resultArray; } - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [AFJSONResponseSerializer serializer]; + // list of primitives + NSString *arrayOfPrimitivesPet = @"NSArray"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]]; + }]; + + return resultArray; } - else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; + + // map + NSString *dictPat = @"NSDictionary /\\* (.+), (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:dictPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; + + resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; + }]; + + return resultDict; } - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + // primitives + NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"]; - NSMutableURLRequest * request = nil; - if (body != nil && [body isKindOfClass:[NSArray class]]){ - SWGFile * file; - NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; - for(id obj in body) { - if([obj isKindOfClass:[SWGFile class]]) { - file = (SWGFile*) obj; - requestContentType = @"multipart/form-data"; - } - else if([obj isKindOfClass:[NSDictionary class]]) { - for(NSString * key in obj) { - params[key] = obj[key]; - } - } + if ([primitiveTypes containsObject:class]) { + if ([class isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; } - NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; - - // request with multipart form - if([requestContentType isEqualToString:@"multipart/form-data"]) { - request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" - URLString: urlString - parameters: nil - constructingBodyWithBlock: ^(id formData) { - - for(NSString * key in params) { - NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData: data name: key]; - } - - if (file) { - [formData appendPartWithFileData: [file data] - name: [file paramName] - fileName: [file name] - mimeType: [file mimeType]]; - } - - } - error:nil]; + else if ([class isEqualToString:@"NSDate"]) { + return [NSDate dateWithISO8601String:data]; } - // request with form parameters or json - else { - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:params - error:nil]; + else if ([class isEqualToString:@"BOOL"]) { + // Returns YES on encountering one of "Y", "y", "T", "t", or a + // digit 1-9—the method ignores any trailing characters + // NSString => BOOL => NSNumber + return [NSNumber numberWithBool:[data boolValue]]; + } + else if ([class isEqualToString:@"NSNumber"]) { + return [data numberFromString:data]; } } - else { - NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) - hasHeaderParams = true; - if(offlineState) { - NSLog(@"%@ cache forced", path); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - NSLog(@"%@ cache disabled", path); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + + // model + Class ModelClass = NSClassFromString(class); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [[ModelClass alloc] initWithDictionary:data error:nil]; } - if(body != nil) { - if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ - [self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; - } - else if ([body isKindOfClass:[SWGFile class]]) {} - else { - NSAssert(false, @"unsupported post type!"); - } - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; - - - if (self.logRequests) { - [self logRequest:request]; - } - - NSNumber* requestId = [SWGApiClient queueRequest]; - AFHTTPRequestOperation *op = - [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id JSON) { - if([self executeRequestWithId:requestId]) { - if(self.logServerResponses) - [self logResponse:JSON forRequest:request error:nil]; - completionBlock(JSON, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { - // Add in the (parsed) response body. - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if(self.logServerResponses) - [self logResponse:nil forRequest:request error:augmentedError]; - completionBlock(nil, augmentedError); - } - } - ]; - - [self.operationQueue addOperation:op]; - return requestId; + return nil; } --(NSNumber*) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - completionBlock: (void (^)(NSString*, NSError *))completionBlock { +#pragma mark - Perform Request Methods + +-(NSNumber*) requestWithCompletionBlock: (NSString*) path + method: (NSString*) method + queryParams: (NSDictionary*) queryParams + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + completionBlock: (void (^)(id, NSError *))completionBlock { // setting request serializer if ([requestContentType isEqualToString:@"application/json"]) { self.requestSerializer = [AFJSONRequestSerializer serializer]; @@ -648,11 +583,11 @@ static bool loggingEnabled = true; NSNumber* requestId = [SWGApiClient queueRequest]; AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSString *response = [operation responseString]; + success:^(AFHTTPRequestOperation *operation, id response) { if([self executeRequestWithId:requestId]) { - if(self.logServerResponses) - [self logResponse:responseObject forRequest:request error:nil]; + if(self.logServerResponses) { + [self logResponse:response forRequest:request error:nil]; + } completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { @@ -683,3 +618,4 @@ static bool loggingEnabled = true; + diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index c14da125af5..8a03932001c 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -153,30 +153,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"PUT" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"PUT" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -260,30 +249,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -350,44 +328,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - // response is in a container - // array container response type - return [self.apiClient dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - - - SWGPet* d = [[SWGPet alloc] initWithDictionary:dict error:nil]; - - [objs addObject:d]; - } - completionBlock((NSArray*)objs, nil); - } - - - }]; - - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"NSArray*"], error); + } + ]; } /*! @@ -454,44 +407,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - // response is in a container - // array container response type - return [self.apiClient dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - - - SWGPet* d = [[SWGPet alloc] initWithDictionary:dict error:nil]; - - [objs addObject:d]; - } - completionBlock((NSArray*)objs, nil); - } - - - }]; - - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"NSArray*"], error); + } + ]; } /*! @@ -556,44 +484,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - // non container response - - - - - // complex response - - // comples response type - return [self.apiClient dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - - return; - } - SWGPet* result = nil; - if (data) { - result = [[SWGPet alloc] initWithDictionary:data error:nil]; - } - completionBlock(result , nil); - - }]; - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"SWGPet*"], error); + } + ]; } /*! @@ -678,30 +581,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -770,30 +662,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"DELETE" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -885,30 +766,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } diff --git a/samples/client/petstore/objc/client/SWGStoreApi.h b/samples/client/petstore/objc/client/SWGStoreApi.h index 49d8db806c8..b7d64469532 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -21,10 +21,10 @@ - return type: NSDictionary* + return type: NSDictionary* /* NSString, NSNumber */ */ -(NSNumber*) getInventoryWithCompletionBlock : - (void (^)(NSDictionary* output, NSError* error))completionBlock; + (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock; diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index a112db6d639..0af0ebaad78 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -74,10 +74,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; /*! * Returns pet inventories by status * Returns a map of status codes to quantities - * \returns NSDictionary* + * \returns NSDictionary* /* NSString, NSNumber */ */ -(NSNumber*) getInventoryWithCompletionBlock: - (void (^)(NSDictionary* output, NSError* error))completionBlock + (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock { @@ -127,37 +127,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - // response is in a container - // map container response type - return [self.apiClient dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - - NSDictionary *result = nil; - if (data) { - result = [[NSDictionary alloc]initWithDictionary: data]; - } - completionBlock(data, nil); - - }]; - - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"NSDictionary* /* NSString, NSNumber */"], error); + } + ]; } /*! @@ -241,44 +223,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - // non container response - - - - - // complex response - - // comples response type - return [self.apiClient dictionary: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - - return; - } - SWGOrder* result = nil; - if (data) { - result = [[SWGOrder alloc] initWithDictionary:data error:nil]; - } - completionBlock(result , nil); - - }]; - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"SWGOrder*"], error); + } + ]; } /*! @@ -343,44 +300,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - // non container response - - - - - // complex response - - // comples response type - return [self.apiClient dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - - return; - } - SWGOrder* result = nil; - if (data) { - result = [[SWGOrder alloc] initWithDictionary:data error:nil]; - } - completionBlock(result , nil); - - }]; - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"SWGOrder*"], error); + } + ]; } /*! @@ -445,30 +377,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"DELETE" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index e2fe69aca8d..401df17e396 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -152,30 +152,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -259,30 +248,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -366,30 +344,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"POST" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -460,43 +427,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - // non container response - - - // primitive response - // primitive response type - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - NSString *result = data ? [[NSString alloc]initWithString: data] : nil; - completionBlock(result, nil); - }]; - - - - - - - // complex response - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"NSString*"], error); + } + ]; } /*! @@ -555,30 +498,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -643,44 +575,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - // non container response - - - - - // complex response - - // comples response type - return [self.apiClient dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error); - - return; - } - SWGUser* result = nil; - if (data) { - result = [[SWGUser alloc] initWithDictionary:data error:nil]; - } - completionBlock(result , nil); - - }]; - - - - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + + completionBlock([self.apiClient deserialize: data class:@"SWGUser*"], error); + } + ]; } /*! @@ -770,30 +677,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"PUT" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"PUT" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } /*! @@ -858,30 +754,19 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - - - - - - - // it's void - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"DELETE" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - + return [self.apiClient requestWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(id data, NSError *error) { + completionBlock(error); + + } + ]; } From c50c8b724d65186b4c548f0a76495871832f709e Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 13 Jun 2015 09:32:53 +0800 Subject: [PATCH 16/30] Support map response for objc client. completed. --- .../resources/objc/SWGApiClient-body.mustache | 23 ++- .../src/main/resources/objc/api-body.mustache | 12 +- .../main/resources/objc/api-header.mustache | 19 +- .../apiBodyResponseWithContainer.mustache | 45 ----- .../objc/apiNonPrimitiveResponse.mustache | 24 --- .../objc/apiPrimitiveResponse.mustache | 36 ---- .../main/resources/objc/voidResponse.mustache | 15 -- .../PetstoreClientTests/StoreApiTest.m | 47 +++++ .../SwaggerClient.xcodeproj/project.pbxproj | 4 + .../SwaggerClient/ViewController.m | 9 +- .../SwaggerClientTests/SWGApiClientTest.m | 62 +++++++ .../petstore/objc/client/SWGApiClient.m | 23 ++- .../client/petstore/objc/client/SWGPetApi.h | 162 +++++++++--------- .../client/petstore/objc/client/SWGPetApi.m | 106 ++++++------ .../client/petstore/objc/client/SWGStoreApi.h | 74 ++++---- .../client/petstore/objc/client/SWGStoreApi.m | 47 +++-- .../client/petstore/objc/client/SWGUserApi.h | 154 ++++++++--------- .../client/petstore/objc/client/SWGUserApi.m | 98 +++++------ 18 files changed, 477 insertions(+), 483 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache index ee8be40e2ab..45c6fc6d305 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache @@ -351,6 +351,7 @@ static bool loggingEnabled = true; *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +#pragma mark - Deserialize methods - (id) deserialize:(id) data class:(NSString *) class { NSRegularExpression *regexp = nil; @@ -358,6 +359,11 @@ static bool loggingEnabled = true; NSMutableArray *resultArray = nil; NSMutableDictionary *resultDict = nil; + // remove "*" from class, if ends with "*" + if ([class hasSuffix:@"*"]) { + class = [class substringToIndex:[class length] - 1]; + } + // list of models NSString *arrayOfModelsPat = @"NSArray<(.+)>"; regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat @@ -371,7 +377,7 @@ static bool loggingEnabled = true; if (match) { NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; } @@ -390,7 +396,7 @@ static bool loggingEnabled = true; range:NSMakeRange(0, [class length])]; if (match) { - resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]]; }]; @@ -399,7 +405,7 @@ static bool loggingEnabled = true; } // map - NSString *dictPat = @"NSDictionary /\\* (.+), (.+) \\*/"; + NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/"; regexp = [NSRegularExpression regularExpressionWithPattern:dictPat options:NSRegularExpressionCaseInsensitive error:nil]; @@ -435,7 +441,16 @@ static bool loggingEnabled = true; return [NSNumber numberWithBool:[data boolValue]]; } else if ([class isEqualToString:@"NSNumber"]) { - return [data numberFromString:data]; + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + // NSNumber from NSString + else { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + return [formatter numberFromString:data]; + } } } diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index ba61a8b2c7c..1f3c6ca299e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -74,12 +74,12 @@ static NSString * basePath = @"{{basePath}}"; {{#operation}} -/*! - * {{{summary}}} - * {{{notes}}} -{{#allParams}} * \param {{paramName}} {{{description}}} -{{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ +// +// {{{summary}}} +// {{{notes}}} +// {{#allParams}} @param {{paramName}} {{{description}}} +// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +// -(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} {{/allParams}} {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}} diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 65f4c39e0b3..cc9ad03616e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -17,16 +17,15 @@ +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; {{#operation}} -/** - - {{{summary}}} - {{#notes}}{{{notes}}}{{/notes}} - - {{#allParams}}@param {{paramName}} {{description}} - {{/allParams}} - - return type: {{{returnType}}} - */ +// +// +// {{{summary}}} +// {{#notes}}{{{notes}}}{{/notes}} +// +// {{#allParams}}@param {{paramName}} {{description}} +// {{/allParams}} +// +// @return {{{returnType}}} -(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} {{/hasMore}}{{/allParams}} {{#returnBaseType}}{{#hasParams}} diff --git a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache deleted file mode 100644 index 7d178353d52..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache +++ /dev/null @@ -1,45 +0,0 @@ - // {{returnContainer}} container response type - return [self.apiClient dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - {{#isMapContainer}} - NSDictionary *result = nil; - if (data) { - result = [[NSDictionary alloc]initWithDictionary: data]; - } - completionBlock(data, nil); - {{/isMapContainer}}{{#isListContainer}} - {{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - {{#returnTypeIsPrimitive}} - {{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict]; - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil]; - {{/returnTypeIsPrimitive}} - [objs addObject:d]; - } - completionBlock(({{{returnType}}})objs, nil); - } - {{/returnBaseType}} - {{/isListContainer}} - }]; - - - - - - - - diff --git a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache deleted file mode 100644 index da8ea063bfb..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache +++ /dev/null @@ -1,24 +0,0 @@ - {{^returnTypeIsPrimitive}} - // comples response type - return [self.apiClient dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - {{#returnType}}{{returnType}} result = nil; - if (data) { - result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil]; - } - {{#returnType}}completionBlock(result , nil);{{/returnType}} - {{/returnType}} - }]; - {{/returnTypeIsPrimitive}} diff --git a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache deleted file mode 100644 index d44d356526d..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache +++ /dev/null @@ -1,36 +0,0 @@ - // primitive response type - {{#returnBaseType}}return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - {{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; - completionBlock(result, nil); - }]; - {{/returnBaseType}} - {{^returnBaseType}} - // no return base type - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - {{/returnBaseType}} - diff --git a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache deleted file mode 100644 index 7bbbc14c066..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache +++ /dev/null @@ -1,15 +0,0 @@ - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m new file mode 100644 index 00000000000..5440935be1b --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m @@ -0,0 +1,47 @@ +#import +#import +#import "SWGStoreApi.h" + +@interface StoreApiTest : XCTestCase + +@property (nonatomic) SWGStoreApi *api; + +@end + +@implementation StoreApiTest + +- (void)setUp { + [super setUp]; + self.api = [[SWGStoreApi alloc] init]; +} + +- (void)tearDown { + [super tearDown]; +} + +- (void)testGetInventory { + XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByStatus"]; + + [self.api getInventoryWithCompletionBlock:^(NSDictionary *output, NSError *error) { + + if (error) { + XCTFail(@"got error %@", error); + } + + if (!output) { + XCTFail(@"failed to fetch inventory"); + } + + NSSet *expectKeys = [NSSet setWithArray:@[@"confused", @"string", @"pending", @"available", @"sold"]]; + NSSet *keys = [NSSet setWithArray:[output allKeys]]; + + XCTAssertEqualObjects(expectKeys, keys); + + [expectation fulfill]; + }]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; +} + + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj index ae903f27499..ffb61953051 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj @@ -10,6 +10,7 @@ BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; CF0560EB1B1855CF00C0D4EC /* SWGConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */; }; CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF31D0981B105E4B00509935 /* SWGApiClientTest.m */; }; + CFB37D061B2B11DD00D2E5F1 /* StoreApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */; }; CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; @@ -60,6 +61,7 @@ CF0560E91B1855CF00C0D4EC /* SWGConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGConfiguration.h; sourceTree = ""; }; CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGConfiguration.m; sourceTree = ""; }; CF31D0981B105E4B00509935 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; + CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StoreApiTest.m; sourceTree = ""; }; CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = ""; }; CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = ""; }; E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; @@ -212,6 +214,7 @@ isa = PBXGroup; children = ( EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */, + CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */, CF31D0981B105E4B00509935 /* SWGApiClientTest.m */, EA6699C71811D2FB00A70D03 /* PetApiTest.m */, EA6699C21811D2FB00A70D03 /* Supporting Files */, @@ -426,6 +429,7 @@ EAB26B0C1AC8DF78002F5C7A /* PetApiTest.h in Sources */, CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */, + CFB37D061B2B11DD00D2E5F1 /* StoreApiTest.m in Sources */, CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m index fd15f391f49..56d0a8f621f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m @@ -8,6 +8,7 @@ #import "ViewController.h" #import "SWGPetApi.h" +#import "SWGStoreApi.h" #import "SWGConfiguration.h" @interface ViewController () @@ -54,14 +55,6 @@ // } ]; */ - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - config.username = @"foo"; - config.password = @"bar"; - SWGPetApi *api = [[SWGPetApi alloc] init]; - [api addPetWithCompletionBlock:nil - completionHandler:^(NSError *error) { - - }]; } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m index 61925b16960..1bd0c0eb1c3 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m @@ -98,4 +98,66 @@ XCTAssertEqualObjects(basicAuthCredentials, [config getBasicAuthToken]); } +- (void)testDeserialize { + id data; + id result; + + // list of models + data = + @[ + @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + }]; + result = [self.apiClient deserialize:data class:@"NSArray*"]; + + XCTAssertTrue([result isKindOfClass:[NSArray class]]); + XCTAssertTrue([[result firstObject] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([[result firstObject] _id], @119); + + // map of models + data = + @{ + @"pet": @{ + @"id": @119, + @"category": @{ + @"id": @0, + @"name": @"string" + }, + @"name": @"doggie", + @"photoUrls": @[ + @"string" + ], + @"tags": @[ + @{ + @"id": @0, + @"name": @"string" + } + ], + @"status": @"available" + + } + }; + result = [self.apiClient deserialize:data class:@"NSDictionary* /* NSString, SWGPet */"]; + + XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); + XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); + XCTAssertEqualObjects([result[@"pet"] _id], @119); +} + @end diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index ee8be40e2ab..45c6fc6d305 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -351,6 +351,7 @@ static bool loggingEnabled = true; *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } +#pragma mark - Deserialize methods - (id) deserialize:(id) data class:(NSString *) class { NSRegularExpression *regexp = nil; @@ -358,6 +359,11 @@ static bool loggingEnabled = true; NSMutableArray *resultArray = nil; NSMutableDictionary *resultDict = nil; + // remove "*" from class, if ends with "*" + if ([class hasSuffix:@"*"]) { + class = [class substringToIndex:[class length] - 1]; + } + // list of models NSString *arrayOfModelsPat = @"NSArray<(.+)>"; regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat @@ -371,7 +377,7 @@ static bool loggingEnabled = true; if (match) { NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; } @@ -390,7 +396,7 @@ static bool loggingEnabled = true; range:NSMakeRange(0, [class length])]; if (match) { - resultArray = [NSMutableArray arrayWithCapacity:[data length]]; + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]]; }]; @@ -399,7 +405,7 @@ static bool loggingEnabled = true; } // map - NSString *dictPat = @"NSDictionary /\\* (.+), (.+) \\*/"; + NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/"; regexp = [NSRegularExpression regularExpressionWithPattern:dictPat options:NSRegularExpressionCaseInsensitive error:nil]; @@ -435,7 +441,16 @@ static bool loggingEnabled = true; return [NSNumber numberWithBool:[data boolValue]]; } else if ([class isEqualToString:@"NSNumber"]) { - return [data numberFromString:data]; + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + // NSNumber from NSString + else { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + return [formatter numberFromString:data]; + } } } diff --git a/samples/client/petstore/objc/client/SWGPetApi.h b/samples/client/petstore/objc/client/SWGPetApi.h index aa255cd144e..ce17f2c30ab 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.h +++ b/samples/client/petstore/objc/client/SWGPetApi.h @@ -15,98 +15,92 @@ +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -/** - - Update an existing pet - - - @param body Pet object that needs to be added to the store - - - return type: - */ +// +// +// Update an existing pet +// +// +// @param body Pet object that needs to be added to the store +// +// +// @return -(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Add a new pet to the store - - - @param body Pet object that needs to be added to the store - - - return type: - */ +// +// +// Add a new pet to the store +// +// +// @param body Pet object that needs to be added to the store +// +// +// @return -(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Finds Pets by status - Multiple status values can be provided with comma seperated strings - - @param status Status values that need to be considered for filter - - - return type: NSArray* - */ +// +// +// Finds Pets by status +// Multiple status values can be provided with comma seperated strings +// +// @param status Status values that need to be considered for filter +// +// +// @return NSArray* -(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; -/** - - Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - - @param tags Tags to filter by - - - return type: NSArray* - */ +// +// +// Finds Pets by tags +// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +// +// @param tags Tags to filter by +// +// +// @return NSArray* -(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; -/** - - 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 type: SWGPet* - */ +// +// +// 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 SWGPet* -(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; -/** - - 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 type: - */ +// +// +// 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 -(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId name:(NSString*) name status:(NSString*) status @@ -115,17 +109,16 @@ completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Deletes a pet - - - @param apiKey - @param petId Pet id to delete - - - return type: - */ +// +// +// Deletes a pet +// +// +// @param apiKey +// @param petId Pet id to delete +// +// +// @return -(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey petId:(NSNumber*) petId @@ -133,18 +126,17 @@ completionHandler: (void (^)(NSError* error))completionBlock; -/** - - uploads an image - - - @param petId ID of pet to update - @param additionalMetadata Additional data to pass to server - @param file file to upload - - - return type: - */ +// +// +// uploads an image +// +// +// @param petId ID of pet to update +// @param additionalMetadata Additional data to pass to server +// @param file file to upload +// +// +// @return -(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId additionalMetadata:(NSString*) additionalMetadata file:(SWGFile*) file diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 8a03932001c..d23a2ce9979 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -72,12 +72,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } -/*! - * Update an existing pet - * - * \param body Pet object that needs to be added to the store - * \returns void - */ +// +// Update an existing pet +// +// @param body Pet object that needs to be added to the store +// @returns void +// -(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body @@ -168,12 +168,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Add a new pet to the store - * - * \param body Pet object that needs to be added to the store - * \returns void - */ +// +// Add a new pet to the store +// +// @param body Pet object that needs to be added to the store +// @returns void +// -(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body @@ -264,12 +264,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Finds Pets by status - * Multiple status values can be provided with comma seperated strings - * \param status Status values that need to be considered for filter - * \returns NSArray* - */ +// +// Finds Pets by status +// Multiple status values can be provided with comma seperated strings +// @param status Status values that need to be considered for filter +// @returns NSArray* +// -(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock @@ -343,12 +343,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Finds Pets by tags - * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - * \param tags Tags to filter by - * \returns NSArray* - */ +// +// Finds Pets by tags +// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +// @param tags Tags to filter by +// @returns NSArray* +// -(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock @@ -422,12 +422,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * 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 - * \returns SWGPet* - */ +// +// 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 +// @returns SWGPet* +// -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock @@ -499,14 +499,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * 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 - * \returns void - */ +// +// 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 +// @returns void +// -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId name: (NSString*) name status: (NSString*) status @@ -596,13 +596,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Deletes a pet - * - * \param apiKey - * \param petId Pet id to delete - * \returns void - */ +// +// Deletes a pet +// +// @param apiKey +// @param petId Pet id to delete +// @returns void +// -(NSNumber*) deletePetWithCompletionBlock: (NSString*) apiKey petId: (NSNumber*) petId @@ -677,14 +677,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * uploads an image - * - * \param petId ID of pet to update - * \param additionalMetadata Additional data to pass to server - * \param file file to upload - * \returns void - */ +// +// uploads an image +// +// @param petId ID of pet to update +// @param additionalMetadata Additional data to pass to server +// @param file file to upload +// @returns void +// -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (SWGFile*) file diff --git a/samples/client/petstore/objc/client/SWGStoreApi.h b/samples/client/petstore/objc/client/SWGStoreApi.h index b7d64469532..a59d861bbb8 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -14,62 +14,58 @@ +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -/** - - Returns pet inventories by status - Returns a map of status codes to quantities - - - - return type: NSDictionary* /* NSString, NSNumber */ - */ +// +// +// Returns pet inventories by status +// Returns a map of status codes to quantities +// +// +// +// @return NSDictionary* /* NSString, NSNumber */ -(NSNumber*) getInventoryWithCompletionBlock : (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock; -/** - - Place an order for a pet - - - @param body order placed for purchasing the pet - - - return type: SWGOrder* - */ +// +// +// Place an order for a pet +// +// +// @param body order placed for purchasing the pet +// +// +// @return SWGOrder* -(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; -/** - - Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - @param orderId ID of pet that needs to be fetched - - - return type: SWGOrder* - */ +// +// +// Find purchase order by ID +// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +// +// @param orderId ID of pet that needs to be fetched +// +// +// @return SWGOrder* -(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; -/** - - Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - - @param orderId ID of the order that needs to be deleted - - - return type: - */ +// +// +// Delete purchase order by ID +// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +// +// @param orderId ID of the order that needs to be deleted +// +// +// @return -(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index 0af0ebaad78..ce3a63c9483 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -71,17 +71,16 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } -/*! - * Returns pet inventories by status - * Returns a map of status codes to quantities - * \returns NSDictionary* /* NSString, NSNumber */ - */ +// +// Returns pet inventories by status +// Returns a map of status codes to quantities +// @returns NSDictionary* /* NSString, NSNumber */ +// -(NSNumber*) getInventoryWithCompletionBlock: (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock { - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; // remove format in URL if needed @@ -142,12 +141,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Place an order for a pet - * - * \param body order placed for purchasing the pet - * \returns SWGOrder* - */ +// +// Place an order for a pet +// +// @param body order placed for purchasing the pet +// @returns SWGOrder* +// -(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock @@ -238,12 +237,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Find purchase order by ID - * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - * \param orderId ID of pet that needs to be fetched - * \returns SWGOrder* - */ +// +// Find purchase order by ID +// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +// @param orderId ID of pet that needs to be fetched +// @returns SWGOrder* +// -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock @@ -315,12 +314,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Delete purchase order by ID - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - * \param orderId ID of the order that needs to be deleted - * \returns void - */ +// +// Delete purchase order by ID +// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +// @param orderId ID of the order that needs to be deleted +// @returns void +// -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId diff --git a/samples/client/petstore/objc/client/SWGUserApi.h b/samples/client/petstore/objc/client/SWGUserApi.h index e6e73ddfba6..c26046a17c6 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.h +++ b/samples/client/petstore/objc/client/SWGUserApi.h @@ -14,65 +14,61 @@ +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -/** - - Create user - This can only be done by the logged in user. - - @param body Created user object - - - return type: - */ +// +// +// Create user +// This can only be done by the logged in user. +// +// @param body Created user object +// +// +// @return -(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Creates list of users with given input array - - - @param body List of user object - - - return type: - */ +// +// +// Creates list of users with given input array +// +// +// @param body List of user object +// +// +// @return -(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray*) body completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Creates list of users with given input array - - - @param body List of user object - - - return type: - */ +// +// +// Creates list of users with given input array +// +// +// @param body List of user object +// +// +// @return -(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray*) body completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Logs user into the system - - - @param username The user name for login - @param password The password for login in clear text - - - return type: NSString* - */ +// +// +// Logs user into the system +// +// +// @param username The user name for login +// @param password The password for login in clear text +// +// +// @return NSString* -(NSNumber*) loginUserWithCompletionBlock :(NSString*) username password:(NSString*) password @@ -80,47 +76,44 @@ -/** - - Logs out current logged in user session - - - - - return type: - */ +// +// +// Logs out current logged in user session +// +// +// +// +// @return -(NSNumber*) logoutUserWithCompletionBlock : (void (^)(NSError* error))completionBlock; -/** - - Get user by user name - - - @param username The name that needs to be fetched. Use user1 for testing. - - - return type: SWGUser* - */ +// +// +// Get user by user name +// +// +// @param username The name that needs to be fetched. Use user1 for testing. +// +// +// @return SWGUser* -(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; -/** - - Updated user - This can only be done by the logged in user. - - @param username name that need to be deleted - @param body Updated user object - - - return type: - */ +// +// +// Updated user +// This can only be done by the logged in user. +// +// @param username name that need to be deleted +// @param body Updated user object +// +// +// @return -(NSNumber*) updateUserWithCompletionBlock :(NSString*) username body:(SWGUser*) body @@ -128,16 +121,15 @@ completionHandler: (void (^)(NSError* error))completionBlock; -/** - - Delete user - This can only be done by the logged in user. - - @param username The name that needs to be deleted - - - return type: - */ +// +// +// Delete user +// This can only be done by the logged in user. +// +// @param username The name that needs to be deleted +// +// +// @return -(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index 401df17e396..3ef45ea1e77 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -71,12 +71,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } -/*! - * Create user - * This can only be done by the logged in user. - * \param body Created user object - * \returns void - */ +// +// Create user +// This can only be done by the logged in user. +// @param body Created user object +// @returns void +// -(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body @@ -167,12 +167,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Creates list of users with given input array - * - * \param body List of user object - * \returns void - */ +// +// Creates list of users with given input array +// +// @param body List of user object +// @returns void +// -(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray*) body @@ -263,12 +263,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Creates list of users with given input array - * - * \param body List of user object - * \returns void - */ +// +// Creates list of users with given input array +// +// @param body List of user object +// @returns void +// -(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray*) body @@ -359,13 +359,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Logs user into the system - * - * \param username The user name for login - * \param password The password for login in clear text - * \returns NSString* - */ +// +// Logs user into the system +// +// @param username The user name for login +// @param password The password for login in clear text +// @returns NSString* +// -(NSNumber*) loginUserWithCompletionBlock: (NSString*) username password: (NSString*) password @@ -442,11 +442,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Logs out current logged in user session - * - * \returns void - */ +// +// Logs out current logged in user session +// +// @returns void +// -(NSNumber*) logoutUserWithCompletionBlock: (void (^)(NSError* error))completionBlock { @@ -513,12 +513,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Get user by user name - * - * \param username The name that needs to be fetched. Use user1 for testing. - * \returns SWGUser* - */ +// +// Get user by user name +// +// @param username The name that needs to be fetched. Use user1 for testing. +// @returns SWGUser* +// -(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock @@ -590,13 +590,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Updated user - * This can only be done by the logged in user. - * \param username name that need to be deleted - * \param body Updated user object - * \returns void - */ +// +// Updated user +// This can only be done by the logged in user. +// @param username name that need to be deleted +// @param body Updated user object +// @returns void +// -(NSNumber*) updateUserWithCompletionBlock: (NSString*) username body: (SWGUser*) body @@ -692,12 +692,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -/*! - * Delete user - * This can only be done by the logged in user. - * \param username The name that needs to be deleted - * \returns void - */ +// +// Delete user +// This can only be done by the logged in user. +// @param username The name that needs to be deleted +// @returns void +// -(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username From a6bdc35d59b0692352f6465a4f483c0f182cc0e8 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 13 Jun 2015 10:17:08 +0800 Subject: [PATCH 17/30] Support pure object response for objc client --- .../src/main/resources/objc/SWGApiClient-body.mustache | 5 +++++ .../objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m | 2 +- .../objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m | 5 +++++ samples/client/petstore/objc/client/SWGApiClient.m | 5 +++++ samples/client/petstore/objc/client/SWGStoreApi.m | 1 + 5 files changed, 17 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache index 45c6fc6d305..a0c9c63d27c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache @@ -364,6 +364,11 @@ static bool loggingEnabled = true; class = [class substringToIndex:[class length] - 1]; } + // pure object + if ([class isEqualToString:@"NSObject"]) { + return [[NSObject alloc] init]; + } + // list of models NSString *arrayOfModelsPat = @"NSArray<(.+)>"; regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m index 5440935be1b..8ea2e7ee0fc 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m @@ -32,7 +32,7 @@ XCTFail(@"failed to fetch inventory"); } - NSSet *expectKeys = [NSSet setWithArray:@[@"confused", @"string", @"pending", @"available", @"sold"]]; + NSSet *expectKeys = [NSSet setWithArray:@[@"confused", @"string", @"available"]]; NSSet *keys = [NSSet setWithArray:[output allKeys]]; XCTAssertEqualObjects(expectKeys, keys); diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m index 1bd0c0eb1c3..597cf2fb714 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m @@ -158,6 +158,11 @@ XCTAssertTrue([result isKindOfClass:[NSDictionary class]]); XCTAssertTrue([result[@"pet"] isKindOfClass:[SWGPet class]]); XCTAssertEqualObjects([result[@"pet"] _id], @119); + + // pure object + result = [self.apiClient deserialize:nil class:@"NSObject*"]; + + XCTAssertTrue([result isKindOfClass:[NSObject class]]); } @end diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index 45c6fc6d305..a0c9c63d27c 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -364,6 +364,11 @@ static bool loggingEnabled = true; class = [class substringToIndex:[class length] - 1]; } + // pure object + if ([class isEqualToString:@"NSObject"]) { + return [[NSObject alloc] init]; + } + // list of models NSString *arrayOfModelsPat = @"NSArray<(.+)>"; regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index ce3a63c9483..2613f8b6caf 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -81,6 +81,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; { + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; // remove format in URL if needed From bc92465bf7596d488b9e3cb73325b773033a2482 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 13 Jun 2015 10:48:45 +0800 Subject: [PATCH 18/30] Update Objective-C method description (doc comments) style --- .../src/main/resources/objc/api-body.mustache | 14 +- .../main/resources/objc/api-header.mustache | 18 +- .../client/petstore/objc/client/SWGPetApi.h | 154 +++++++++--------- .../client/petstore/objc/client/SWGPetApi.m | 120 ++++++++------ .../client/petstore/objc/client/SWGStoreApi.h | 70 ++++---- .../client/petstore/objc/client/SWGStoreApi.m | 50 +++--- .../client/petstore/objc/client/SWGUserApi.h | 146 ++++++++--------- .../client/petstore/objc/client/SWGUserApi.m | 108 ++++++------ 8 files changed, 355 insertions(+), 325 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 1f3c6ca299e..29dca1f4a7a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -72,14 +72,16 @@ static NSString * basePath = @"{{basePath}}"; return [SWGApiClient requestQueueSize]; } +#pragma mark - Api Methods {{#operation}} -// -// {{{summary}}} -// {{{notes}}} -// {{#allParams}} @param {{paramName}} {{{description}}} -// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} -// +/// +/// {{{summary}}} +/// {{{notes}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} +/// +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// -(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} {{/allParams}} {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}} diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index cc9ad03616e..7f14262d116 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -17,15 +17,15 @@ +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; {{#operation}} -// -// -// {{{summary}}} -// {{#notes}}{{{notes}}}{{/notes}} -// -// {{#allParams}}@param {{paramName}} {{description}} -// {{/allParams}} -// -// @return {{{returnType}}} +/// +/// +/// {{{summary}}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}} +/// {{/allParams}} +/// +/// @return {{{returnType}}} -(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} {{/hasMore}}{{/allParams}} {{#returnBaseType}}{{#hasParams}} diff --git a/samples/client/petstore/objc/client/SWGPetApi.h b/samples/client/petstore/objc/client/SWGPetApi.h index ce17f2c30ab..257a7d1453e 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.h +++ b/samples/client/petstore/objc/client/SWGPetApi.h @@ -15,92 +15,92 @@ +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -// -// -// Update an existing pet -// -// -// @param body Pet object that needs to be added to the store -// -// -// @return +/// +/// +/// Update an existing pet +/// +/// +/// @param body Pet object that needs to be added to the store +/// +/// +/// @return -(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Add a new pet to the store -// -// -// @param body Pet object that needs to be added to the store -// -// -// @return +/// +/// +/// Add a new pet to the store +/// +/// +/// @param body Pet object that needs to be added to the store +/// +/// +/// @return -(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Finds Pets by status -// Multiple status values can be provided with comma seperated strings -// -// @param status Status values that need to be considered for filter -// -// -// @return NSArray* +/// +/// +/// Finds Pets by status +/// Multiple status values can be provided with comma seperated strings +/// +/// @param status Status values that need to be considered for filter +/// +/// +/// @return NSArray* -(NSNumber*) findPetsByStatusWithCompletionBlock :(NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; -// -// -// Finds Pets by tags -// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. -// -// @param tags Tags to filter by -// -// -// @return NSArray* +/// +/// +/// Finds Pets by tags +/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// +/// @param tags Tags to filter by +/// +/// +/// @return NSArray* -(NSNumber*) findPetsByTagsWithCompletionBlock :(NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; -// -// -// 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 SWGPet* +/// +/// +/// 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 SWGPet* -(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; -// -// -// 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 +/// +/// +/// 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 -(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId name:(NSString*) name status:(NSString*) status @@ -109,16 +109,16 @@ completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Deletes a pet -// -// -// @param apiKey -// @param petId Pet id to delete -// -// -// @return +/// +/// +/// Deletes a pet +/// +/// +/// @param apiKey +/// @param petId Pet id to delete +/// +/// +/// @return -(NSNumber*) deletePetWithCompletionBlock :(NSString*) apiKey petId:(NSNumber*) petId @@ -126,17 +126,17 @@ completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// uploads an image -// -// -// @param petId ID of pet to update -// @param additionalMetadata Additional data to pass to server -// @param file file to upload -// -// -// @return +/// +/// +/// uploads an image +/// +/// +/// @param petId ID of pet to update +/// @param additionalMetadata Additional data to pass to server +/// @param file file to upload +/// +/// +/// @return -(NSNumber*) uploadFileWithCompletionBlock :(NSNumber*) petId additionalMetadata:(NSString*) additionalMetadata file:(SWGFile*) file diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index d23a2ce9979..e4306f1b235 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -71,13 +71,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return [SWGApiClient requestQueueSize]; } +#pragma mark - Api Methods -// -// Update an existing pet -// -// @param body Pet object that needs to be added to the store -// @returns void -// +/// +/// Update an existing pet +/// +/// @param body Pet object that needs to be added to the store +/// +/// @returns void +/// -(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body @@ -168,12 +170,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Add a new pet to the store -// -// @param body Pet object that needs to be added to the store -// @returns void -// +/// +/// Add a new pet to the store +/// +/// @param body Pet object that needs to be added to the store +/// +/// @returns void +/// -(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body @@ -264,12 +267,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Finds Pets by status -// Multiple status values can be provided with comma seperated strings -// @param status Status values that need to be considered for filter -// @returns NSArray* -// +/// +/// Finds Pets by status +/// Multiple status values can be provided with comma seperated strings +/// @param status Status values that need to be considered for filter +/// +/// @returns NSArray* +/// -(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock @@ -343,12 +347,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Finds Pets by tags -// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. -// @param tags Tags to filter by -// @returns NSArray* -// +/// +/// Finds Pets by tags +/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// @param tags Tags to filter by +/// +/// @returns NSArray* +/// -(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock @@ -422,12 +427,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// 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 -// @returns SWGPet* -// +/// +/// 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 +/// +/// @returns SWGPet* +/// -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock @@ -499,14 +505,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// 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 -// @returns void -// +/// +/// 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 +/// +/// @returns void +/// -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId name: (NSString*) name status: (NSString*) status @@ -596,13 +605,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Deletes a pet -// -// @param apiKey -// @param petId Pet id to delete -// @returns void -// +/// +/// Deletes a pet +/// +/// @param apiKey +/// +/// @param petId Pet id to delete +/// +/// @returns void +/// -(NSNumber*) deletePetWithCompletionBlock: (NSString*) apiKey petId: (NSNumber*) petId @@ -677,14 +688,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// uploads an image -// -// @param petId ID of pet to update -// @param additionalMetadata Additional data to pass to server -// @param file file to upload -// @returns void -// +/// +/// uploads an image +/// +/// @param petId ID of pet to update +/// +/// @param additionalMetadata Additional data to pass to server +/// +/// @param file file to upload +/// +/// @returns void +/// -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (SWGFile*) file diff --git a/samples/client/petstore/objc/client/SWGStoreApi.h b/samples/client/petstore/objc/client/SWGStoreApi.h index a59d861bbb8..7488c1baa70 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -14,58 +14,58 @@ +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -// -// -// Returns pet inventories by status -// Returns a map of status codes to quantities -// -// -// -// @return NSDictionary* /* NSString, NSNumber */ +/// +/// +/// Returns pet inventories by status +/// Returns a map of status codes to quantities +/// +/// +/// +/// @return NSDictionary* /* NSString, NSNumber */ -(NSNumber*) getInventoryWithCompletionBlock : (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock; -// -// -// Place an order for a pet -// -// -// @param body order placed for purchasing the pet -// -// -// @return SWGOrder* +/// +/// +/// Place an order for a pet +/// +/// +/// @param body order placed for purchasing the pet +/// +/// +/// @return SWGOrder* -(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; -// -// -// Find purchase order by ID -// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -// -// @param orderId ID of pet that needs to be fetched -// -// -// @return SWGOrder* +/// +/// +/// Find purchase order by ID +/// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +/// +/// @param orderId ID of pet that needs to be fetched +/// +/// +/// @return SWGOrder* -(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; -// -// -// Delete purchase order by ID -// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -// -// @param orderId ID of the order that needs to be deleted -// -// -// @return +/// +/// +/// Delete purchase order by ID +/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +/// +/// @param orderId ID of the order that needs to be deleted +/// +/// +/// @return -(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index 2613f8b6caf..98582602027 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -70,12 +70,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return [SWGApiClient requestQueueSize]; } +#pragma mark - Api Methods -// -// Returns pet inventories by status -// Returns a map of status codes to quantities -// @returns NSDictionary* /* NSString, NSNumber */ -// +/// +/// Returns pet inventories by status +/// Returns a map of status codes to quantities +/// @returns NSDictionary* /* NSString, NSNumber */ +/// -(NSNumber*) getInventoryWithCompletionBlock: (void (^)(NSDictionary* /* NSString, NSNumber */ output, NSError* error))completionBlock { @@ -142,12 +143,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Place an order for a pet -// -// @param body order placed for purchasing the pet -// @returns SWGOrder* -// +/// +/// Place an order for a pet +/// +/// @param body order placed for purchasing the pet +/// +/// @returns SWGOrder* +/// -(NSNumber*) placeOrderWithCompletionBlock: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock @@ -238,12 +240,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Find purchase order by ID -// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -// @param orderId ID of pet that needs to be fetched -// @returns SWGOrder* -// +/// +/// Find purchase order by ID +/// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions +/// @param orderId ID of pet that needs to be fetched +/// +/// @returns SWGOrder* +/// -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock @@ -315,12 +318,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Delete purchase order by ID -// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -// @param orderId ID of the order that needs to be deleted -// @returns void -// +/// +/// Delete purchase order by ID +/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors +/// @param orderId ID of the order that needs to be deleted +/// +/// @returns void +/// -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId diff --git a/samples/client/petstore/objc/client/SWGUserApi.h b/samples/client/petstore/objc/client/SWGUserApi.h index c26046a17c6..6fda87cca70 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.h +++ b/samples/client/petstore/objc/client/SWGUserApi.h @@ -14,61 +14,61 @@ +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; +(void) setBasePath:(NSString*)basePath; +(NSString*) getBasePath; -// -// -// Create user -// This can only be done by the logged in user. -// -// @param body Created user object -// -// -// @return +/// +/// +/// Create user +/// This can only be done by the logged in user. +/// +/// @param body Created user object +/// +/// +/// @return -(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Creates list of users with given input array -// -// -// @param body List of user object -// -// -// @return +/// +/// +/// Creates list of users with given input array +/// +/// +/// @param body List of user object +/// +/// +/// @return -(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray*) body completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Creates list of users with given input array -// -// -// @param body List of user object -// -// -// @return +/// +/// +/// Creates list of users with given input array +/// +/// +/// @param body List of user object +/// +/// +/// @return -(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray*) body completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Logs user into the system -// -// -// @param username The user name for login -// @param password The password for login in clear text -// -// -// @return NSString* +/// +/// +/// Logs user into the system +/// +/// +/// @param username The user name for login +/// @param password The password for login in clear text +/// +/// +/// @return NSString* -(NSNumber*) loginUserWithCompletionBlock :(NSString*) username password:(NSString*) password @@ -76,44 +76,44 @@ -// -// -// Logs out current logged in user session -// -// -// -// -// @return +/// +/// +/// Logs out current logged in user session +/// +/// +/// +/// +/// @return -(NSNumber*) logoutUserWithCompletionBlock : (void (^)(NSError* error))completionBlock; -// -// -// Get user by user name -// -// -// @param username The name that needs to be fetched. Use user1 for testing. -// -// -// @return SWGUser* +/// +/// +/// Get user by user name +/// +/// +/// @param username The name that needs to be fetched. Use user1 for testing. +/// +/// +/// @return SWGUser* -(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; -// -// -// Updated user -// This can only be done by the logged in user. -// -// @param username name that need to be deleted -// @param body Updated user object -// -// -// @return +/// +/// +/// Updated user +/// This can only be done by the logged in user. +/// +/// @param username name that need to be deleted +/// @param body Updated user object +/// +/// +/// @return -(NSNumber*) updateUserWithCompletionBlock :(NSString*) username body:(SWGUser*) body @@ -121,15 +121,15 @@ completionHandler: (void (^)(NSError* error))completionBlock; -// -// -// Delete user -// This can only be done by the logged in user. -// -// @param username The name that needs to be deleted -// -// -// @return +/// +/// +/// Delete user +/// This can only be done by the logged in user. +/// +/// @param username The name that needs to be deleted +/// +/// +/// @return -(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index 3ef45ea1e77..2e8ce66b74e 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -70,13 +70,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return [SWGApiClient requestQueueSize]; } +#pragma mark - Api Methods -// -// Create user -// This can only be done by the logged in user. -// @param body Created user object -// @returns void -// +/// +/// Create user +/// This can only be done by the logged in user. +/// @param body Created user object +/// +/// @returns void +/// -(NSNumber*) createUserWithCompletionBlock: (SWGUser*) body @@ -167,12 +169,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Creates list of users with given input array -// -// @param body List of user object -// @returns void -// +/// +/// Creates list of users with given input array +/// +/// @param body List of user object +/// +/// @returns void +/// -(NSNumber*) createUsersWithArrayInputWithCompletionBlock: (NSArray*) body @@ -263,12 +266,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Creates list of users with given input array -// -// @param body List of user object -// @returns void -// +/// +/// Creates list of users with given input array +/// +/// @param body List of user object +/// +/// @returns void +/// -(NSNumber*) createUsersWithListInputWithCompletionBlock: (NSArray*) body @@ -359,13 +363,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Logs user into the system -// -// @param username The user name for login -// @param password The password for login in clear text -// @returns NSString* -// +/// +/// Logs user into the system +/// +/// @param username The user name for login +/// +/// @param password The password for login in clear text +/// +/// @returns NSString* +/// -(NSNumber*) loginUserWithCompletionBlock: (NSString*) username password: (NSString*) password @@ -442,11 +448,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Logs out current logged in user session -// -// @returns void -// +/// +/// Logs out current logged in user session +/// +/// @returns void +/// -(NSNumber*) logoutUserWithCompletionBlock: (void (^)(NSError* error))completionBlock { @@ -513,12 +519,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Get user by user name -// -// @param username The name that needs to be fetched. Use user1 for testing. -// @returns SWGUser* -// +/// +/// Get user by user name +/// +/// @param username The name that needs to be fetched. Use user1 for testing. +/// +/// @returns SWGUser* +/// -(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock @@ -590,13 +597,15 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Updated user -// This can only be done by the logged in user. -// @param username name that need to be deleted -// @param body Updated user object -// @returns void -// +/// +/// Updated user +/// This can only be done by the logged in user. +/// @param username name that need to be deleted +/// +/// @param body Updated user object +/// +/// @returns void +/// -(NSNumber*) updateUserWithCompletionBlock: (NSString*) username body: (SWGUser*) body @@ -692,12 +701,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; ]; } -// -// Delete user -// This can only be done by the logged in user. -// @param username The name that needs to be deleted -// @returns void -// +/// +/// Delete user +/// This can only be done by the logged in user. +/// @param username The name that needs to be deleted +/// +/// @returns void +/// -(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username From 8b15416be5eb405174d6d147723f7a0ce9d11005 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 13 Jun 2015 17:31:48 +0800 Subject: [PATCH 19/30] Add SWGJSONResponseSerializer for objective-c client. If the response data is valid json, return the deserialized json. If the response data is invalid json, return the string of response data. --- .../codegen/languages/ObjcClientCodegen.java | 2 + .../resources/objc/SWGApiClient-body.mustache | 5 ++ .../SWGJSONResponseSerializer-body.mustache | 28 +++++++++++ .../SWGJSONResponseSerializer-header.mustache | 6 +++ .../PetstoreClientTests/StoreApiTest.m | 5 +- .../PetstoreClientTests/UserApiTest.m | 47 +++++++++++++++++++ .../SwaggerClient.xcodeproj/project.pbxproj | 10 ++++ .../SwaggerClient/ViewController.m | 6 +++ .../SwaggerClientTests/SWGApiClientTest.m | 8 +++- .../petstore/objc/client/SWGApiClient.m | 5 ++ .../objc/client/SWGJSONResponseSerializer.h | 6 +++ .../objc/client/SWGJSONResponseSerializer.m | 28 +++++++++++ 12 files changed, 151 insertions(+), 5 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-header.mustache create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/UserApiTest.m create mode 100644 samples/client/petstore/objc/client/SWGJSONResponseSerializer.h create mode 100644 samples/client/petstore/objc/client/SWGJSONResponseSerializer.m diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index ce3ec065012..ddd4d0c53ff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -145,6 +145,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m")); supportingFiles.add(new SupportingFile("SWGApiClient-header.mustache", sourceFolder, "SWGApiClient.h")); supportingFiles.add(new SupportingFile("SWGApiClient-body.mustache", sourceFolder, "SWGApiClient.m")); + supportingFiles.add(new SupportingFile("SWGJSONResponseSerializer-header.mustache", sourceFolder, "SWGJSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("SWGJSONResponseSerializer-body.mustache", sourceFolder, "SWGJSONResponseSerializer.m")); supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache index a0c9c63d27c..39ad87c76bb 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache @@ -359,6 +359,11 @@ static bool loggingEnabled = true; NSMutableArray *resultArray = nil; NSMutableDictionary *resultDict = nil; + // return nil if data is nil + if (!data) { + return nil; + } + // remove "*" from class, if ends with "*" if ([class hasSuffix:@"*"]) { class = [class substringToIndex:[class length] - 1]; diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache new file mode 100644 index 00000000000..80fd09f6954 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache @@ -0,0 +1,28 @@ +#import "SWGJSONResponseSerializer.h" + +static BOOL JSONParseError(NSError *error) { + if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { + return YES; + } + + return NO; +} + +@implementation SWGJSONResponseSerializer + +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { + NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; + + // if response data is not a valid json, return string of data. + if (JSONParseError(*error)) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-header.mustache new file mode 100644 index 00000000000..16cda122217 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-header.mustache @@ -0,0 +1,6 @@ +#import +#import + +@interface SWGJSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m index 8ea2e7ee0fc..d2864afe51d 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m @@ -32,10 +32,7 @@ XCTFail(@"failed to fetch inventory"); } - NSSet *expectKeys = [NSSet setWithArray:@[@"confused", @"string", @"available"]]; - NSSet *keys = [NSSet setWithArray:[output allKeys]]; - - XCTAssertEqualObjects(expectKeys, keys); + XCTAssertNotNil(output.allKeys); [expectation fulfill]; }]; diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/UserApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/UserApiTest.m new file mode 100644 index 00000000000..b703797a280 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/UserApiTest.m @@ -0,0 +1,47 @@ +#import +#import +#import "SWGUserApi.h" + +@interface UserApiTest : XCTestCase + +@property (nonatomic) SWGUserApi *api; + +@end + +@implementation UserApiTest + +- (void)setUp { + [super setUp]; + self.api = [[SWGUserApi alloc] init]; +} + +- (void)tearDown { + [super tearDown]; +} + +- (void)testLoginUser { + XCTestExpectation *expectation = [self expectationWithDescription:@"test login user"]; + + [self.api loginUserWithCompletionBlock:@"test username" password:@"test password" completionHandler:^(NSString *output, NSError *error) { + if (error) { + XCTFail(@"got error %@", error); + } + + if (!output) { + XCTFail(@"response can't be nil"); + } + + NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"logged in user" + options:0 + error:nil]; + NSTextCheckingResult *match = [regex firstMatchInString:output + options:0 + range:NSMakeRange(0, [output length])]; + XCTAssertNotNil(match); + [expectation fulfill]; + }]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; +} + +@end diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj index ffb61953051..ac15f78e357 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClient.xcodeproj/project.pbxproj @@ -10,7 +10,9 @@ BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; CF0560EB1B1855CF00C0D4EC /* SWGConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */; }; CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF31D0981B105E4B00509935 /* SWGApiClientTest.m */; }; + CF5B6E2D1B2BD70800862A1C /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF5B6E2C1B2BD70800862A1C /* UserApiTest.m */; }; CFB37D061B2B11DD00D2E5F1 /* StoreApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */; }; + CFCEFE511B2C1330006313BE /* SWGJSONResponseSerializer.m in Sources */ = {isa = PBXBuildFile; fileRef = CFCEFE501B2C1330006313BE /* SWGJSONResponseSerializer.m */; }; CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; @@ -61,7 +63,10 @@ CF0560E91B1855CF00C0D4EC /* SWGConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGConfiguration.h; sourceTree = ""; }; CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGConfiguration.m; sourceTree = ""; }; CF31D0981B105E4B00509935 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; + CF5B6E2C1B2BD70800862A1C /* UserApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = UserApiTest.m; sourceTree = ""; }; CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = StoreApiTest.m; sourceTree = ""; }; + CFCEFE4F1B2C1330006313BE /* SWGJSONResponseSerializer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGJSONResponseSerializer.h; sourceTree = ""; }; + CFCEFE501B2C1330006313BE /* SWGJSONResponseSerializer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGJSONResponseSerializer.m; sourceTree = ""; }; CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = ""; }; CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = ""; }; E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; @@ -214,6 +219,7 @@ isa = PBXGroup; children = ( EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */, + CF5B6E2C1B2BD70800862A1C /* UserApiTest.m */, CFB37D051B2B11DC00D2E5F1 /* StoreApiTest.m */, CF31D0981B105E4B00509935 /* SWGApiClientTest.m */, EA6699C71811D2FB00A70D03 /* PetApiTest.m */, @@ -251,6 +257,8 @@ EAEA85D61811D3AE00F06E69 /* SWGOrder.h */, EAEA85D71811D3AE00F06E69 /* SWGOrder.m */, EAB26B0E1AC8E692002F5C7A /* SWGPet.h */, + CFCEFE4F1B2C1330006313BE /* SWGJSONResponseSerializer.h */, + CFCEFE501B2C1330006313BE /* SWGJSONResponseSerializer.m */, EAEA85D91811D3AE00F06E69 /* SWGPet.m */, EAEA85DA1811D3AE00F06E69 /* SWGPetApi.h */, EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */, @@ -418,6 +426,7 @@ EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */, EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */, EA8B8AA41AC6683700638FBB /* SWGQueryParamCollection.m in Sources */, + CFCEFE511B2C1330006313BE /* SWGJSONResponseSerializer.m in Sources */, EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; @@ -429,6 +438,7 @@ EAB26B0C1AC8DF78002F5C7A /* PetApiTest.h in Sources */, CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */, + CF5B6E2D1B2BD70800862A1C /* UserApiTest.m in Sources */, CFB37D061B2B11DD00D2E5F1 /* StoreApiTest.m in Sources */, CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */, ); diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m index 56d0a8f621f..5ba0fe18382 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m @@ -9,6 +9,7 @@ #import "ViewController.h" #import "SWGPetApi.h" #import "SWGStoreApi.h" +#import "SWGUserApi.h" #import "SWGConfiguration.h" @interface ViewController () @@ -55,6 +56,11 @@ // } ]; */ + SWGUserApi *api = [[SWGUserApi alloc] init]; + [api loginUserWithCompletionBlock:@"username" password:@"password" completionHandler:^(NSString *output, NSError *error) { + NSLog(@"output => %@", output); + NSLog(@"error => %@", error); + }]; } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m index 597cf2fb714..c68b3e2a42e 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/SWGApiClientTest.m @@ -160,9 +160,15 @@ XCTAssertEqualObjects([result[@"pet"] _id], @119); // pure object - result = [self.apiClient deserialize:nil class:@"NSObject*"]; + result = [self.apiClient deserialize:@"" class:@"NSObject*"]; XCTAssertTrue([result isKindOfClass:[NSObject class]]); + + // NSString + data = @"test string"; + result = [self.apiClient deserialize:data class:@"NSString*"]; + + XCTAssertTrue([result isKindOfClass:[NSString class]]); } @end diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index a0c9c63d27c..39ad87c76bb 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -359,6 +359,11 @@ static bool loggingEnabled = true; NSMutableArray *resultArray = nil; NSMutableDictionary *resultDict = nil; + // return nil if data is nil + if (!data) { + return nil; + } + // remove "*" from class, if ends with "*" if ([class hasSuffix:@"*"]) { class = [class substringToIndex:[class length] - 1]; diff --git a/samples/client/petstore/objc/client/SWGJSONResponseSerializer.h b/samples/client/petstore/objc/client/SWGJSONResponseSerializer.h new file mode 100644 index 00000000000..16cda122217 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGJSONResponseSerializer.h @@ -0,0 +1,6 @@ +#import +#import + +@interface SWGJSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m b/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m new file mode 100644 index 00000000000..80fd09f6954 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m @@ -0,0 +1,28 @@ +#import "SWGJSONResponseSerializer.h" + +static BOOL JSONParseError(NSError *error) { + if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { + return YES; + } + + return NO; +} + +@implementation SWGJSONResponseSerializer + +- (id) responseObjectForResponse:(NSURLResponse *)response + data:(NSData *)data + error:(NSError *__autoreleasing *)error { + NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; + + // if response data is not a valid json, return string of data. + if (JSONParseError(*error)) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +@end From a4df33d04083a54b6ea7650089a24a0e556fccc4 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 13 Jun 2015 17:49:39 +0800 Subject: [PATCH 20/30] Add comments for SWGJSONResponseSerializer#responseObjectForResponse method of objective-c client. --- .../objc/SWGJSONResponseSerializer-body.mustache | 11 +++++++++++ .../petstore/objc/client/SWGJSONResponseSerializer.m | 11 +++++++++++ 2 files changed, 22 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache index 80fd09f6954..a2dd21bcf5d 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGJSONResponseSerializer-body.mustache @@ -10,6 +10,17 @@ static BOOL JSONParseError(NSError *error) { @implementation SWGJSONResponseSerializer +/// +/// When customize a response serializer, +/// the serializer must conform the protocol `AFURLResponseSerialization` +/// and implements the protocol method `responseObjectForResponse:error:` +/// +/// @param response The response to be processed. +/// @param data The response data to be decoded. +/// @param error The error that occurred while attempting to decode the respnse data. +/// +/// @return The object decoded from the specified response data. +/// - (id) responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error { diff --git a/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m b/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m index 80fd09f6954..a2dd21bcf5d 100644 --- a/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m +++ b/samples/client/petstore/objc/client/SWGJSONResponseSerializer.m @@ -10,6 +10,17 @@ static BOOL JSONParseError(NSError *error) { @implementation SWGJSONResponseSerializer +/// +/// When customize a response serializer, +/// the serializer must conform the protocol `AFURLResponseSerialization` +/// and implements the protocol method `responseObjectForResponse:error:` +/// +/// @param response The response to be processed. +/// @param data The response data to be decoded. +/// @param error The error that occurred while attempting to decode the respnse data. +/// +/// @return The object decoded from the specified response data. +/// - (id) responseObjectForResponse:(NSURLResponse *)response data:(NSData *)data error:(NSError *__autoreleasing *)error { From 6b6480a026604c8ed1bc6441270eea54a82b1080 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 18 Jun 2015 10:38:19 +0800 Subject: [PATCH 21/30] Updated xcode project of objc client --- .../codegen/languages/ObjcClientCodegen.java | 2 +- .../resources/objc/SWGApiClient-body.mustache | 2 +- .../objc/SWGApiClient-header.mustache | 1 + .../xcshareddata/SwaggerClient.xccheckout | 41 ++++++++++++++++++ .../UserInterfaceState.xcuserstate | Bin 7666 -> 16336 bytes .../xcdebugger/Breakpoints_v2.xcbkptlist | 17 ++++++++ .../SwaggerClient/ViewController.m | 13 +++--- .../SwaggerClientTests}/StoreApiTest.m | 0 .../SwaggerClientTests}/UserApiTest.m | 0 .../petstore/objc/client/SWGApiClient.h | 1 + .../petstore/objc/client/SWGApiClient.m | 2 +- 11 files changed, 71 insertions(+), 8 deletions(-) create mode 100644 samples/client/petstore/objc/SwaggerClient.xcworkspace/xcshareddata/SwaggerClient.xccheckout create mode 100644 samples/client/petstore/objc/SwaggerClient.xcworkspace/xcuserdata/geekerzp.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist rename samples/client/petstore/objc/{PetstoreClient/PetstoreClientTests => SwaggerClient/SwaggerClientTests}/StoreApiTest.m (100%) rename samples/client/petstore/objc/{PetstoreClient/PetstoreClientTests => SwaggerClient/SwaggerClientTests}/UserApiTest.m (100%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index ddd4d0c53ff..03905cbdfaf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -153,7 +153,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m")); supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h")); - // supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); + supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache index 39ad87c76bb..1b479d039e6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-body.mustache @@ -500,7 +500,7 @@ static bool loggingEnabled = true; // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [AFJSONResponseSerializer serializer]; + self.responseSerializer = [SWGJSONResponseSerializer serializer]; } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache index 09cb6fe57bd..691c92cc625 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient-header.mustache @@ -1,6 +1,7 @@ #import #import #import "AFHTTPRequestOperationManager.h" +#import "SWGJSONResponseSerializer.h" {{#models}}{{#model}}#import "{{classname}}.h" {{/model}}{{/models}} diff --git a/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcshareddata/SwaggerClient.xccheckout b/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcshareddata/SwaggerClient.xccheckout new file mode 100644 index 00000000000..325cb92c1b8 --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcshareddata/SwaggerClient.xccheckout @@ -0,0 +1,41 @@ + + + + + IDESourceControlProjectFavoriteDictionaryKey + + IDESourceControlProjectIdentifier + 15AAFA18-9D61-437F-988D-A691BA4C08B1 + IDESourceControlProjectName + SwaggerClient + IDESourceControlProjectOriginsDictionary + + E5BBF0AA85077C865C95437976D06D819733A208 + https://github.com/geekerzp/swagger-codegen.git + + IDESourceControlProjectPath + samples/client/petstore/objc/SwaggerClient.xcworkspace + IDESourceControlProjectRelativeInstallPathDictionary + + E5BBF0AA85077C865C95437976D06D819733A208 + ../../../../.. + + IDESourceControlProjectURL + https://github.com/geekerzp/swagger-codegen.git + IDESourceControlProjectVersion + 111 + IDESourceControlProjectWCCIdentifier + E5BBF0AA85077C865C95437976D06D819733A208 + IDESourceControlProjectWCConfigurations + + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + E5BBF0AA85077C865C95437976D06D819733A208 + IDESourceControlWCCName + swagger-codegen + + + + diff --git a/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcuserdata/geekerzp.xcuserdatad/UserInterfaceState.xcuserstate b/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcuserdata/geekerzp.xcuserdatad/UserInterfaceState.xcuserstate index 79012184db63a3743953f712c7514d98f2b40464..d8a48b72bc2eb6cb0a734c22a88f15e99e0edb35 100644 GIT binary patch literal 16336 zcmd6Od3=+__V>&)PrA2Ro2_k+pPo5@i6z}zqd++qe%?*!h)BT<< z8N!!r-Xq0VqDT~lbPc)%-HHa#4zv^9j_yQvqjhK>x)0rt9z~C# zC($$LMf3_fjNU}=qW93p=r}rwzCquj@6b;;8pq&R9Eam^0v2Nlmf{qw!+LDMso03q za5~PyR$PEf@MwG<9*f80N?e7f;OTeG@g}?(Z^PU1F1#1tjqk&c;r;k={2YEBzkpxGuj6;|d-xds6n}<) z!N1~D_&5AJK8?>XVn)J985tvI6igzM#3VCDCXLBvau_R9z?3oPF_p~u%yh=Zv@oqq z8{=jcFbkP>ri1BZ7BSt-5~hz?!Ensg%sS>8W&?90a~rdX*~#3_>|*XoNA$!%a)_1Wl0s5S&LtIO9GOI>lX^0XG!Q3gBu!)?X(t_|oAi*yWC>YE zt|8Zw_2fEoJ-LBwAUBem$jxLk=_mJ*hseWZKY5%SAWxI$$qVG4hvz*?x8>yN|txy_fw5dmnp0`vChS`xJYCeVToReU&}P9%A2N-(}xpKV&~)e`0@T ze_?-RPob;W-$Y16M65_8iV($!lp?JtNu(DUMCqaoky&IB<<3m+>~3#AgrZRlibZiq zjAZrGYH}C4dVRCueMqnB(wo|yKHmU}M+uanWB^H!l(HO-p!E((de!*Sai!(93Ttsi zRf)B*s?=^RuPUpume`7m#*Hs7DlN{>cSsbI##h#RybFC@&L-D*Pg8e?tJ5ExS&4Kg zb30NYHPRq0N2;pM(HSn#?g4nGZRB4G?_LzBx;_% zyR+G|xYpTN;q*@O)wzA{#&*~IP(zj1+2L|XQsKdLZ?ntmY7Q|3W5#(p{a#OdI~Wy* zBxfYI0@>mAnVs%M-L6T^umE?9+vRmg^w7P$$q%OI>=Yf6b4L;ko6S*CR5;#dFD-_x zD=)MbR#sG4%kwMBtp#Oem4#&`1(l_xHityR6A;$t@w7LNSYVVxqU`I-&oLC1F3&Oa z0V()gVlP|1{9xc%ZK$9hCBsgM527Mej7m`HY~e&ZVLxUGA6-5;_;Rn;**gFo%4SWg znI15z!4n#ds!-gt?y7eB+u$(DeLlFdoSlAwZQm4U zuczBTzovddd6#=!yBp*tw<9{Zvkv4&nLE*i$cY+J6KX~-)Ph=38`V)gHPBRQq-ivr zW>Dy~04;>QtcE`i>OzY^53=Yvu&Z|XYoU~Kye`ac56oBVb%C%eL%TQC)9iB809(yY zZ!^EC{4NU|f_Bykcd78brn|8Nde0WV1qMpwFk-x`#o68N4{V08lZK&3)%n7i=tguCss{N9+P*2Crofo_!-hnVAL!BHbaxIv=9Ry**|lVP zOK|LP8!e*Qw3J$?-66@F)dZWA3kN00JFq&*@9Gf9<%V>o#_#QJ@^^b(f_d183I@?_ zXcO8@b7(#-pyESl5N!d@x1w!m`|RPlW(K&RR+>xm{vgc~kziYPp*tLsWZ+-!iXev6EL#L9q^@2Y~Yj z(L?BAv}#W9>}JlG(%^S@xIimAx@a*ip~xX|wt&ix%FD}}=>zG_YjwF6y1Yxf@_Yil z;JcOIR1mv7AB=5x`SJu#^157p9~dQ99^8^m!H3~GF6_yE^teMJA757+JiXw_51=Rb ztvFkgF!CvMz#%dH@jQpOHe3(~(9=A*zuiAvA)W=5xDrt8DzuJ{0y!Q{ksu#0@z=*i zpg}{|$E)a|Ly`qdg#;?hf`)7C06N6;^mn@p%YF^L?vSMYjTr{e8$9*D(=}*qkD#L{ zvmd=h&+SKV)AM-bkRg~1fpN!QS+XF3W9S2(!25J;Kl+fC)27;~psc~xPtfN`Hi$k& zpP>`9f{vr(2hkTGt6$Mdkkw`$FPX!p1B2{$)xcfX*&6sb-VHFq)9D180=6?TysxVr z+#FZ)AD>Tfc{*HvZ?AA(-}C471FhoqSip5ZW5lDYU(m1U6#5PQj!vU9bON17C(+6D zd^&|r-HtJ4Fu^R^iX(6&okpkAS=0flej#(-5K@ z*XHy(;UK&-oSm(%c@y2uuJZQwNj_gUe`Xnf7*sQKYT={O${(_~c#7Hm4LowQ<(K6z zpWSCGv6YtP81ezQ0Z_vkICJi_nvg{F4&V$_HsV^rCTte26*`|b2)95$25>IebexCt zv5n5AbLiYZ*mS{!2W{yHD?9WEj|rI9dH=?|1`X+ItJej9*ypcz``gBOcq_@va7DYP zY2hf4%r;N+C}{WgR>Qt^_(nB)ntMmJxtsvOhn_gQ{cSZazaO-~H)@Dj;C2^oVR+>0 z0x;nk`K;*=6FDTAq5JQAw?9`9)8MJ*)&%5Z9N6+hcmj&W6VWO>89l_iJB?1CYYx17 zUF~oq_qf3NHPT|?45s2~GpE&n)D7UNs7!cPjV}PJJ*{SHx1Wat!v{2otN9}m&Y%YL z5Z6){6$88q;PZSQo|hEEc^C2MJSeNP@H~{c1vlW?cn+RRTWK40(*;}beC)s%Vkccl z7t!T(1#Ox&#nmzdY7@aahVWDfkIfcr7!TMQX1H710-b}?wBZhZ8aG~m7vgr>PCIBP z^=tvZsv36%JSscw;_;(Hl2ixwhhG}_P_D&1R`bnpF0OO72LxOj-Z~`SHBFuXTncLp z4EJ~eG5VUk?k>14K|z#ZT>{j3yCUq`5>&7`WVvu3UJk|Y{a+C4~a{_ z$r{8Pc{fYK1c~lim1aQZQGbACYp&sdL|C(=_b0BZiAchcK8n~=Yu$vOS-^^bTtQb zkN3=Y2YBdaoB{YmIQ<}tf)~n%T%Zlyq@X<(gc|I9WhZZF0MqbJd1ygllT^4`0B46r z2qbwYqh{Px9)@)LLTy9Tf=g90Y9#AtRCIGcqoMsl(G)CMxsRt5?3%*pK_VF)9q4Ba zbdWav(XR+#DJGrCLYV_h2HHcnP#b(;GT_4&+61oM2rF+df_uEUpfF_RnOr76#EOk> zr}e>!3z_23#3gh`NU51o%ou2ZiERDMIdtc6!&s(*Z`ew${ejtoW`L<;CWhviM0X9( zF@>2LW-yp)W;O&JmU=dOy5BKp%wHhj`iG18|jIugCkx!vKMWrg0Ejb9VV$&CtxlB>q|G zlmpO-m!rUKP|+*6-hoSQ=z0m^#i5}ga(q{K#)roQ3H$T(vXRqI@OrwtV8EXaE5B$c zV8(cuuFdqmfazwuj1Mr_&`l2zWe}eDQ5j$Y_!2N$OwUkv2%$2)c=cwwOnAO*#PgMb z&%q;K#axOqw}J*<%&Z0-WI+EOp^t(F-n^B$3@&6na|LrHeGGOsjy_9Y=69E0Urke+ zt7BLXLYkw4wkjuVYcp>?{!$sPWv=6;V?Ev9&sh&*pst}$4Fg%j(LT*pwBZeFfTGMfe!tXzCvH62k9Zu zp2OSV{0;(u)-$i+3*iJ`gX=twehC;3CQISZ5dhWn&i39(5M}~o%cI^QU<&~*Xb+hA zTCWp)Ah4JLM+*d2HNIj($UYAB7eaHq<^^fa=J4Kp z_iTG5#Nq-|5R3}85QY%K5)u7?eoQ~5Cqj-Ii6YSu`}&Z6MDrlBS7>lJ?4{O`T4UhF zc8aIf-N~!cJVzt%ZaLhYJ)VUw2^sR_NCFW9nd9^mnm4Pq4ZuLN!6spYt%`u3_Zjc! zopmpQ{WO7op9}pm$29ZNaDz_}Cj(s0hCgrcx$>1~gnz;Ggw0mMJ3zx%S<%U z#*T!&WHy->Hh4a9(BJ84aEM^20Q7}%YxakYYbLE>)CX?;KUhTG852@aU^tROJ%)g0SZnKlID$L5X8N=lLlK7> z7kI+$?xikoZbwi!ddbC*3nNQOA6Z70lNDqop@bu=$VD8EBd*+cFkd&%8oAGwFz%i(km z=WsZm!-X6!;qWL9pUdG24p#vZ84fLx2l+4(hZ7x=B`yEKL_?UR%?tm=YXy%Cgfun? z>)8G24&D9IsNzQnqOPx@G! z-9D&$aCJ1c_d=e?$KxnR3tvQVUc0lqvk5|$0YEjw)pCviLP~8-%?0_Hfu4bCgNaUG z+c{;W#rC3t{QTkqdw#Lq24xW=y97r!<~yAwc6lQuaG7NDX7B%B#-iz9uJ`jfeZ@A2ZrF;7ik3I@ z*~&_a_>@J^P=7~${>$b3LVkti{KjD`hjaPm2sX$r}yqC*dzH90kO((L(c^`YyG7+0h6F5APr#fkf*M*;*9GKl# zP|A}mwlAO6SH@>qh7a1!E(DOyF5vL_{cJmjrwDkL&q)ey>sf<+>>{=g$#$|{*2ntU zZnlSA%r0Sj*`*ww#^LE4uIBIs9G=198V_rIlxgKyX z06GrO;&20pXLEQCJgIN+JH4$gf6e&wXS;os?e12-Tn)S>;qiD^kGsh=$ye`&ycAqC zbKE`vrS7G?p8{ZMWT#+30UyfLvEzK=}vbN?Pe{+CQ>mQm&6_>&(7mUldR#lF#g4(wH zGAmR97FtWHO3TL;jvF_=vbd^lNold8xUkM$&692r-b!-pK@q#2y$K>q><#P&_C^lR zh zS>lVP!l~7|{p~`AiXFhKx3Yum7IrJUjor>+fQoG#2B8AiraR=NvA463k{M)ov3Ib$ zISfD$#I|{m-NW9+?&YwH!z~dsK^?~mw9o~HnHAko zR~0;VFvF!Wo2Ykl28EP4(OPPg@!Qyhv5LOg1dd%M|D&HL$C6;KDlG8J?ZG|O6 zMYPc|v2pPUP&hfXwL)Db1dq%8PyyB04dEK7SB;~jp{Bd3$>o9+$|0#NMy}MHrQ~)% zkw{r88c?aB2sWC=)=jIa0$>k4A++J~9!}BeV+^UrGT5NXMs=xXnQynK^$nycFdF5kjH_^}15ajg}e_U40`Stj$@>OzO69xz#k zi$Zg(F}Zp9z)gLd+wX!k2Dqx>OM5Hwk%Z6~AZITKvO8e6!1to!@M?x4{$XhuSe6lc z)GX}Yz$nXEpM$eGtp;L@;Dip9`oDV4xwU+yAjK#ONuhW+4GR11kX)^V+S3_O#@`6F zl8cZJ%J^481>jXsg?B5IyKP2;P~Wy4%J=VrqW#Cwv*=YQ)_)&;1f}|)LV3OfCqW^8 zHqON*_*^KzuYuD0S&*T3K-v8Q?7_?MN_;WC2}w=b>__a!^FkQ~zNlsp9vw$zu+RLrpuT*{eho2ZupcMb&)MDVm+V&oE7HT^#b8J{ zyoAHO+t`!rH|)3UckucRhv8o8c~{ro+8s3&dPSkr38J z@t}u7jz$!VSMP)%z;?1rBo;}?Hjzvu7b$r6AHo1e4nss|bs#FRhQpU}crDoXVV_#0 z5qt+IR{bA(EFzsS>m~nJJZDjwz|f`tM?woClfcjA|2HBpBCEj875{Z-`Ygs#WE0tE z1~MrD`=~)i_~}y-D9Cwa9{ez-3w{oB5yT>|hM&Z&habY+Og55D@Y9!f$O-ZbIYoYl zpSNHZu0}SJRkCVU3qNqtu?E)2rn8xBIa>|5c#u5+KQA$g(nMoKm7V8Pjs*7dC`lamqo9L4vG$oUKbq^9TmMR zIwtx+^i>3o5J#LBF(ZPDxGJJQ;;xA2BHoNR5^+4@mxxmlzek*j1ci+hMMg$ON5)3# zA`Owo$n?m}NK>RGGAA-OGC$HDc}`?qWOHO+AEnNj6Y*GF%N-WI(hdT;bA(XT~+AA@5^j3_2DCLty%CM8B6 zlNys3GbUzY%#4`Yn7Wu*F%QQah&dW_Eau0UGqIM~yx7^XzS!>A#j(AyeX$qEu8F-Y zc5Uo+v5&?+8T)1Ik8#Oysc{qHYUAqT8sg^0&5yeqJrBF+$JiOu3{u~nQWE)}0AE*FmzSBfWy zYsGcqS>oB^RWP~0J2DqbdDA*SN1#J7kyiZ_Y-C1%MCi9^yV@kzQRizU61Rgz03 zS4wV>+#%T~d06t8M>;hShY^JPU=8`Ruak9&08)Uc2Zj)`6ZIx}8?Ue13-79-k_KfUx z**miLWM9a>mVG1pUiPExXL+1lBiG84s) zOYW8X<-PJg`EvP6`DOBJ<(uSNITDF0agiTtGe z2l-F(U*xA0QHpqlSRqv?6>5c6k*r8jWGV_2rHWCCF^Y14Q5;r$nYnoT8kjyinPp>{5D_-O9zv zUga9)b;_HRwkg>Qr^9yehw{N3}$? zRJBaCLPb^URoAOFsBTi-qS~n1r0Q1JD{}da=4! zy-Izx`Udr_>aFT+>K*F6>buqVs2@>3s@|`DPW`<4MfDN&N9yD1Pt_;XU#P!Q|Dryn z{#|`WgEd4W(xhrCG}ARRG_{&~O@n5RrbDw-vs|-Mvr2QZ<`T^nAZIm`ftI}$<$y&WORhy>G*A{4tw58fn+A-P* z+FEVBwm~~rJ70UDwp)9J_9pE%?GEkj+B>v&YVXqCt$j@Uxb{iy0qrx|=d>?qU($Y= z6q%HoG$yG&sX3`5$&<7w$(Pifv?7TntxCE$>5`;NlkQG>KIwF_J~=nJBza8oxyfUb zE0X6XFG^mTygYejGM9Wq@{P$iC*PWUTk_`Q!^!U?A5Z=?`9$&;$zLU(O#VIjObSjR zDMcwIDdSVBQYNNMPN_+mnbMfjoYIogma;tM@{}u5u1Z;#@<7THDMwRI>tb~Zol>XP zX?4lE3|*GatjpF}b$PlfU8k;3w?apC7wJ~(*66O&U9Y=AccX5rZinu6-EQ3;-Co_J zy2o_;bx-Jy=#J|?(|xY{N_SHCt?rbb(X;vpeUv^%uhJ*$b$Ww7L!YHL>$COe>L=)H z^$q$t`g!_BeY3tr-=^=;uhd_mzec}af4%-@{YL#}{eb>n{iFI9^snd->0j3$)xV>E zPyfDw7*Y*u4L2Hg8}2gfGyKEwfZ<`oV}>UT2Mo^|UN9Upd|>$4@QLAs;Y-6w!*_-s z4L=)xHT;$;Pt8xAoLZmSncAPaFZJcrPgBnr*tpcV+_=uT-gtxYCgZKfO~wJ^R^txiF5_F)otlS)XP7XhNoVlhULyC7bjnqbb{zYqFUNOvR>B zQ@LrXsn+B)EiiSMx=cP(k7=c8m1(tUjp=gJ6{hP=n@o3@?ls+KdcgFM=@HY@rsqsA znqD@&YC2?k+jQLYo#{8z88c%RnWM~7v%;)0Ys|@JojJ=~WFBjtYOXWSGS4>8HP1J< znirTm%pSAX>^CnruQ6Y1-elfk-etbiyw`k>`4RJe^ONQS=4Z{%n-7`aH-BON#ll!v zON1rL5@V5DlopL8$)d9uEM`lgxrksJCtvNe#cIDieb63tI zIZx$0lktX8~*0-$hSU<9UVm)E~()zXaXX~ll=v-xPO0FR{EjKgQnwy_nkXxKv znp>VbG53PphWuyqU&ue4|3Us|`6uסvZ4#T@rnG5n$u_es$ChWa+lp+Zw$Zk8 zY>l=xw!OBawvTLI+J3N|wqtvYU20d_%j~1=6YUq+YwdORS$3!0Z||}9+Lzf^+E>|E z+b^}RwO?glXWwYwWbe0cDTpYL7bF&_3bX|q3bqt%E7(!6t1zn&s%;8O3r83JqwvYX g1BK5NK3|kwbWTx4(ZnG?m=WGZ1z~P5Dw_QN0GEDeL;wH) delta 4592 zcmZWs34Bvk)<5SaFYo2$Wlu>86k56fr7hjlfzCbRbNN10n;fEK>{n-AP9OwFX#=?&`7ja+ zU=$QW5sZe3FbSqY1$bZv%!Ep)fd-fZ^I#z?gXORSo`ucu9BhHDunnGvo$vy@2rt2Y zco~ksF?bD5z+3PheB^_(@CAGW-@;|M0{=urhALE}fEpB0LM_T@LNnUYfjuxBBQO$s zV=N|MA`Zksn1Pu%81r!?7T_o>#4$JtCu1>|VFk{@C$JIc;zC@4D{(z;KtFE5t+)+e zzyo*$kKr5WJBeT5Is6jO;|2T*FXGqu4StK?;otEp{tK@$H4~VIiA-WzCNmvVn4TG! zk(rp8Sy)#V!n(2UtS3ugi7bgFvlN!foGg83=t4X3hBv6j6`x!3Pt)e)hX(ML$h=I2h{e6tTd-HDJ?B6 zHX$)JJvKQtHz{^-VnPnTOia#6PEJWl$W8Ej)kVHwK4YAxy1b@gbWKfVsjGHq-B?eZ zr?k>tVsbou<|-ZB;Zdh~^WtMdlhYQ&gw9JyOygr`V)}vwpMVTHh=;@`2%^QcFsgFMNxnLo6Q+Hs0p@~m`r>Z zMHMv-`L5ZX=`L?gt>37r9q{n}7_X<&wQiRQwC$dZfpHMk1Y@al z6O5-Wd}V_rI36ZLNi!6~6zWPnD54$gf^x7lLn)L|2z6@)H%z1M6iQ+Kah5P&L3qZz z9T0f6QBwuglkvJt;c1B41y8{$SPg4nEv%zx>O(OUOL5e97p#X!@bk|`c!uJ+G*kH} zjnXNy#AFLlJZF}xy4+np)a$OQ^PdQs-ERuNdtY>gTmU5|V<2SiNkY zO<-w)9hA@n&6LPF&F>UE9CpE;Kzw#nQWNZ@WQr^MfPI1X<-z`aTR9^y{IsWx2u#MAK318KZVk5Ob>2AqMC z7I+^%fWOcH8bp~7{5xEt!IZ`MY3?5GhO2NJqV~eS;2Kb;MI40WjI1ffDBo6tZ7oZ+cT-wd>%EpXdPqna>?3Mq2*2$!e&KC2jvAz*32 z&e#RJQW1@&F)i2)vM`j!ayQ2FeSM_3d>F;+4ECgPWN4oljeXkU(;5bh3jq4k1Tt{x zwN|Y7K*4gR@_Lo(Oj@v@eO?l#LDWu6#uQ9NCrzTsR7_KLVmkK2{`eS`kejAc1x1b@ z?w;ly>v1UeP+7IJ|Y&BWlWd%?t`icNQ-w0Z=PJ0e0H$WZ~lhJK30nxj2NT zl8Z{IY$s+f7ZusqM-{7kTb06U%wgLN`vM8C3Z|mFU6BM+L-*sHRCinia8rjl&*EmPr`dtyHBeI?6>NCM(L} zgdF6c{ZJTy&|JO-2efJO)qo~j_?m5pBff^mOH4hvbNt-ydP}40|vuvqMx1v#}u7iMG-Gvj`SRJ7_n(NC)W1139r?EGDo}Zx+q^P!ly% zOACu-ajY-xq!(xxU+C+YJv~?&d+c|x0c;=}M0;p2?c=Zmv5p=rhYkH5Y#7U9!|5g3 zPcL)W_1LiftdNcU9c&yM&nD18Iz)#lGJMdDRt-WKghnz5{e(>c9V=l|Ul|qGz$)mK z*1)q;R#yDrfX{Y$T`l}pIi!u{tpmThpPFnMtKtVU-(v;yus&=itK>UBsp;j+4o zckoxP7-TBmo5%1zyMUGWcynFG+w19k!!ubGcYh%x-ditW%h(F`6kE-2hg8Q^Z>v63eXcsM`d;;;8q`d!R%_IfT2?D+gE~arT^*(lS4XOQ zs(Y*ZsAJW+>Iv$V>aFVc)fd%Q)z{S5)pynR1Rn}&K_f^)S0Pe}7Gi`rAzm0D3>LD5 zTp>>wA&eA82_-_UP$$e6mI@n$O~OuLukfO((`?gh*BsS+ zDQd-DqEj3yjuj_}lf)_FRIya_ii^Z0;xciixJq0jZV|VN+r)k1e(`{KSUe&g72gt1 zi*JkXiWkLyir2&&;!onw;=d)eBuE-bl7b|M)L9CVx=UeFw3HwvNhy+3N|$n_JZXe9 zQW`Cdm3-r+iBg#~ORAR|q(*6>MABkuiL^#~PTDRtNiEVIX`l3x^s;nHIwPHxu1Hs< zYtjwrrgTfXE!~lRmF{YdTC>)w4bs}R!P+j`5N&sDm^NISsvW5<)_S!*?MCe}?FZVk z+V8cOw3oG4wb!&aWQQCn_mZRKSfAWiPLNaOEP0qbT+WvZH;&k!4L|w9OfNqGc zP&Y%@pd;O4-4fk0-3r}$onN<6w@J5Iw?+4w?sMHQibd(7bX9!als-zF60amFDT-6c zQ${Egm13ntDOJjqX-bXaRc0%5l)1`sWwo+ad0N@1Y*IEWTa=y3A?2uYOgXNcP);dt zDQ_zuD(968%2&$Q%2nmM@}qJ~xvkvMqh6zz^s-*j2kX1(L-jrMJ@viyee|(~LSrv0YlrZ-I|On)|=Hoar|%=De8Zyh>^%@N{=bi_I09qEn?M~LxHad1YUUD36J2V(`+#jrK`)&Vr9QiMztmrTR diff --git a/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcuserdata/geekerzp.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcuserdata/geekerzp.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist new file mode 100644 index 00000000000..e2573a5943c --- /dev/null +++ b/samples/client/petstore/objc/SwaggerClient.xcworkspace/xcuserdata/geekerzp.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist @@ -0,0 +1,17 @@ + + + + + + + + + diff --git a/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m index 5ba0fe18382..388cacbb157 100644 --- a/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m +++ b/samples/client/petstore/objc/SwaggerClient/SwaggerClient/ViewController.m @@ -56,11 +56,14 @@ // } ]; */ - SWGUserApi *api = [[SWGUserApi alloc] init]; - [api loginUserWithCompletionBlock:@"username" password:@"password" completionHandler:^(NSString *output, NSError *error) { - NSLog(@"output => %@", output); - NSLog(@"error => %@", error); - }]; + SWGPetApi *api = [[SWGPetApi alloc] init]; + [api deletePetWithCompletionBlock:@"hello" + petId:@1434529787992 + completionHandler:^(NSError *error) { + if (error) { + NSLog(@"%@", error); + } + }]; } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/StoreApiTest.m similarity index 100% rename from samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/StoreApiTest.m rename to samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/StoreApiTest.m diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/UserApiTest.m b/samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/UserApiTest.m similarity index 100% rename from samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/UserApiTest.m rename to samples/client/petstore/objc/SwaggerClient/SwaggerClientTests/UserApiTest.m diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index 829aec58b96..6ede775cb02 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -1,6 +1,7 @@ #import #import #import "AFHTTPRequestOperationManager.h" +#import "SWGJSONResponseSerializer.h" #import "SWGUser.h" #import "SWGCategory.h" diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index 39ad87c76bb..1b479d039e6 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -500,7 +500,7 @@ static bool loggingEnabled = true; // setting response serializer if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [AFJSONResponseSerializer serializer]; + self.responseSerializer = [SWGJSONResponseSerializer serializer]; } else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; From 8ed690cad0cc2f88d88727caf5dd881c5b4c6640 Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Fri, 12 Jun 2015 15:01:10 -0700 Subject: [PATCH 22/30] Better namespace support, so that your not limited to only having a single vendor space, you can have \Vendor\Package\Model as a namespace. Also updates with proper phpdoc comments so that IDE code hinting can function properly. --- .../codegen/languages/PhpClientCodegen.java | 78 ++++++++++++++----- .../src/main/resources/php/ApiClient.mustache | 16 ++-- .../main/resources/php/ApiException.mustache | 8 +- .../src/main/resources/php/api.mustache | 15 ++-- .../src/main/resources/php/autoload.mustache | 41 ++++++++++ .../src/main/resources/php/composer.mustache | 5 +- .../main/resources/php/configuration.mustache | 31 +++----- .../src/main/resources/php/model.mustache | 18 +++-- .../src/main/resources/php/require.mustache | 13 ---- 9 files changed, 138 insertions(+), 87 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/php/autoload.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/php/require.mustache 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 10c03fe4381..2134bfe75dc 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 @@ -7,6 +7,7 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; +import io.swagger.models.properties.RefProperty; import java.io.File; import java.util.Arrays; @@ -14,24 +15,20 @@ import java.util.HashMap; import java.util.HashSet; public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; + protected String invokerPackage = "Swagger\\Client"; + protected String groupId = "swagger"; protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String artifactVersion = null; public PhpClientCodegen() { super(); - invokerPackage = camelize("SwaggerClient"); - - String packagePath = invokerPackage + "-php"; - - modelPackage = packagePath + "/lib/models"; - apiPackage = packagePath + "/lib"; outputFolder = "generated-code/php"; modelTemplateFiles.put("model.mustache", ".php"); apiTemplateFiles.put("api.mustache", ".php"); templateDir = "php"; + apiPackage = invokerPackage + "\\Api"; + modelPackage = invokerPackage + "\\Model"; reservedWords = new HashSet( Arrays.asList( @@ -39,6 +36,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { ); additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("modelPackage", modelPackage); + additionalProperties.put("apiPackage", apiPackage); + additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\")); additionalProperties.put("groupId", groupId); additionalProperties.put("artifactId", artifactId); additionalProperties.put("artifactVersion", artifactVersion); @@ -46,6 +46,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { // ref: http://php.net/manual/en/language.types.intro.php languageSpecificPrimitives = new HashSet( Arrays.asList( + "bool", "boolean", "int", "integer", @@ -55,7 +56,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { "object", "DateTime", "mixed", - "number") + "number", + "void", + "byte") ); instantiationTypes.put("array", "array"); @@ -69,20 +72,41 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("double", "double"); typeMapping.put("string", "string"); typeMapping.put("byte", "int"); - typeMapping.put("boolean", "boolean"); - typeMapping.put("date", "DateTime"); - typeMapping.put("datetime", "DateTime"); + typeMapping.put("boolean", "bool"); + typeMapping.put("date", "\\DateTime"); + typeMapping.put("datetime", "\\DateTime"); typeMapping.put("file", "string"); typeMapping.put("map", "map"); typeMapping.put("array", "array"); typeMapping.put("list", "array"); typeMapping.put("object", "object"); + typeMapping.put("DateTime", "\\DateTime"); - supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json")); - supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php")); - supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php")); - supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php")); - supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php")); + supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json")); + supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, "lib"), "Configuration.php")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php")); + supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php")); + supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php")); + } + + public String getPackagePath() { + //invokerPackage.replace("\\", "") + return "SwaggerClient-php"; + } + + public String toPackagePath(String packageName, String basePath) { + packageName = packageName.replace(invokerPackage, ""); + if (basePath != null && basePath.length() > 0) { + basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar; + } + + return (getPackagePath() + File.separatorChar + basePath + // Replace period, backslash, forward slash with file separator in package name + + packageName.replaceAll("[\\.\\\\/]", File.separator) + // Trim prefix file separators from package path + .replaceAll("^" + File.separator, "")) + // Trim trailing file separators from the overall path + .replaceAll(File.separator + "$", ""); } public CodegenType getTag() { @@ -104,11 +128,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar); + return (outputFolder + "/" + toPackagePath(apiPackage(), "lib")); } public String modelFileFolder() { - return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar); + return (outputFolder + "/" + toPackagePath(modelPackage(), "lib")); } @Override @@ -116,15 +140,27 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + return getTypeDeclaration(inner) + "[]"; } else if (p instanceof MapProperty) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]"; + } else if (p instanceof RefProperty) { + String type = super.getTypeDeclaration(p); + return (!languageSpecificPrimitives.contains(type)) + ? "\\" + modelPackage + "\\" + type : type; } return super.getTypeDeclaration(p); } + @Override + public String getTypeDeclaration(String name) { + if (!languageSpecificPrimitives.contains(name)) { + return "\\" + modelPackage + "\\" + name; + } + return super.getTypeDeclaration(name); + } + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index b116eee0829..9badb4dbb37 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -24,17 +24,14 @@ class ApiClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; - + + /** @var string[] Array of default headers where the key is the header name and the value is the header value */ private $default_header = array(); - /* - * @var string timeout (second) of the HTTP request, by default set to 0, no timeout - */ + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ protected $curl_timeout = 0; - /* - * @var string user agent of the HTTP request, set to "PHP-Swagger" by default - */ + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ protected $user_agent = "PHP-Swagger"; /** @@ -386,8 +383,8 @@ class ApiClient { $deserialized[$key] = $this->deserialize($value, $subClass); } } - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { $values[] = $this->deserialize($value, $subClass); @@ -399,7 +396,6 @@ class ApiClient { settype($data, $class); $deserialized = $data; } else { - $class = "{{invokerPackage}}\\models\\".$class; $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { $original_property_name = $instance::$attributeMap[$property]; diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index b66c3a51eb7..a835d579d32 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -21,14 +21,10 @@ use \Exception; class ApiException extends Exception { - /** - * The HTTP body of the server response. - */ + /** @var string The HTTP body of the server response. */ protected $response_body; - /** - * The HTTP header of the server response. - */ + /** @var string[] The HTTP header of the server response. */ protected $response_headers; public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 755d0e70452..1946e26bf34 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -20,11 +20,17 @@ * NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. */ -namespace {{invokerPackage}}; +namespace {{apiPackage}}; + +use \{{invokerPackage}}\ApiClient; +use \{{invokerPackage}}\Configuration; {{#operations}} class {{classname}} { + /** + * @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration + */ function __construct($apiClient = null) { if (null === $apiClient) { if (Configuration::$apiClient === null) { @@ -41,14 +47,14 @@ class {{classname}} { private $apiClient; // instance of the ApiClient /** - * get the API client - */ + * @return \{{invokerPackage}}\ApiClient get the API client + */ public function getApiClient() { return $this->apiClient; } /** - * set the API client + * @param \{{invokerPackage}} $apiClient set the API client */ public function setApiClient($apiClient) { $this->apiClient = $apiClient; @@ -123,7 +129,6 @@ class {{classname}} { $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, $headerParams, $authSettings); - {{#returnType}}if(! $response) { return null; } diff --git a/modules/swagger-codegen/src/main/resources/php/autoload.mustache b/modules/swagger-codegen/src/main/resources/php/autoload.mustache new file mode 100644 index 00000000000..4f56a6e20c0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/autoload.mustache @@ -0,0 +1,41 @@ + '{{{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}} ); - - {{#vars}}{{#description}} + {{#vars}} + /** @var {{datatype}} ${{name}} {{#description}}{{{description}}} {{/description}}*/ + public ${{name}}; + {{/vars}} /** - * {{{description}}} - */{{/description}} - public ${{name}}; /* {{{datatype}}} */{{/vars}} - + * @param mixed[] Array of parameters to initialize the object with + */ public function __construct(array $data = null) { - {{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}} + {{#vars}}$this->{{name}} = @$data["{{name}}"];{{#hasMore}} {{/hasMore}}{{/vars}} } diff --git a/modules/swagger-codegen/src/main/resources/php/require.mustache b/modules/swagger-codegen/src/main/resources/php/require.mustache deleted file mode 100644 index 3c02d861ef1..00000000000 --- a/modules/swagger-codegen/src/main/resources/php/require.mustache +++ /dev/null @@ -1,13 +0,0 @@ - From 719a0b732ee0c64e958c53cd93329793854af7d5 Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Fri, 12 Jun 2015 15:01:25 -0700 Subject: [PATCH 23/30] Update sample client --- .../php/SwaggerClient-php/SwaggerClient.php | 13 - .../php/SwaggerClient-php/autoload.php | 41 ++ .../php/SwaggerClient-php/composer.json | 4 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 541 ++++++++++++++++++ .../SwaggerClient-php/lib/Api/StoreApi.php | 296 ++++++++++ .../php/SwaggerClient-php/lib/Api/UserApi.php | 516 +++++++++++++++++ .../php/SwaggerClient-php/lib/ApiClient.php | 18 +- .../SwaggerClient-php/lib/ApiException.php | 10 +- .../SwaggerClient-php/lib/Configuration.php | 33 +- .../lib/{models => Model}/Category.php | 21 +- .../lib/{models => Model}/Order.php | 50 +- .../lib/{models => Model}/Pet.php | 52 +- .../lib/{models => Model}/Tag.php | 21 +- .../lib/{models => Model}/User.php | 58 +- samples/client/petstore/php/test.php | 18 +- 15 files changed, 1551 insertions(+), 141 deletions(-) delete mode 100644 samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/autoload.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php rename samples/client/petstore/php/SwaggerClient-php/lib/{models => Model}/Category.php (76%) rename samples/client/petstore/php/SwaggerClient-php/lib/{models => Model}/Order.php (65%) rename samples/client/petstore/php/SwaggerClient-php/lib/{models => Model}/Pet.php (61%) rename samples/client/petstore/php/SwaggerClient-php/lib/{models => Model}/Tag.php (76%) rename samples/client/petstore/php/SwaggerClient-php/lib/{models => Model}/User.php (64%) diff --git a/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php b/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php deleted file mode 100644 index 3c02d861ef1..00000000000 --- a/samples/client/petstore/php/SwaggerClient-php/SwaggerClient.php +++ /dev/null @@ -1,13 +0,0 @@ - diff --git a/samples/client/petstore/php/SwaggerClient-php/autoload.php b/samples/client/petstore/php/SwaggerClient-php/autoload.php new file mode 100644 index 00000000000..acbd3968b23 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/autoload.php @@ -0,0 +1,41 @@ +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 + + /** + * @return \Swagger\Client\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \Swagger\Client $apiClient set the API client + */ + public function setApiClient($apiClient) { + $this->apiClient = $apiClient; + } + + + /** + * updatePet + * + * Update an existing pet + * + * @param \Swagger\Client\Model\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 \Swagger\Client\Model\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 string[] $status Status values that need to be considered for filter (required) + * @return \Swagger\Client\Model\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,'\Swagger\Client\Model\Pet[]'); + return $responseObject; + } + + /** + * findPetsByTags + * + * Finds Pets by tags + * + * @param string[] $tags Tags to filter by (required) + * @return \Swagger\Client\Model\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,'\Swagger\Client\Model\Pet[]'); + return $responseObject; + } + + /** + * getPetById + * + * Find pet by ID + * + * @param int $pet_id ID of pet that needs to be fetched (required) + * @return \Swagger\Client\Model\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,'\Swagger\Client\Model\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/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php new file mode 100644 index 00000000000..b8b30977b59 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -0,0 +1,296 @@ +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 + + /** + * @return \Swagger\Client\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \Swagger\Client $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 \Swagger\Client\Model\Order $body order placed for purchasing the pet (required) + * @return \Swagger\Client\Model\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,'\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 + */ + 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,'\Swagger\Client\Model\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/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php new file mode 100644 index 00000000000..2e83df74da4 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -0,0 +1,516 @@ +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 + + /** + * @return \Swagger\Client\ApiClient get the API client + */ + public function getApiClient() { + return $this->apiClient; + } + + /** + * @param \Swagger\Client $apiClient set the API client + */ + public function setApiClient($apiClient) { + $this->apiClient = $apiClient; + } + + + /** + * createUser + * + * Create user + * + * @param \Swagger\Client\Model\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 \Swagger\Client\Model\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 \Swagger\Client\Model\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 \Swagger\Client\Model\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,'\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 + */ + 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); + + } + + +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 280fe9bdd71..bb5229fb170 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -15,7 +15,7 @@ * limitations under the License. */ -namespace SwaggerClient; +namespace Swagger\Client; class ApiClient { @@ -24,17 +24,14 @@ class ApiClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; - + + /** @var string[] Array of default headers where the key is the header name and the value is the header value */ private $default_header = array(); - /* - * @var string timeout (second) of the HTTP request, by default set to 0, no timeout - */ + /** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */ protected $curl_timeout = 0; - /* - * @var string user agent of the HTTP request, set to "PHP-Swagger" by default - */ + /** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */ protected $user_agent = "PHP-Swagger"; /** @@ -391,8 +388,8 @@ class ApiClient { $deserialized[$key] = $this->deserialize($value, $subClass); } } - } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { - $subClass = substr($class, 6, -1); + } elseif (strcasecmp(substr($class, -2),'[]') == 0) { + $subClass = substr($class, 0, -2); $values = array(); foreach ($data as $key => $value) { $values[] = $this->deserialize($value, $subClass); @@ -404,7 +401,6 @@ class ApiClient { settype($data, $class); $deserialized = $data; } else { - $class = "SwaggerClient\\models\\".$class; $instance = new $class(); foreach ($instance::$swaggerTypes as $property => $type) { $original_property_name = $instance::$attributeMap[$property]; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 51f2c4b877e..5f3b1812261 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -15,20 +15,16 @@ * limitations under the License. */ -namespace SwaggerClient; +namespace Swagger\Client; use \Exception; class ApiException extends Exception { - /** - * The HTTP body of the server response. - */ + /** @var string The HTTP body of the server response. */ protected $response_body; - /** - * The HTTP header of the server response. - */ + /** @var string[] The HTTP header of the server response. */ protected $response_headers; public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index cd514956a29..e6381781bb0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -15,43 +15,31 @@ * limitations under the License. */ -namespace SwaggerClient; +namespace Swagger\Client; + +use \Swagger\Client\ApiClient; class Configuration { - /** - * Associate array to store API key(s) - */ + /** @var string[] Associate array to store API key(s) */ public static $apiKey = array(); - /** - * Associate array to store API prefix (e.g. Bearer) - */ + /** string[] Associate array to store API prefix (e.g. Bearer) */ public static $apiKeyPrefix = array(); - /** - * Username for HTTP basic authentication - */ + /** @var string Username for HTTP basic authentication */ public static $username = ''; - /** - * Password for HTTP basic authentication - */ + /** @var string Password for HTTP basic authentication */ public static $password = ''; - /** - * The default instance of ApiClient - */ + /** @var \Swagger\Client\ApiClient The default instance of ApiClient */ public static $apiClient; - /** - * Debug switch (default set to false) - */ + /** @var bool Debug switch (default set to false) */ public static $debug = false; - /** - * Debug file location (log to STDOUT by default) - */ + /** @var string Debug file location (log to STDOUT by default) */ public static $debug_file = 'php://output'; /* @@ -63,4 +51,3 @@ class Configuration { } } - diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/models/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php similarity index 76% rename from samples/client/petstore/php/SwaggerClient-php/lib/models/Category.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index c49c711fa8e..750a8fee5df 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/models/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -22,28 +22,35 @@ * */ -namespace SwaggerClient\models; +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' ); - - public $id; /* int */ - public $name; /* string */ - + /** @var int $id */ + public $id; + + /** @var string $name */ + public $name; + + /** + * @param mixed[] Array of parameters to initialize the object with + */ public function __construct(array $data = null) { - $this->id = $data["id"]; - $this->name = $data["name"]; + $this->id = @$data["id"]; + $this->name = @$data["name"]; } public function offsetExists($offset) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/models/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php similarity index 65% rename from samples/client/petstore/php/SwaggerClient-php/lib/models/Order.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index bf8a0178e4c..64552afb763 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/models/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -22,20 +22,22 @@ * */ -namespace SwaggerClient\models; +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', + 'ship_date' => '\DateTime', 'status' => 'string', - 'complete' => 'boolean' + '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', @@ -44,25 +46,35 @@ class Order implements ArrayAccess { 'status' => 'status', 'complete' => 'complete' ); - - public $id; /* int */ - public $pet_id; /* int */ - public $quantity; /* int */ - public $ship_date; /* DateTime */ + /** @var int $id */ + public $id; + + /** @var int $pet_id */ + public $pet_id; + + /** @var int $quantity */ + public $quantity; + + /** @var \DateTime $ship_date */ + public $ship_date; + + /** @var string $status Order Status */ + public $status; + + /** @var bool $complete */ + public $complete; + /** - * Order Status - */ - public $status; /* string */ - public $complete; /* boolean */ - + * @param mixed[] Array of parameters to initialize the object with + */ public function __construct(array $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"]; + $this->id = @$data["id"]; + $this->pet_id = @$data["pet_id"]; + $this->quantity = @$data["quantity"]; + $this->ship_date = @$data["ship_date"]; + $this->status = @$data["status"]; + $this->complete = @$data["complete"]; } public function offsetExists($offset) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/models/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php similarity index 61% rename from samples/client/petstore/php/SwaggerClient-php/lib/models/Pet.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 2009cc373cf..ef2a4c76a0d 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/models/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -22,20 +22,22 @@ * */ -namespace SwaggerClient\models; +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' => 'Category', + 'category' => '\Swagger\Client\Model\Category', 'name' => 'string', - 'photo_urls' => 'array[string]', - 'tags' => 'array[Tag]', + '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', @@ -44,25 +46,35 @@ class Pet implements ArrayAccess { 'tags' => 'tags', 'status' => 'status' ); - - public $id; /* int */ - public $category; /* Category */ - public $name; /* string */ - public $photo_urls; /* array[string] */ - public $tags; /* array[Tag] */ + /** @var int $id */ + public $id; + + /** @var \Swagger\Client\Model\Category $category */ + public $category; + + /** @var string $name */ + public $name; + + /** @var string[] $photo_urls */ + public $photo_urls; + + /** @var \Swagger\Client\Model\Tag[] $tags */ + public $tags; + + /** @var string $status pet status in the store */ + public $status; + /** - * pet status in the store - */ - public $status; /* string */ - + * @param mixed[] Array of parameters to initialize the object with + */ public function __construct(array $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"]; + $this->id = @$data["id"]; + $this->category = @$data["category"]; + $this->name = @$data["name"]; + $this->photo_urls = @$data["photo_urls"]; + $this->tags = @$data["tags"]; + $this->status = @$data["status"]; } public function offsetExists($offset) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/models/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php similarity index 76% rename from samples/client/petstore/php/SwaggerClient-php/lib/models/Tag.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index 37729c68d9e..5959cb20a6a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/models/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -22,28 +22,35 @@ * */ -namespace SwaggerClient\models; +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' ); - - public $id; /* int */ - public $name; /* string */ - + /** @var int $id */ + public $id; + + /** @var string $name */ + public $name; + + /** + * @param mixed[] Array of parameters to initialize the object with + */ public function __construct(array $data = null) { - $this->id = $data["id"]; - $this->name = $data["name"]; + $this->id = @$data["id"]; + $this->name = @$data["name"]; } public function offsetExists($offset) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/models/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php similarity index 64% rename from samples/client/petstore/php/SwaggerClient-php/lib/models/User.php rename to samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 0ec53c409e6..1bfb7f332db 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/models/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -22,11 +22,12 @@ * */ -namespace SwaggerClient\models; +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', @@ -38,6 +39,7 @@ 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 */ static $attributeMap = array( 'id' => 'id', 'username' => 'username', @@ -48,29 +50,43 @@ class User implements ArrayAccess { 'phone' => 'phone', 'user_status' => 'userStatus' ); - - public $id; /* int */ - public $username; /* string */ - public $first_name; /* string */ - public $last_name; /* string */ - public $email; /* string */ - public $password; /* string */ - public $phone; /* string */ + /** @var int $id */ + public $id; + + /** @var string $username */ + public $username; + + /** @var string $first_name */ + public $first_name; + + /** @var string $last_name */ + public $last_name; + + /** @var string $email */ + public $email; + + /** @var string $password */ + public $password; + + /** @var string $phone */ + public $phone; + + /** @var int $user_status User Status */ + public $user_status; + /** - * User Status - */ - public $user_status; /* int */ - + * @param mixed[] Array of parameters to initialize the object with + */ public function __construct(array $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"]; + $this->id = @$data["id"]; + $this->username = @$data["username"]; + $this->first_name = @$data["first_name"]; + $this->last_name = @$data["last_name"]; + $this->email = @$data["email"]; + $this->password = @$data["password"]; + $this->phone = @$data["phone"]; + $this->user_status = @$data["user_status"]; } public function offsetExists($offset) { diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 0c52f0fdb8a..f5383a9a4dc 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -1,6 +1,5 @@ getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); // return Pet (model) @@ -28,34 +27,31 @@ try { // add pet (post json) $new_pet_id = 10005; - $new_pet = new SwaggerClient\models\Pet; + $new_pet = new Swagger\Client\Model\Pet; $new_pet->id = $new_pet_id; $new_pet->name = "PHP Unit Test"; // new tag - $tag= new SwaggerClient\models\Tag; + $tag= new Swagger\Client\Model\Tag; $tag->id = $new_pet_id; // use the same id as pet //$tag->name = "test php tag"; // new category - $category = new SwaggerClient\models\Category; + $category = new Swagger\Client\Model\Category; $category->id = 0; // use the same id as pet //$category->name = "test php category"; $new_pet->tags = array($tag); $new_pet->category = $category; - $pet_api = new SwaggerClient\PetAPI(); + $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); -} catch (Exception $e) { +} catch (Swagger\Client\Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; echo 'HTTP response headers: ', $e->getResponseHeaders(), "\n"; echo 'HTTP response body: ', $e->getResponseBody(), "\n"; echo 'HTTP status code: ', $e->getCode(), "\n"; } - - -?> From 5119299e8ac2b40be22441c5e7d1a0c5e05650e3 Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Fri, 12 Jun 2015 15:45:36 -0700 Subject: [PATCH 24/30] Remove unused code --- .../main/java/io/swagger/codegen/languages/PhpClientCodegen.java | 1 - 1 file changed, 1 deletion(-) 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 2134bfe75dc..0690163f137 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 @@ -90,7 +90,6 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { } public String getPackagePath() { - //invokerPackage.replace("\\", "") return "SwaggerClient-php"; } From 69c2f6f945e55450cfd5c9ce209364ed245f218e Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Fri, 12 Jun 2015 16:05:45 -0700 Subject: [PATCH 25/30] Add phpdoc for the api.apiClient --- modules/swagger-codegen/src/main/resources/php/api.mustache | 3 ++- 1 file changed, 2 insertions(+), 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 1946e26bf34..05f6944e720 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -44,7 +44,8 @@ class {{classname}} { } } - private $apiClient; // instance of the ApiClient + /** @var \{{invokerPackage}}\ApiClient instance of the ApiClient + private $apiClient; /** * @return \{{invokerPackage}}\ApiClient get the API client From eed45a41a391be9a87482bead63bc7b90e3c5b0f Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Fri, 12 Jun 2015 16:21:37 -0700 Subject: [PATCH 26/30] Fixed the missing closing doc chars and updated sample --- .../swagger-codegen/src/main/resources/php/api.mustache | 6 +++--- .../petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 7 ++++--- .../petstore/php/SwaggerClient-php/lib/Api/StoreApi.php | 7 ++++--- .../petstore/php/SwaggerClient-php/lib/Api/UserApi.php | 7 ++++--- 4 files changed, 15 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 05f6944e720..3ed7f18c579 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -44,12 +44,12 @@ class {{classname}} { } } - /** @var \{{invokerPackage}}\ApiClient instance of the ApiClient + /** @var \{{invokerPackage}}\ApiClient instance of the ApiClient */ private $apiClient; /** - * @return \{{invokerPackage}}\ApiClient get the API client - */ + * @return \{{invokerPackage}}\ApiClient get the API client + */ public function getApiClient() { return $this->apiClient; } 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 01ecd6771e4..f4f6ea8538a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -43,11 +43,12 @@ class PetApi { } } - private $apiClient; // instance of the ApiClient + /** @var \Swagger\Client\ApiClient instance of the ApiClient */ + private $apiClient; /** - * @return \Swagger\Client\ApiClient get the API client - */ + * @return \Swagger\Client\ApiClient get the API client + */ public function getApiClient() { return $this->apiClient; } 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 b8b30977b59..07a922aab0a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -43,11 +43,12 @@ class StoreApi { } } - private $apiClient; // instance of the ApiClient + /** @var \Swagger\Client\ApiClient instance of the ApiClient */ + private $apiClient; /** - * @return \Swagger\Client\ApiClient get the API client - */ + * @return \Swagger\Client\ApiClient get the API client + */ public function getApiClient() { return $this->apiClient; } 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 2e83df74da4..f4d35a3a7a0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -43,11 +43,12 @@ class UserApi { } } - private $apiClient; // instance of the ApiClient + /** @var \Swagger\Client\ApiClient instance of the ApiClient */ + private $apiClient; /** - * @return \Swagger\Client\ApiClient get the API client - */ + * @return \Swagger\Client\ApiClient get the API client + */ public function getApiClient() { return $this->apiClient; } From 2ac7384abf841f63a6170916256baa68ab9696d4 Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Fri, 12 Jun 2015 16:49:17 -0700 Subject: [PATCH 27/30] Fix tests --- .../src/test/scala/php/PhpModelTest.scala | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala index ade8a09e80d..ffb9c8683db 100644 --- a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala @@ -51,16 +51,16 @@ class PhpModelTest extends FlatSpec with Matchers { vars.get(1).isNotContainer should equal(true) vars.get(2).baseName should be("createdAt") - vars.get(2).complexType should be(null) - vars.get(2).datatype should be("DateTime") + vars.get(2).complexType should be("\\DateTime") + vars.get(2).datatype should be("\\DateTime") vars.get(2).name should be("created_at") vars.get(2).defaultValue should be("null") - vars.get(2).baseType should be("DateTime") + vars.get(2).baseType should be("\\DateTime") vars.get(2).hasMore should equal(null) vars.get(2).required should equal(null) vars.get(2).isNotContainer should equal(true) - cm.imports.size() should be(0) + cm.imports.size() should be(1) } it should "convert a model with list property" in { @@ -91,7 +91,7 @@ class PhpModelTest extends FlatSpec with Matchers { vars.get(0).isNotContainer should equal(true) vars.get(1).baseName should be("urls") - vars.get(1).datatype should be("array[string]") + vars.get(1).datatype should be("string[]") vars.get(1).name should be("urls") vars.get(1).baseType should be("array") vars.get(1).hasMore should be(null) @@ -142,7 +142,7 @@ class PhpModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") - vars.get(0).datatype should be("Children") + vars.get(0).datatype should be("\\Swagger\\Client\\Model\\Children") vars.get(0).name should be("children") vars.get(0).baseType should be("Children") vars.get(0).required should equal(null) @@ -166,7 +166,7 @@ class PhpModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") vars.get(0).complexType should be("Children") - vars.get(0).datatype should be("array[Children]") + vars.get(0).datatype should be("\\Swagger\\Client\\Model\\Children[]") vars.get(0).name should be("children") vars.get(0).baseType should be("array") vars.get(0).containerType should be("array") @@ -192,7 +192,7 @@ class PhpModelTest extends FlatSpec with Matchers { val vars = cm.vars vars.get(0).baseName should be("children") vars.get(0).complexType should be("Children") - vars.get(0).datatype should be("map[string,Children]") + vars.get(0).datatype should be("map[string,\\Swagger\\Client\\Model\\Children]") vars.get(0).name should be("children") vars.get(0).baseType should be("map") vars.get(0).containerType should be("map") From b74050dd7bc3d4ff73fe2bd77406953559e0a993 Mon Sep 17 00:00:00 2001 From: Branden Cash Date: Sat, 13 Jun 2015 09:40:32 -0700 Subject: [PATCH 28/30] Change to use the autoload.php and change the namespacing --- .../SwaggerClient-php/tests/PetApiTest.php | 66 +++++++++---------- 1 file changed, 33 insertions(+), 33 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 5131fb7649c..131a79dba92 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -1,6 +1,6 @@ id = $new_pet_id; $new_pet->name = "PHP Unit Test"; // new tag - $tag= new SwaggerClient\models\Tag; + $tag= new Swagger\Client\Model\Tag; $tag->id = $new_pet_id; // use the same id as pet $tag->name = "test php tag"; // new category - $category = new SwaggerClient\models\Category; + $category = new Swagger\Client\Model\Category; $category->id = $new_pet_id; // use the same id as pet $category->name = "test php category"; $new_pet->tags = array($tag); $new_pet->category = $category; - $pet_api = new SwaggerClient\PetAPI(); + $pet_api = new Swagger\Client\Api\PetAPI(); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); } @@ -45,7 +45,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testApiClient() { // test selectHeaderAccept - $api_client = new SwaggerClient\ApiClient(); + $api_client = new Swagger\Client\ApiClient(); $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); @@ -67,22 +67,22 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $defaultHeader = $api_client->getDefaultHeader(); $this->assertFalse(isset($defaultHeader['test2'])); - $pet_api = new SwaggerClient\PetAPI(); - $pet_api2 = new SwaggerClient\PetAPI(); - $apiClient3 = new SwaggerClient\ApiClient(); + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api2 = new Swagger\Client\Api\PetAPI(); + $apiClient3 = new Swagger\Client\ApiClient(); $apiClient3->setUserAgent = 'api client 3'; - $apiClient4 = new SwaggerClient\ApiClient(); + $apiClient4 = new Swagger\Client\ApiClient(); $apiClient4->setUserAgent = 'api client 4'; - $pet_api3 = new SwaggerClient\PetAPI($apiClient3); + $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); // same default api client $this->assertSame($pet_api->getApiClient(), $pet_api2->getApiClient()); // confirm using the default api client in the Configuration - $this->assertSame($pet_api->getApiClient(), SwaggerClient\Configuration::$apiClient); + $this->assertSame($pet_api->getApiClient(), Swagger\Client\Configuration::$apiClient); // 2 different api clients are not the same $this->assertNotEquals($apiClient3, $apiClient4); // customized pet api not using the default (configuration) api client - $this->assertNotEquals($pet_api3->getApiClient(), SwaggerClient\Configuration::$apiClient); + $this->assertNotEquals($pet_api3->getApiClient(), Swagger\Client\Configuration::$apiClient); // customied pet api not using the old pet api's api client $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); @@ -96,10 +96,10 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetPetById() { // initialize the API client without host - $api_client = new SwaggerClient\ApiClient(); - SwaggerClient\Configuration::$apiKey['api_key'] = '111222333444555'; + $api_client = new Swagger\Client\ApiClient(); + Swagger\Client\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new SwaggerClient\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); // return Pet (model) $response = $pet_api->getPetById($pet_id); $this->assertSame($response->id, $pet_id); @@ -114,12 +114,12 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testFindPetByStatus() { // initialize the API client - $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); - $pet_api = new SwaggerClient\PetAPI($api_client); + $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); // return Pet (model) $response = $pet_api->findPetsByStatus("available"); $this->assertGreaterThan(0, count($response)); // at least one object returned - $this->assertSame(get_class($response[0]), "SwaggerClient\models\Pet"); // verify the object is Pet + $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet // loop through result to ensure status is "available" foreach ($response as $_pet) { $this->assertSame($_pet['status'], "available"); @@ -133,11 +133,11 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePet() { // initialize the API client - $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new SwaggerClient\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); // create updated pet object - $updated_pet = new SwaggerClient\models\Pet; + $updated_pet = new Swagger\Client\Model\Pet; $updated_pet->id = $pet_id; $updated_pet->name = 'updatePet'; // new name $updated_pet->status = 'pending'; // new status @@ -156,9 +156,9 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUpdatePetWithForm() { // initialize the API client - $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new SwaggerClient\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); // update Pet (form) $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) @@ -173,12 +173,12 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testAddPet() { // initialize the API client - $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); $new_pet_id = 10001; - $new_pet = new SwaggerClient\models\Pet; + $new_pet = new Swagger\Client\Model\Pet; $new_pet->id = $new_pet_id; $new_pet->name = "PHP Unit Test"; - $pet_api = new SwaggerClient\PetAPI($api_client); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); // add a new pet (model) $add_response = $pet_api->addPet($new_pet); // return nothing (void) @@ -193,8 +193,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testUploadFile() { // initialize the API client - $api_client = new SwaggerClient\ApiClient('http://petstore.swagger.io/v2'); - $pet_api = new SwaggerClient\PetAPI($api_client); + $api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); // upload file $pet_id = 10001; $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); @@ -206,8 +206,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase public function testGetInventory() { // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); - $store_api = new SwaggerClient\StoreAPI($api_client); + $api_client = new Swagger\Client\APIClient('http://petstore.swagger.io/v2'); + $store_api = new Swagger\Client\Api\StoreAPI($api_client); // get inventory $get_response = $store_api->getInventory(); From a664abcf51e1e47bbd7e1d534867490fd264562e Mon Sep 17 00:00:00 2001 From: Gareth Evans Date: Mon, 22 Jun 2015 19:17:29 +0100 Subject: [PATCH 29/30] Contributed maven plugin to the swagger-codegen project --- .gitignore | 1 + .../swagger-codegen-maven-plugin/README.md | 41 ++++++ modules/swagger-codegen-maven-plugin/pom.xml | 87 +++++++++++++ .../codegen/plugin/AdditionalParams.java | 16 +++ .../swagger/codegen/plugin/CodeGenMojo.java | 118 ++++++++++++++++++ pom.xml | 1 + 6 files changed, 264 insertions(+) create mode 100644 modules/swagger-codegen-maven-plugin/README.md create mode 100644 modules/swagger-codegen-maven-plugin/pom.xml create mode 100644 modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java create mode 100644 modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java diff --git a/.gitignore b/.gitignore index 24bb9709fc3..a0e39ffd165 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ version.properties lib/* build/* generated-files/* +generated-sources/* generated-code/* *.swp *.swo diff --git a/modules/swagger-codegen-maven-plugin/README.md b/modules/swagger-codegen-maven-plugin/README.md new file mode 100644 index 00000000000..a7eaf852a22 --- /dev/null +++ b/modules/swagger-codegen-maven-plugin/README.md @@ -0,0 +1,41 @@ +swagger-codegen-maven-plugin +============================ + +A Maven plugin to support the [swagger](http://swagger.io) code generation project + +Usage +============================ + +Add to your `build->plugins` section (default phase is `generate-sources` phase) +```xml + + io.swagger + swagger-codegen-maven-plugin + ${project.version} + + + + generate + + + src/main/resources/api.yaml + java + + + + +``` + +Followed by: + +``` +mvn clean compile +``` + +### Configuration parameters + +- `inputSpec` - swagger spec file path +- `language` - target generation language +- `output` - target output path (default is `${project.build.directory}/generated-sources/swagger`) +- `templateDirectory` - directory with mustache templates +- `addCompileSourceRoot` - add the output directory to the project as a source root (`true` by default) diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml new file mode 100644 index 00000000000..7ad4496872c --- /dev/null +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -0,0 +1,87 @@ + + + 4.0.0 + + + io.swagger + swagger-codegen-project + 2.1.3-SNAPSHOT + ../.. + + swagger-codegen-maven-plugin + swagger-codegen (maven-plugin) + maven-plugin + maven plugin to build modules from swagger codegen + + UTF-8 + + + + org.apache.maven + maven-core + 3.2.5 + + + org.apache.maven + maven-artifact + 3.2.5 + provided + + + org.apache.maven + maven-compat + 3.2.5 + + + org.apache.maven + maven-plugin-api + 3.2.5 + + + org.apache.maven.plugin-tools + maven-plugin-annotations + 3.4 + + + io.swagger + swagger-codegen + ${project.version} + + + junit + junit + 4.12 + test + + + + + + + org.apache.maven.plugins + maven-plugin-plugin + 3.4 + + true + + + + mojo-descriptor + process-classes + + descriptor + + + + help-goal + + helpmojo + + + + + + + + diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java new file mode 100644 index 00000000000..aa137cbf6c3 --- /dev/null +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/AdditionalParams.java @@ -0,0 +1,16 @@ +package io.swagger.codegen.plugin; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 14:47 + */ +public final class AdditionalParams { + public static final String TEMPLATE_DIR_PARAM = "templateDir"; + + private AdditionalParams() { + + } + + +} diff --git a/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java new file mode 100644 index 00000000000..26b6fef1135 --- /dev/null +++ b/modules/swagger-codegen-maven-plugin/src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java @@ -0,0 +1,118 @@ +package io.swagger.codegen.plugin; + +/* + * Copyright 2001-2005 The Apache Software Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import io.swagger.codegen.ClientOptInput; +import io.swagger.codegen.ClientOpts; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.DefaultGenerator; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; + +import java.io.File; +import java.util.ServiceLoader; + +import static io.swagger.codegen.plugin.AdditionalParams.TEMPLATE_DIR_PARAM; + +/** + * Goal which generates client/server code from a swagger json/yaml definition. + */ +@Mojo(name = "generate", defaultPhase = LifecyclePhase.GENERATE_SOURCES) +public class CodeGenMojo extends AbstractMojo { + + /** + * Location of the output directory. + */ + @Parameter(name = "output", + property = "swagger.codegen.maven.plugin.output", + defaultValue = "${project.build.directory}/generated-sources/swagger") + private File output; + + /** + * Location of the swagger spec, as URL or file. + */ + @Parameter(name = "inputSpec", required = true) + private String inputSpec; + + /** + * Folder containing the template files. + */ + @Parameter(name = "templateDirectory") + private File templateDirectory; + + /** + * Client language to generate. + */ + @Parameter(name = "language", required = true) + private String language; + + + /** + * Add the output directory to the project as a source root, so that the + * generated java types are compiled and included in the project artifact. + */ + @Parameter(defaultValue = "true") + private boolean addCompileSourceRoot = true; + + /** + * The project being built. + */ + @Parameter(readonly = true, required = true, defaultValue = "${project}") + private MavenProject project; + + @Override + public void execute() throws MojoExecutionException { + Swagger swagger = new SwaggerParser().read(inputSpec); + + CodegenConfig config = forName(language); + config.setOutputDir(output.getAbsolutePath()); + + if (null != templateDirectory) { + config.additionalProperties().put(TEMPLATE_DIR_PARAM, templateDirectory.getAbsolutePath()); + } + + ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger); + input.setConfig(config); + new DefaultGenerator().opts(input).generate(); + + if (addCompileSourceRoot) { + project.addCompileSourceRoot(output.toString()); + } + } + + private CodegenConfig forName(String name) { + ServiceLoader loader = ServiceLoader.load(CodegenConfig.class); + for (CodegenConfig config : loader) { + if (config.getName().equals(name)) { + return config; + } + } + + // else try to load directly + try { + return (CodegenConfig) Class.forName(name).newInstance(); + } catch (Exception e) { + throw new RuntimeException("Can't load config class with name ".concat(name), e); + } + } +} diff --git a/pom.xml b/pom.xml index ca707056230..10bd7340167 100644 --- a/pom.xml +++ b/pom.xml @@ -397,6 +397,7 @@ modules/swagger-codegen modules/swagger-codegen-cli + modules/swagger-codegen-maven-plugin modules/swagger-generator From 02c41ac574a4cbd853b83862296abfe477c0c319 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 22 Jun 2015 20:00:28 -0700 Subject: [PATCH 30/30] fix for #900, invalid param name for java client --- .../codegen/languages/JavaClientCodegen.java | 4 +++ .../src/test/scala/Java/JavaModelTest.scala | 30 +++++++++++++++++++ 2 files changed, 34 insertions(+) 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 fcec455e9b3..effcddc6834 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 @@ -144,6 +144,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { // replace - with _ e.g. created-at => created_at name = name.replaceAll("-", "_"); + if("_".equals(name)) { + name = "_u"; + } + // if it's all uppper case, do nothing if (name.matches("^[A-Z_]*$")) { return name; diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala index fc819f1f195..0df82fce377 100644 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala +++ b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala @@ -3,6 +3,7 @@ package Java import io.swagger.codegen.languages.JavaClientCodegen import io.swagger.models._ import io.swagger.models.properties._ +import io.swagger.util.Json import org.junit.runner.RunWith import org.scalatest.{FlatSpec, Matchers} import org.scalatest.junit.JUnitRunner @@ -344,3 +345,32 @@ class JavaModelTest extends FlatSpec with Matchers { cm.classname should be("WithDots") } } + + +@RunWith(classOf[JUnitRunner]) +class JavaModelTest2 extends FlatSpec with Matchers { + it should "translate an invalid param name" in { + val model = new ModelImpl() + .description("a model with a 2nd char upper-case property names") + .property("_", new StringProperty()) + + val codegen = new JavaClientCodegen() + val cm = codegen.fromModel("sample", model) + + cm.name should be("sample") + cm.classname should be("Sample") + cm.vars.size should be(1) + + val vars = cm.vars + Json.prettyPrint(vars.get(0)) + vars.get(0).baseName should be("_") + vars.get(0).getter should be("getU") + vars.get(0).setter should be("setU") + vars.get(0).datatype should be("String") + vars.get(0).name should be("u") + vars.get(0).defaultValue should be("null") + vars.get(0).baseType should be("String") + vars.get(0).hasMore should equal(null) + vars.get(0).isNotContainer should equal(true) + } +}