From 3de42afed344720463f73821a60f8970b6644b4b Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 15 Jul 2015 15:24:31 +0800 Subject: [PATCH 001/219] Implement API client structure for Ruby client --- .../codegen/languages/RubyClientCodegen.java | 20 ++++++------- .../src/main/resources/ruby/api.mustache | 30 +++++++++++-------- .../{swagger_client.mustache => gem.mustache} | 0 ...ient.gemspec.mustache => gemspec.mustache} | 0 4 files changed, 27 insertions(+), 23 deletions(-) rename modules/swagger-codegen/src/main/resources/ruby/{swagger_client.mustache => gem.mustache} (100%) rename modules/swagger-codegen/src/main/resources/ruby/{swagger_client.gemspec.mustache => gemspec.mustache} (100%) 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 716c1bb08708..352307220a61 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 @@ -105,17 +105,15 @@ public void processOpts() { setModelPackage("models"); setApiPackage("api"); - supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); - supportingFiles.add(new SupportingFile("swagger_client.mustache", libFolder, gemName + ".rb")); - String baseFolder = libFolder + File.separator + gemName; - supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); - String swaggerFolder = baseFolder + File.separator + "swagger"; - supportingFiles.add(new SupportingFile("swagger" + File.separator + "request.mustache", swaggerFolder, "request.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "response.mustache", swaggerFolder, "response.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "api_error.mustache", swaggerFolder, "api_error.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "version.mustache", swaggerFolder, "version.rb")); - supportingFiles.add(new SupportingFile("swagger" + File.separator + "configuration.mustache", swaggerFolder, "configuration.rb")); - String modelFolder = baseFolder + File.separator + modelPackage.replace("/", File.separator); + supportingFiles.add(new SupportingFile("gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("gem.mustache", libFolder, gemName + ".rb")); + String gemFolder = libFolder + File.separator + gemName; + supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); + supportingFiles.add(new SupportingFile("request.mustache", gemFolder, "request.rb")); + supportingFiles.add(new SupportingFile("response.mustache", gemFolder, "response.rb")); + supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); + supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); + String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 612292b78fff..bc62a1140501 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -3,6 +3,12 @@ require "uri" module {{moduleName}} {{#operations}} class {{classname}} + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + {{#operation}} {{newline}} # {{summary}} @@ -11,9 +17,9 @@ module {{moduleName}} {{/required}}{{/allParams}} # @param [Hash] opts the optional parameters {{#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 = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + if @client.debugging + @client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -39,11 +45,11 @@ module {{moduleName}} # HTTP header 'Accept' (if needed) _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} @@ -54,18 +60,18 @@ module {{moduleName}} # http body (model) {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}}{{#bodyParam}}post_body = Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) {{/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 + {{#returnType}}response = Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('{{{returnType}}}') - if Swagger.configuration.debug - Swagger.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + if @client.debugging + @client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end - result{{/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 - if Swagger.configuration.debug - Swagger.logger.debug "API called: {{classname}}#{{nickname}}" + result{{/returnType}}{{^returnType}}Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @client.debugging + @client.logger.debug "API called: {{classname}}#{{nickname}}" end nil{{/returnType}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache rename to modules/swagger-codegen/src/main/resources/ruby/gem.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache rename to modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache From 4ecc757bea277a464efe8e8830256c86821d6acf Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 21 Jul 2015 17:07:41 +0800 Subject: [PATCH 002/219] More on API client structure for Ruby client --- .../main/resources/ruby/api_client.mustache | 77 +++++++ .../src/main/resources/ruby/gem.mustache | 16 +- .../src/main/resources/ruby/gemspec.mustache | 4 +- .../src/main/resources/ruby/request.mustache | 208 +++++++++++++++++ .../src/main/resources/ruby/swagger.mustache | 76 ------- .../resources/ruby/swagger/request.mustache | 214 ------------------ .../resources/ruby/swagger/version.mustache | 5 - .../src/main/resources/ruby/version.mustache | 3 + 8 files changed, 296 insertions(+), 307 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/api_client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/request.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/version.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache new file mode 100644 index 000000000000..8e295047dd9c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -0,0 +1,77 @@ +require 'logger' +require 'json' + +module {{moduleName}} + class ApiClient + attr_accessor :logger + + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration + + attr_accessor :resources + + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key['api_key'] = '1234567890abcdef' # api key authentication + # config.username = 'wordlover' # http basic authentication + # config.password = 'i<3words' # http basic authentication + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? + + self.logger = configuration.logger + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + !Swagger.configuration.auth_token.nil? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? + raise ApiError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] + end + + def last_response + Thread.current[:swagger_last_response] + end + + def last_response=(response) + Thread.current[:swagger_last_response] = response + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index a43c8a9f6ea4..41f151590d98 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -1,10 +1,9 @@ -# Swagger common files -require '{{gemName}}/swagger' -require '{{gemName}}/swagger/configuration' -require '{{gemName}}/swagger/api_error' -require '{{gemName}}/swagger/request' -require '{{gemName}}/swagger/response' -require '{{gemName}}/swagger/version' +# Common files +require '{{gemName}}/api_client' +require '{{gemName}}/api_error' +require '{{gemName}}/request' +require '{{gemName}}/response' +require '{{gemName}}/version' # Models require '{{gemName}}/{{modelPackage}}/base_object' @@ -20,7 +19,4 @@ require '{{importPath}}' {{/apiInfo}} module {{moduleName}} - # Initialize the default configuration - Swagger.configuration = Swagger::Configuration.new - Swagger.configure { |config| } end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 38d70c07dd57..5c9c1c1a497e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "{{gemName}}/swagger/version" +require "{{gemName}}/version" Gem::Specification.new do |s| s.name = "{{gemName}}" - s.version = {{moduleName}}::Swagger::VERSION + s.version = {{moduleName}}::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] diff --git a/modules/swagger-codegen/src/main/resources/ruby/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/request.mustache new file mode 100644 index 000000000000..c3de5843483b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/request.mustache @@ -0,0 +1,208 @@ +require 'uri' +require 'typhoeus' + +module {{moduleName}} + class Request + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(api_client, http_method, path, attributes = {}) + @api_client = api_client + + @http_method = http_method.to_sym.downcase + @path = path + + attributes.each { |name, value| send "#{name}=", value } + + @format ||= @api_client.format + @params ||= {} + + # Apply default headers + @headers = @api_client.default_headers.merge(@headers || {}) + {{#hasAuthMethods}} + update_params_for_auth! + {{/hasAuthMethods}} + end + + {{#hasAuthMethods}} + # Update hearder and query params based on authentication settings. + def update_params_for_auth! + (@auth_names || []).each do |auth_name| + case auth_name + {{#authMethods}}when '{{name}}' + {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} + @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} + @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} + http_auth_header = 'Basic ' + ["#{@api_client.username}:#{@api_client.password}"].pack('m').delete("\r\n") + @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} + {{/authMethods}} + end + end + end + {{/hasAuthMethods}} + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_client.api_key_prefix[param_name] + "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" + else + @api_client.api_key[param_name] + end + end + + # Construct the request URL. + def url(options = {}) + _path = self.interpreted_path + _path = "/#{_path}" unless _path.start_with?('/') + "#{@api_client.scheme}://#{@api_client.host}#{_path}" + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if @api_client.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if @api_client.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if headers['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + elsif @body # http body is JSON + data = @body.is_a?(String) ? @body : @body.to_json + else + data = nil + end + + if @api_client.debugging + @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" + end + + data + end + + def make + request_options = { + :method => self.http_method, + :headers => self.headers, + :params => self.params, + :ssl_verifypeer => @api_client.verify_ssl, + :cainfo => @api_client.ssl_ca_cert, + :verbose => @api_client.debugging + } + + if [:post, :patch, :put, :delete].include?(self.http_method) + request_options.update :body => self.outgoing_body + end + + raw = Typhoeus::Request.new(self.url, request_options).run + @response = Response.new(raw) + + if @api_client.debugging + @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" + end + + # record as last response + @api_client.last_response = @response + + unless @response.success? + fail ApiError.new(:code => @response.code, + :response_headers => @response.headers, + :response_body => @response.body), + @response.status_message + end + + @response + end + + def response_code_pretty + return unless @response + @response.code.to_s + end + + def response_headers_pretty + return unless @response + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache deleted file mode 100644 index 9be82e015cd4..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ /dev/null @@ -1,76 +0,0 @@ -module {{moduleName}} - module Swagger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - self.logger = configuration.logger - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - !Swagger.configuration.auth_token.nil? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? - raise ApiError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - def last_response - Thread.current[:swagger_last_response] - end - - def last_response=(response) - Thread.current[:swagger_last_response] = response - end - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache deleted file mode 100644 index dd39449e1f31..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ /dev/null @@ -1,214 +0,0 @@ -require 'uri' -require 'typhoeus' - -module {{moduleName}} - module Swagger - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(http_method, path, attributes = {}) - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= Swagger.configuration.format - @params ||= {} - - # Apply default headers - @headers = Swagger.configuration.default_headers.merge(@headers || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - @headers.merge!({:auth_token => Swagger.configuration.auth_token}) - end - {{#hasAuthMethods}} - update_params_for_auth! - {{/hasAuthMethods}} - end - - {{#hasAuthMethods}} - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} - @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} - @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} - http_auth_header = 'Basic ' + ["#{Swagger.configuration.username}:#{Swagger.configuration.password}"].pack('m').delete("\r\n") - @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} - end - end - end - {{/hasAuthMethods}} - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if Swagger.configuration.api_key_prefix[param_name] - "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" - else - Swagger.configuration.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => Swagger.configuration.verify_ssl, - :cainfo => Swagger.configuration.ssl_ca_cert, - :verbose => Swagger.configuration.debug - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(raw) - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - Swagger.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache deleted file mode 100644 index 5e93268298dc..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ /dev/null @@ -1,5 +0,0 @@ -module {{moduleName}} - module Swagger - VERSION = "{{gemVersion}}" - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/version.mustache new file mode 100644 index 000000000000..67cfc8ea3251 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/version.mustache @@ -0,0 +1,3 @@ +module {{moduleName}} + VERSION = "{{gemVersion}}" +end From 948cdb3a75b6146d62c5af925013746724df222d Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 22 Jul 2015 15:37:29 +0800 Subject: [PATCH 003/219] Done with API client structure for Ruby client --- .../src/main/resources/ruby/api.mustache | 16 +- .../main/resources/ruby/api_client.mustache | 159 ++++++++++++------ .../main/resources/ruby/api_error.mustache | 24 +++ .../src/main/resources/ruby/request.mustache | 2 +- .../src/main/resources/ruby/response.mustache | 155 +++++++++++++++++ .../resources/ruby/swagger/api_error.mustache | 26 --- .../ruby/swagger/configuration.mustache | 101 ----------- .../resources/ruby/swagger/response.mustache | 156 ----------------- 8 files changed, 296 insertions(+), 343 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/api_error.mustache create mode 100644 modules/swagger-codegen/src/main/resources/ruby/response.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index bc62a1140501..e1005a901595 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -18,8 +18,8 @@ module {{moduleName}} {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if @client.debugging - @client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + if @api_client.debugging + @api_client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -64,14 +64,14 @@ module {{moduleName}} {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + {{#returnType}}response = Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('{{{returnType}}}') - if @client.debugging - @client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end - result{{/returnType}}{{^returnType}}Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if @client.debugging - @client.logger.debug "API called: {{classname}}#{{nickname}}" + result{{/returnType}}{{^returnType}}Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: {{classname}}#{{nickname}}" end nil{{/returnType}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 8e295047dd9c..e8fc5b9440a2 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -3,75 +3,132 @@ require 'json' module {{moduleName}} class ApiClient - attr_accessor :logger + attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username - attr_accessor :resources + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password - # Call this method to modify defaults in your initializers. + # Defines API keys used with API Key authentications. # - # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' - # end + # @return [Hash] key: parameter name, value: parameter value (API key) # - def configure - yield(configuration) if block_given? + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key - self.logger = configuration.logger - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert - def authenticated? - !Swagger.configuration.auth_token.nil? - end + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging - def de_authenticate - Swagger.configuration.auth_token = nil - end + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger - def authenticate - return if Swagger.authenticated? + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path - if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? - raise ApiError, "Username and password are required to authenticate." - end + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) + # Stores the HTTP response from the last API call using this API client. + attr_accessor :last_response - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] + # The constructor accepts a optional block to configure the API client. + # + # @example + # {{moduleName}}::ApiClient.new do |client| + # client.api_key['api_key'] = 'your key' # api key authentication + # client.username = 'your username' # username for http basic authentication + # client.password = 'your password' # password for http basic authentication + # client.format = 'json' # optional, defaults to 'json' + # end + def initialize(&block) + @format = 'json' + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @user_agent = "ruby-swagger-#{VERSION}" + @inject_format = false + @force_ending_format = false + + @default_headers = { + 'Content-Type' => "application/#{@format.downcase}", + 'User-Agent' => @user_agent + } + + # keys for API key authentication (param-name => api-key) + @api_key = {} + @api_key_prefix = {} + + @verify_ssl = true + + @debugging = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + configure(&block) end - def last_response - Thread.current[:swagger_last_response] + # Call this method to modify defaults in your initializers. + def configure + yield(self) if block_given? + + # remove :// from scheme + @scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + @host.sub!(/https?:\/\//, '') + @host = @host.split('/').first + + # Add leading and trailing slashes to base_path + @base_path = "/#{@base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" end - def last_response=(response) - Thread.current[:swagger_last_response] = response + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache new file mode 100644 index 000000000000..f8b598dad717 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/api_error.mustache @@ -0,0 +1,24 @@ +module {{moduleName}} + 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 diff --git a/modules/swagger-codegen/src/main/resources/ruby/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/request.mustache index c3de5843483b..6a7d2ac448e5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/request.mustache @@ -124,7 +124,7 @@ module {{moduleName}} end raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(raw) + @response = Response.new(@api_client, raw) if @api_client.debugging @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" diff --git a/modules/swagger-codegen/src/main/resources/ruby/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/response.mustache new file mode 100644 index 000000000000..d3119437232f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/response.mustache @@ -0,0 +1,155 @@ +require 'json' +require 'date' +require 'tempfile' + +module {{moduleName}} + class Response + attr_accessor :raw + + def initialize(api_client, raw) + @api_client = api_client + @raw = raw + end + + def code + raw.code + end + + def status_message + raw.status_message + end + + def body + raw.body + end + + def success? + raw.success? + end + + # 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.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file if return_type == 'File' + + # ensuring a default content type + content_type = raw.headers['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)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'BOOLEAN' + data == true + when 'DateTime' + # parse date time (expecting ISO 8601 format) + DateTime.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + {{moduleName}}.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file + tmp_file = Tempfile.new '', @api_client.temp_folder_path + content_disposition = raw.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(raw.body) } + @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body + if format == 'json' + JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') + else + body + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache deleted file mode 100644 index 552161238a0c..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/api_error.mustache +++ /dev/null @@ -1,26 +0,0 @@ -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/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache deleted file mode 100644 index 1279a454e71d..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ /dev/null @@ -1,101 +0,0 @@ -require 'logger' - -module {{moduleName}} - module Swagger - class Configuration - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format - - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debug - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path - - # Defines the headers to be used in HTTP requests of all API calls by default. - # - # @return [Hash] - attr_accessor :default_headers - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - - @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", - 'User-Agent' => @user_agent - } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debug = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - 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 deleted file mode 100644 index 5f55fd686900..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ /dev/null @@ -1,156 +0,0 @@ -module {{moduleName}} - module Swagger - class Response - require 'json' - require 'date' - require 'tempfile' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # 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.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['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)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - when 'String' - data.to_s - when 'Integer' - data.to_i - when 'Float' - data.to_f - when 'BOOLEAN' - data == true - when 'DateTime' - # parse date time (expecting ISO 8601 format) - DateTime.parse data - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - {{moduleName}}.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end - end -end From 609d915541ac99dd52330e13e04f3347b2811bf8 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 22 Jul 2015 15:39:48 +0800 Subject: [PATCH 004/219] Rebuild Ruby petstore sample --- samples/client/petstore/ruby/README.md | 21 +- samples/client/petstore/ruby/lib/petstore.rb | 16 +- .../petstore/ruby/lib/petstore/api/pet_api.rb | 138 ++++++------ .../ruby/lib/petstore/api/store_api.rb | 72 +++--- .../ruby/lib/petstore/api/user_api.rb | 142 ++++++------ .../petstore/ruby/lib/petstore/api_client.rb | 134 +++++++++++ .../petstore/ruby/lib/petstore/api_error.rb | 24 ++ .../petstore/ruby/lib/petstore/request.rb | 207 +++++++++++++++++ .../petstore/ruby/lib/petstore/response.rb | 155 +++++++++++++ .../petstore/ruby/lib/petstore/swagger.rb | 76 ------- .../ruby/lib/petstore/swagger/api_error.rb | 26 --- .../lib/petstore/swagger/configuration.rb | 101 --------- .../ruby/lib/petstore/swagger/request.rb | 213 ------------------ .../ruby/lib/petstore/swagger/response.rb | 156 ------------- .../ruby/lib/petstore/swagger/version.rb | 5 - .../petstore/ruby/lib/petstore/version.rb | 3 + samples/client/petstore/ruby/petstore.gemspec | 4 +- 17 files changed, 725 insertions(+), 768 deletions(-) create mode 100644 samples/client/petstore/ruby/lib/petstore/api_client.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/api_error.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/request.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/response.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/request.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/response.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/swagger/version.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/version.rb diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index c98d79e5a89b..b251d14faf7f 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -37,23 +37,20 @@ You can also use the client directly like this: ruby -Ilib script.rb ``` -## Configuration +## Getting Started ```ruby require 'petstore' -Petstore::Swagger.configure do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - # enable debugging (default is false) - config.debug = true +api_client = Petstore::ApiClient.new do |client| + client.api_key['api_key'] = 'special-key' + client.host = 'petstore.swagger.io' + client.base_path = '/v2' + # enable debugging (default is disabled) + client.debugging = true end -``` -## Getting Started - -```ruby -pet = Petstore::PetApi.get_pet_by_id(5) +pet_api = Petstore::PetApi.new(api_client) +pet = pet_api.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index a3f555c17651..f77710df1eab 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -1,10 +1,9 @@ -# Swagger common files -require 'petstore/swagger' -require 'petstore/swagger/configuration' -require 'petstore/swagger/api_error' -require 'petstore/swagger/request' -require 'petstore/swagger/response' -require 'petstore/swagger/version' +# Common files +require 'petstore/api_client' +require 'petstore/api_error' +require 'petstore/request' +require 'petstore/response' +require 'petstore/version' # Models require 'petstore/models/base_object' @@ -20,7 +19,4 @@ require 'petstore/api/store_api' module Petstore - # Initialize the default configuration - Swagger.configuration = Swagger::Configuration.new - Swagger.configure { |config| } end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 51c3cec7fdeb..b50b56e63437 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -2,15 +2,21 @@ module Petstore class PetApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Update an existing pet # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] - def self.update_pet(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#update_pet ..." + def update_pet(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#update_pet ..." end # resource path @@ -24,23 +30,23 @@ def self.update_pet(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#update_pet" + Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#update_pet" end nil end @@ -50,9 +56,9 @@ def self.update_pet(opts = {}) # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] - def self.add_pet(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#add_pet ..." + def add_pet(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -66,23 +72,23 @@ def self.add_pet(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#add_pet" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#add_pet" end nil end @@ -92,9 +98,9 @@ def self.add_pet(opts = {}) # @param [Hash] opts the optional parameters # @option opts [Array] :status Status values that need to be considered for filter # @return [Array] - def self.find_pets_by_status(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#find_pets_by_status ..." + def find_pets_by_status(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -109,11 +115,11 @@ def self.find_pets_by_status(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -123,10 +129,10 @@ def self.find_pets_by_status(opts = {}) 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Array') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end result end @@ -136,9 +142,9 @@ def self.find_pets_by_status(opts = {}) # @param [Hash] opts the optional parameters # @option opts [Array] :tags Tags to filter by # @return [Array] - def self.find_pets_by_tags(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#find_pets_by_tags ..." + def find_pets_by_tags(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -153,11 +159,11 @@ def self.find_pets_by_tags(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -167,10 +173,10 @@ def self.find_pets_by_tags(opts = {}) 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Array') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end result end @@ -180,9 +186,9 @@ def self.find_pets_by_tags(opts = {}) # @param pet_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters # @return [Pet] - def self.get_pet_by_id(pet_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#get_pet_by_id ..." + def get_pet_by_id(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -199,11 +205,11 @@ def self.get_pet_by_id(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -213,10 +219,10 @@ def self.get_pet_by_id(pet_id, opts = {}) 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 = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Pet') - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end result end @@ -228,9 +234,9 @@ def self.get_pet_by_id(pet_id, opts = {}) # @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 = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#update_pet_with_form ..." + def update_pet_with_form(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -247,11 +253,11 @@ def self.update_pet_with_form(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -263,9 +269,9 @@ def self.update_pet_with_form(pet_id, opts = {}) auth_names = ['petstore_auth'] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#update_pet_with_form" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#update_pet_with_form" end nil end @@ -276,9 +282,9 @@ def self.update_pet_with_form(pet_id, opts = {}) # @param [Hash] opts the optional parameters # @option opts [String] :api_key # @return [nil] - def self.delete_pet(pet_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#delete_pet ..." + def delete_pet(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#delete_pet ..." end # verify the required parameter 'pet_id' is set @@ -295,11 +301,11 @@ def self.delete_pet(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] # form parameters @@ -310,9 +316,9 @@ def self.delete_pet(pet_id, opts = {}) auth_names = ['petstore_auth'] - Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#delete_pet" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#delete_pet" end nil end @@ -324,9 +330,9 @@ def self.delete_pet(pet_id, opts = {}) # @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 = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: PetApi#upload_file ..." + def upload_file(pet_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -343,11 +349,11 @@ def self.upload_file(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['multipart/form-data'] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -359,9 +365,9 @@ def self.upload_file(pet_id, opts = {}) auth_names = ['petstore_auth'] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: PetApi#upload_file" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: PetApi#upload_file" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 78328f4b8329..3462cd8f7de3 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -2,14 +2,20 @@ module Petstore class StoreApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters # @return [Hash] - def self.get_inventory(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#get_inventory ..." + def get_inventory(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#get_inventory ..." end # resource path @@ -23,11 +29,11 @@ def self.get_inventory(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -37,10 +43,10 @@ def self.get_inventory(opts = {}) 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Hash') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end result end @@ -50,9 +56,9 @@ def self.get_inventory(opts = {}) # @param [Hash] opts the optional parameters # @option opts [Order] :body order placed for purchasing the pet # @return [Order] - def self.place_order(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#place_order ..." + def place_order(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#place_order ..." end # resource path @@ -66,24 +72,24 @@ def self.place_order(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) 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 + response = Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Order') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end result end @@ -93,9 +99,9 @@ def self.place_order(opts = {}) # @param order_id ID of pet that needs to be fetched # @param [Hash] opts the optional parameters # @return [Order] - def self.get_order_by_id(order_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#get_order_by_id ..." + def get_order_by_id(order_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#get_order_by_id ..." end # verify the required parameter 'order_id' is set @@ -112,11 +118,11 @@ def self.get_order_by_id(order_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -126,10 +132,10 @@ def self.get_order_by_id(order_id, opts = {}) 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('Order') - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end result end @@ -139,9 +145,9 @@ def self.get_order_by_id(order_id, opts = {}) # @param order_id ID of the order that needs to be deleted # @param [Hash] opts the optional parameters # @return [nil] - def self.delete_order(order_id, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: StoreApi#delete_order ..." + def delete_order(order_id, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -158,11 +164,11 @@ def self.delete_order(order_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -172,9 +178,9 @@ def self.delete_order(order_id, opts = {}) auth_names = [] - Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: StoreApi#delete_order" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: StoreApi#delete_order" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 532a9ffa5bf6..5664f735f01e 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -2,15 +2,21 @@ module Petstore class UserApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.new) + @api_client = api_client + end + # Create user # This can only be done by the logged in user. # @param [Hash] opts the optional parameters # @option opts [User] :body Created user object # @return [nil] - def self.create_user(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#create_user ..." + def create_user(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -24,23 +30,23 @@ def self.create_user(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#create_user" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_user" end nil end @@ -50,9 +56,9 @@ def self.create_user(opts = {}) # @param [Hash] opts the optional parameters # @option opts [Array] :body List of user object # @return [nil] - def self.create_users_with_array_input(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#create_users_with_array_input ..." + def create_users_with_array_input(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -66,23 +72,23 @@ def self.create_users_with_array_input(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#create_users_with_array_input" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_users_with_array_input" end nil end @@ -92,9 +98,9 @@ def self.create_users_with_array_input(opts = {}) # @param [Hash] opts the optional parameters # @option opts [Array] :body List of user object # @return [nil] - def self.create_users_with_list_input(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#create_users_with_list_input ..." + def create_users_with_list_input(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -108,23 +114,23 @@ def self.create_users_with_list_input(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#create_users_with_list_input" + Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#create_users_with_list_input" end nil end @@ -135,9 +141,9 @@ def self.create_users_with_list_input(opts = {}) # @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 = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#login_user ..." + def login_user(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -153,11 +159,11 @@ def self.login_user(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -167,10 +173,10 @@ def self.login_user(opts = {}) 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('String') - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end result end @@ -179,9 +185,9 @@ def self.login_user(opts = {}) # # @param [Hash] opts the optional parameters # @return [nil] - def self.logout_user(opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#logout_user ..." + def logout_user(opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -195,11 +201,11 @@ def self.logout_user(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -209,9 +215,9 @@ def self.logout_user(opts = {}) auth_names = [] - Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#logout_user" + Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#logout_user" end nil end @@ -221,9 +227,9 @@ def self.logout_user(opts = {}) # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] - def self.get_user_by_name(username, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#get_user_by_name ..." + def get_user_by_name(username, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#get_user_by_name ..." end # verify the required parameter 'username' is set @@ -240,11 +246,11 @@ def self.get_user_by_name(username, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -254,10 +260,10 @@ def self.get_user_by_name(username, opts = {}) 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 + response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make result = response.deserialize('User') - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end result end @@ -268,9 +274,9 @@ def self.get_user_by_name(username, opts = {}) # @param [Hash] opts the optional parameters # @option opts [User] :body Updated user object # @return [nil] - def self.update_user(username, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#update_user ..." + def update_user(username, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -287,23 +293,23 @@ def self.update_user(username, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) + post_body = Request.object_to_http_body(opts[:'body']) auth_names = [] - Swagger::Request.new(:PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#update_user" + Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#update_user" end nil end @@ -313,9 +319,9 @@ def self.update_user(username, opts = {}) # @param username The name that needs to be deleted # @param [Hash] opts the optional parameters # @return [nil] - def self.delete_user(username, opts = {}) - if Swagger.configuration.debug - Swagger.logger.debug "Calling API: UserApi#delete_user ..." + def delete_user(username, opts = {}) + if @api_client.debugging + @api_client.logger.debug "Calling API: UserApi#delete_user ..." end # verify the required parameter 'username' is set @@ -332,11 +338,11 @@ def self.delete_user(username, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -346,9 +352,9 @@ def self.delete_user(username, opts = {}) auth_names = [] - Swagger::Request.new(:DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - if Swagger.configuration.debug - Swagger.logger.debug "API called: UserApi#delete_user" + Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + if @api_client.debugging + @api_client.logger.debug "API called: UserApi#delete_user" end nil end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb new file mode 100644 index 000000000000..569003fa133c --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -0,0 +1,134 @@ +require 'logger' +require 'json' + +module Petstore + class ApiClient + attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Stores the HTTP response from the last API call using this API client. + attr_accessor :last_response + + # The constructor accepts a optional block to configure the API client. + # + # @example + # Petstore::ApiClient.new do |client| + # client.api_key['api_key'] = 'your key' # api key authentication + # client.username = 'your username' # username for http basic authentication + # client.password = 'your password' # password for http basic authentication + # client.format = 'json' # optional, defaults to 'json' + # end + def initialize(&block) + @format = 'json' + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @user_agent = "ruby-swagger-#{VERSION}" + @inject_format = false + @force_ending_format = false + + @default_headers = { + 'Content-Type' => "application/#{@format.downcase}", + 'User-Agent' => @user_agent + } + + # keys for API key authentication (param-name => api-key) + @api_key = {} + @api_key_prefix = {} + + @verify_ssl = true + + @debugging = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + configure(&block) + end + + # Call this method to modify defaults in your initializers. + def configure + yield(self) if block_given? + + # remove :// from scheme + @scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + @host.sub!(/https?:\/\//, '') + @host = @host.split('/').first + + # Add leading and trailing slashes to base_path + @base_path = "/#{@base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb new file mode 100644 index 000000000000..e1b6b3acfd6e --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -0,0 +1,24 @@ +module Petstore + 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 diff --git a/samples/client/petstore/ruby/lib/petstore/request.rb b/samples/client/petstore/ruby/lib/petstore/request.rb new file mode 100644 index 000000000000..af884537ff83 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/request.rb @@ -0,0 +1,207 @@ +require 'uri' +require 'typhoeus' + +module Petstore + class Request + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(api_client, http_method, path, attributes = {}) + @api_client = api_client + + @http_method = http_method.to_sym.downcase + @path = path + + attributes.each { |name, value| send "#{name}=", value } + + @format ||= @api_client.format + @params ||= {} + + # Apply default headers + @headers = @api_client.default_headers.merge(@headers || {}) + + update_params_for_auth! + + end + + + # Update hearder and query params based on authentication settings. + def update_params_for_auth! + (@auth_names || []).each do |auth_name| + case auth_name + when 'api_key' + @headers ||= {} + @headers['api_key'] = get_api_key_with_prefix('api_key') + when 'petstore_auth' + # TODO: support oauth + + end + end + end + + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_client.api_key_prefix[param_name] + "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" + else + @api_client.api_key[param_name] + end + end + + # Construct the request URL. + def url(options = {}) + _path = self.interpreted_path + _path = "/#{_path}" unless _path.start_with?('/') + "#{@api_client.scheme}://#{@api_client.host}#{_path}" + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if @api_client.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if @api_client.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if headers['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + elsif @body # http body is JSON + data = @body.is_a?(String) ? @body : @body.to_json + else + data = nil + end + + if @api_client.debugging + @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" + end + + data + end + + def make + request_options = { + :method => self.http_method, + :headers => self.headers, + :params => self.params, + :ssl_verifypeer => @api_client.verify_ssl, + :cainfo => @api_client.ssl_ca_cert, + :verbose => @api_client.debugging + } + + if [:post, :patch, :put, :delete].include?(self.http_method) + request_options.update :body => self.outgoing_body + end + + raw = Typhoeus::Request.new(self.url, request_options).run + @response = Response.new(@api_client, raw) + + if @api_client.debugging + @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" + end + + # record as last response + @api_client.last_response = @response + + unless @response.success? + fail ApiError.new(:code => @response.code, + :response_headers => @response.headers, + :response_body => @response.body), + @response.status_message + end + + @response + end + + def response_code_pretty + return unless @response + @response.code.to_s + end + + def response_headers_pretty + return unless @response + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/response.rb b/samples/client/petstore/ruby/lib/petstore/response.rb new file mode 100644 index 000000000000..e54e13ac9515 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/response.rb @@ -0,0 +1,155 @@ +require 'json' +require 'date' +require 'tempfile' + +module Petstore + class Response + attr_accessor :raw + + def initialize(api_client, raw) + @api_client = api_client + @raw = raw + end + + def code + raw.code + end + + def status_message + raw.status_message + end + + def body + raw.body + end + + def success? + raw.success? + end + + # 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.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file if return_type == 'File' + + # ensuring a default content type + content_type = raw.headers['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)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'BOOLEAN' + data == true + when 'DateTime' + # parse date time (expecting ISO 8601 format) + DateTime.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + Petstore.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file + tmp_file = Tempfile.new '', @api_client.temp_folder_path + content_disposition = raw.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(raw.body) } + @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body + if format == 'json' + JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') + else + body + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger.rb b/samples/client/petstore/ruby/lib/petstore/swagger.rb deleted file mode 100644 index 4f1433d3286a..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger.rb +++ /dev/null @@ -1,76 +0,0 @@ -module Petstore - module Swagger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key['api_key'] = '1234567890abcdef' # api key authentication - # config.username = 'wordlover' # http basic authentication - # config.password = 'i<3words' # http basic authentication - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - self.logger = configuration.logger - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - !Swagger.configuration.auth_token.nil? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.nil? || Swagger.configuration.password.nil? - raise ApiError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - def last_response - Thread.current[:swagger_last_response] - end - - def last_response=(response) - Thread.current[:swagger_last_response] = response - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb b/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb deleted file mode 100644 index 9eab46b6eec7..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/api_error.rb +++ /dev/null @@ -1,26 +0,0 @@ -module Petstore - 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/petstore/swagger/configuration.rb b/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb deleted file mode 100644 index d7cc3d734e0d..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/configuration.rb +++ /dev/null @@ -1,101 +0,0 @@ -require 'logger' - -module Petstore - module Swagger - class Configuration - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format - - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debug - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path - - # Defines the headers to be used in HTTP requests of all API calls by default. - # - # @return [Hash] - attr_accessor :default_headers - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - - @default_headers = { - 'Content-Type' => "application/#{@format.downcase}", - 'User-Agent' => @user_agent - } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debug = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb deleted file mode 100644 index ecb8cff56435..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb +++ /dev/null @@ -1,213 +0,0 @@ -require 'uri' -require 'typhoeus' - -module Petstore - module Swagger - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(http_method, path, attributes = {}) - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= Swagger.configuration.format - @params ||= {} - - # Apply default headers - @headers = Swagger.configuration.default_headers.merge(@headers || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - @headers.merge!({:auth_token => Swagger.configuration.auth_token}) - end - - update_params_for_auth! - - end - - - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - when 'api_key' - @headers ||= {} - @headers['api_key'] = get_api_key_with_prefix('api_key') - when 'petstore_auth' - # TODO: support oauth - - end - end - end - - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if Swagger.configuration.api_key_prefix[param_name] - "#{Swagger.configuration.api_key_prefix[param_name]} #{Swagger.configuration.api_key[param_name]}" - else - Swagger.configuration.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{Swagger.configuration.scheme}://#{Swagger.configuration.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => Swagger.configuration.verify_ssl, - :cainfo => Swagger.configuration.ssl_ca_cert, - :verbose => Swagger.configuration.debug - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(raw) - - if Swagger.configuration.debug - Swagger.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - Swagger.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/response.rb b/samples/client/petstore/ruby/lib/petstore/swagger/response.rb deleted file mode 100644 index 2ab9be1a5b9e..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/response.rb +++ /dev/null @@ -1,156 +0,0 @@ -module Petstore - module Swagger - class Response - require 'json' - require 'date' - require 'tempfile' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # 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.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['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)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - when 'String' - data.to_s - when 'Integer' - data.to_i - when 'Float' - data.to_f - when 'BOOLEAN' - data == true - when 'DateTime' - # parse date time (expecting ISO 8601 format) - DateTime.parse data - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - Petstore.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', Swagger.configuration.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - Swagger.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/version.rb b/samples/client/petstore/ruby/lib/petstore/swagger/version.rb deleted file mode 100644 index ff3c48bb59e6..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/swagger/version.rb +++ /dev/null @@ -1,5 +0,0 @@ -module Petstore - module Swagger - VERSION = "1.0.0" - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb new file mode 100644 index 000000000000..fed78553ed33 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -0,0 +1,3 @@ +module Petstore + VERSION = "1.0.0" +end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 40a169d1741a..6e41479fe466 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "petstore/swagger/version" +require "petstore/version" Gem::Specification.new do |s| s.name = "petstore" - s.version = Petstore::Swagger::VERSION + s.version = Petstore::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] From a75b05b952f76a575a23ef4af2bcbaa70c1d682c Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 30 Jun 2015 14:32:55 +0800 Subject: [PATCH 005/219] Update tests with latest code --- .../petstore/ruby/spec/api_client_spec.rb | 53 ++++++++++++++++++ samples/client/petstore/ruby/spec/pet_spec.rb | 24 ++++---- .../client/petstore/ruby/spec/request_spec.rb | 18 +++--- .../petstore/ruby/spec/response_spec.rb | 11 +--- .../client/petstore/ruby/spec/spec_helper.rb | 22 +++----- .../client/petstore/ruby/spec/store_spec.rb | 8 +-- .../client/petstore/ruby/spec/swagger_spec.rb | 56 ------------------- 7 files changed, 90 insertions(+), 102 deletions(-) create mode 100644 samples/client/petstore/ruby/spec/api_client_spec.rb delete mode 100644 samples/client/petstore/ruby/spec/swagger_spec.rb diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb new file mode 100644 index 000000000000..f66dcdd68fdb --- /dev/null +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -0,0 +1,53 @@ +# require 'spec_helper' +require File.dirname(__FILE__) + '/spec_helper' + +describe Petstore::ApiClient do + + context 'initialization' do + + context 'URL stuff' do + + context 'host' do + it 'removes http from host' do + c = Petstore::ApiClient.new + c.configure {|c| c.host = 'http://example.com' } + c.host.should == 'example.com' + end + + it 'removes https from host' do + c = Petstore::ApiClient.new {|c| c.host = 'https://wookiee.com' } + c.host.should == 'wookiee.com' + end + + it 'removes trailing path from host' do + c = Petstore::ApiClient.new + c.configure {|c| c.host = 'hobo.com/v4' } + c.host.should == 'hobo.com' + end + end + + context 'base_path' do + it "prepends a slash to base_path" do + c = Petstore::ApiClient.new + c.configure {|c| c.base_path = 'v4/dog' } + c.base_path.should == '/v4/dog' + end + + it "doesn't prepend a slash if one is already there" do + c = Petstore::ApiClient.new + c.configure {|c| c.base_path = '/v4/dog' } + c.base_path.should == '/v4/dog' + end + + it "ends up as a blank string if nil" do + c = Petstore::ApiClient.new + c.configure {|c| c.base_path = nil } + c.base_path.should == '' + end + end + + end + + end + +end diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 8c33c3a9cde8..c288ec2192ea 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -3,8 +3,8 @@ describe "Pet" do before do - configure_swagger - prepare_pet + @pet_api = Petstore::PetApi.new(API_CLIENT) + prepare_pet @pet_api end describe "pet methods" do @@ -42,7 +42,7 @@ end it "should fetch a pet object" do - pet = Petstore::PetApi.get_pet_by_id(10002) + pet = @pet_api.get_pet_by_id(10002) pet.should be_a(Petstore::Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" @@ -52,9 +52,9 @@ it "should not find a pet that does not exist" do begin - Petstore::PetApi.get_pet_by_id(-10002) + @pet_api.get_pet_by_id(-10002) fail 'it should raise error' - rescue Petstore::Swagger::ApiError => e + rescue Petstore::ApiError => e e.code.should == 404 e.message.should == 'Not Found' e.response_body.should == '{"code":1,"type":"error","message":"Pet not found"}' @@ -64,7 +64,7 @@ end it "should find pets by status" do - pets = Petstore::PetApi.find_pets_by_status(:status => 'available') + pets = @pet_api.find_pets_by_status(:status => 'available') pets.length.should >= 3 pets.each do |pet| pet.should be_a(Petstore::Pet) @@ -73,12 +73,12 @@ end it "should not find a pet with invalid status" do - pets = Petstore::PetApi.find_pets_by_status(:status => 'invalid-status') + pets = @pet_api.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 end it "should find a pet by status" do - pets = Petstore::PetApi.find_pets_by_status(:status => "available,sold") + pets = @pet_api.find_pets_by_status(:status => "available,sold") pets.each do |pet| if pet.status != 'available' && pet.status != 'sold' raise "pet status wasn't right" @@ -88,20 +88,20 @@ it "should update a pet" do pet = Petstore::Pet.new({'id' => 10002, 'status' => 'sold'}) - Petstore::PetApi.add_pet(:body => pet) + @pet_api.add_pet(:body => pet) - fetched = Petstore::PetApi.get_pet_by_id(10002) + fetched = @pet_api.get_pet_by_id(10002) fetched.id.should == 10002 fetched.status.should == 'sold' end it "should create a pet" do pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - result = Petstore::PetApi.add_pet(:body => pet) + result = @pet_api.add_pet(:body => pet) # nothing is returned result.should be_nil - pet = Petstore::PetApi.get_pet_by_id(10002) + pet = @pet_api.get_pet_by_id(10002) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb index 8eeac549f93f..b4bf64c8f39b 100644 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' -describe Petstore::Swagger::Request do +describe Petstore::Request do before(:each) do - Petstore::Swagger.configure do |config| + @api_client = Petstore::ApiClient.new do |config| inject_format = true config.api_key['api_key'] = 'special-key' config.host = 'petstore.swagger.io' @@ -15,7 +15,7 @@ @default_params = { :params => {:foo => "1", :bar => "2"} } - @request = Petstore::Swagger::Request.new(@default_http_method, @default_path, @default_params) + @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, @default_params) end describe "initialization" do @@ -29,7 +29,7 @@ end it "allows params to be nil" do - @request = Petstore::Swagger::Request.new(@default_http_method, @default_path, :params => nil) + @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, :params => nil) @request.params.should == {} end @@ -60,7 +60,7 @@ describe "path" do it "accounts for a total absence of format in the path string" do - @request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -69,7 +69,7 @@ end it "does string substitution (format) on path params" do - @request = Petstore::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -78,7 +78,7 @@ end it "URI encodes the path" do - @request = Petstore::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ + @request = Petstore::Request.new(@api_client, :get, "word.{format}/bill gates/definitions", @default_params.merge({ :params => { :word => "bill gates" } @@ -90,7 +90,7 @@ describe "#update_params_for_auth!" do it "sets header api-key parameter with prefix" do - Petstore::Swagger.configure do |config| + @api_client.configure do |config| inject_format = true config.api_key_prefix['api_key'] = 'PREFIX' end @@ -100,7 +100,7 @@ end it "sets header api-key parameter without prefix" do - Petstore::Swagger.configure do |config| + @api_client.configure do |config| inject_format = true config.api_key_prefix['api_key'] = nil end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index c583b413fcae..4aeea0ea832e 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -1,18 +1,13 @@ require 'spec_helper' -describe Petstore::Swagger::Response do - - before do - configure_swagger - prepare_pet - end +describe Petstore::Response do before(:each) do VCR.use_cassette('pet_resource', :record => :new_episodes) do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") end - @response = Petstore::Swagger::Response.new(@raw) + @response = Petstore::Response.new(API_CLIENT, @raw) end describe "initialization" do @@ -43,7 +38,7 @@ @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", :headers => {'Accept'=> "application/xml"}) end - @response = Petstore::Swagger::Response.new(@raw) + @response = Petstore::Response.new(API_CLIENT, @raw) @response.format.should == 'xml' @response.xml?.should == true end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 55279384e61f..f8e5992a342a 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -36,40 +36,36 @@ def help # help #end -def configure_swagger - Petstore::Swagger.configure do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - end +API_CLIENT = Petstore::ApiClient.new do |config| + config.api_key['api_key'] = 'special-key' + config.host = 'petstore.swagger.io' + config.base_path = '/v2' end # always delete and then re-create the pet object with 10002 -def prepare_pet +def prepare_pet(pet_api) # remove the pet - Petstore::PetApi.delete_pet(10002) + pet_api.delete_pet(10002) # recreate the pet category = Petstore::Category.new('id' => 20002, 'name' => 'category test') tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test') pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', 'category' => category, 'tags' => [tag], 'status' => 'pending') - Petstore::PetApi.add_pet(:'body'=> pet) + pet_api.add_pet(:'body'=> pet) end # always delete and then re-create the store order -def prepare_store +def prepare_store(store_api) order = Petstore::Order.new("id" => 10002, "petId" => 10002, "quantity" => 789, "shipDate" => "2015-04-06T23:42:01.678Z", "status" => "placed", "complete" => false) - Petstore::StoreApi.place_order(:body => order) + store_api.place_order(:body => order) end -configure_swagger - # A random string to tack onto stuff to ensure we're not seeing # data from a previous test run RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index 8c59de39fec6..1e0f035d1432 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -2,17 +2,17 @@ describe "Store" do before do - configure_swagger - prepare_store + @api = Petstore::StoreApi.new(API_CLIENT) + prepare_store @api end it "should fetch an order" do - item = Petstore::StoreApi.get_order_by_id(10002) + item = @api.get_order_by_id(10002) item.id.should == 10002 end it "should featch the inventory" do - result = Petstore::StoreApi.get_inventory + result = @api.get_inventory result.should be_a(Hash) result.should_not be_empty result.each do |k, v| diff --git a/samples/client/petstore/ruby/spec/swagger_spec.rb b/samples/client/petstore/ruby/spec/swagger_spec.rb deleted file mode 100644 index 957da5e20a62..000000000000 --- a/samples/client/petstore/ruby/spec/swagger_spec.rb +++ /dev/null @@ -1,56 +0,0 @@ -# require 'spec_helper' -require File.dirname(__FILE__) + '/spec_helper' - -describe Petstore::Swagger do - - before(:each) do - configure_swagger - end - - after(:each) do - end - - context 'initialization' do - - context 'URL stuff' do - - context 'host' do - it 'removes http from host' do - Petstore::Swagger.configure {|c| c.host = 'http://example.com' } - Petstore::Swagger.configuration.host.should == 'example.com' - end - - it 'removes https from host' do - Petstore::Swagger.configure {|c| c.host = 'https://wookiee.com' } - Petstore::Swagger.configuration.host.should == 'wookiee.com' - end - - it 'removes trailing path from host' do - Petstore::Swagger.configure {|c| c.host = 'hobo.com/v4' } - Petstore::Swagger.configuration.host.should == 'hobo.com' - end - end - - context 'base_path' do - it "prepends a slash to base_path" do - Petstore::Swagger.configure {|c| c.base_path = 'v4/dog' } - Petstore::Swagger.configuration.base_path.should == '/v4/dog' - end - - it "doesn't prepend a slash if one is already there" do - Petstore::Swagger.configure {|c| c.base_path = '/v4/dog' } - Petstore::Swagger.configuration.base_path.should == '/v4/dog' - end - - it "ends up as a blank string if nil" do - Petstore::Swagger.configure {|c| c.base_path = nil } - Petstore::Swagger.configuration.base_path.should == '' - end - - end - - end - - end - -end From 5bfae7b78c216e7aec47e8074f780611385ad692 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 27 Jul 2015 10:32:51 +0800 Subject: [PATCH 006/219] Ruby: use a default ApiClient when not provided --- modules/swagger-codegen/src/main/resources/ruby/api.mustache | 4 ++-- .../src/main/resources/ruby/api_client.mustache | 5 +++++ samples/client/petstore/ruby/README.md | 4 ++-- samples/client/petstore/ruby/lib/petstore/api/pet_api.rb | 4 ++-- samples/client/petstore/ruby/lib/petstore/api/store_api.rb | 4 ++-- samples/client/petstore/ruby/lib/petstore/api/user_api.rb | 4 ++-- samples/client/petstore/ruby/lib/petstore/api_client.rb | 5 +++++ 7 files changed, 20 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index e1005a901595..6b459fe013d1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -5,8 +5,8 @@ module {{moduleName}} class {{classname}} attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end {{#operation}} diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index e8fc5b9440a2..600ff190b279 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -110,6 +110,11 @@ module {{moduleName}} configure(&block) end + # Default API client. + def self.default + @@default ||= ApiClient.new + end + # Call this method to modify defaults in your initializers. def configure yield(self) if block_given? diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index b251d14faf7f..ad85f74315bf 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -42,7 +42,7 @@ ruby -Ilib script.rb ```ruby require 'petstore' -api_client = Petstore::ApiClient.new do |client| +Petstore::ApiClient.default.configure do |client| client.api_key['api_key'] = 'special-key' client.host = 'petstore.swagger.io' client.base_path = '/v2' @@ -50,7 +50,7 @@ api_client = Petstore::ApiClient.new do |client| client.debugging = true end -pet_api = Petstore::PetApi.new(api_client) +pet_api = Petstore::PetApi.new pet = pet_api.get_pet_by_id(5) puts pet.to_body ``` diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index b50b56e63437..419aec9f044c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -4,8 +4,8 @@ module Petstore class PetApi attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 3462cd8f7de3..ada198f46a31 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -4,8 +4,8 @@ module Petstore class StoreApi attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 5664f735f01e..375baffc3eff 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -4,8 +4,8 @@ module Petstore class UserApi attr_accessor :api_client - def initialize(api_client = ApiClient.new) - @api_client = api_client + def initialize(api_client = nil) + @api_client = api_client || ApiClient.default end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 569003fa133c..2f4b76d54220 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -110,6 +110,11 @@ def initialize(&block) configure(&block) end + # Default API client. + def self.default + @@default ||= ApiClient.new + end + # Call this method to modify defaults in your initializers. def configure yield(self) if block_given? From 47c8597d36a9bc0983ba5c40e2489bb094f9f076 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 27 Jul 2015 16:34:51 +0800 Subject: [PATCH 007/219] Ruby: move request/response logic to api_client --- .../codegen/languages/RubyClientCodegen.java | 2 - .../src/main/resources/ruby/api.mustache | 24 +- .../main/resources/ruby/api_client.mustache | 255 +++++++++++++++++- .../src/main/resources/ruby/gem.mustache | 2 - .../src/main/resources/ruby/request.mustache | 208 -------------- .../src/main/resources/ruby/response.mustache | 155 ----------- 6 files changed, 269 insertions(+), 377 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/request.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/ruby/response.mustache 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 352307220a61..c82b5f7b6ceb 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 @@ -109,8 +109,6 @@ public void processOpts() { supportingFiles.add(new SupportingFile("gem.mustache", libFolder, gemName + ".rb")); String gemFolder = libFolder + File.separator + gemName; supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); - supportingFiles.add(new SupportingFile("request.mustache", gemFolder, "request.rb")); - supportingFiles.add(new SupportingFile("response.mustache", gemFolder, "response.rb")); supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 6b459fe013d1..e1a6789c54fd 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -45,11 +45,11 @@ module {{moduleName}} # HTTP header 'Accept' (if needed) _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} @@ -60,20 +60,30 @@ module {{moduleName}} # http body (model) {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}}{{#bodyParam}}post_body = @api_client.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) {{/bodyParam}} auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] - {{#returnType}}response = Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('{{{returnType}}}') + {{#returnType}}result = @api_client.call_api(:{{httpMethod}}, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => '{{{returnType}}}') if @api_client.debugging @api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end - result{{/returnType}}{{^returnType}}Request.new(@api_client, :{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + return result{{/returnType}}{{^returnType}}@api_client.call_api(:{{httpMethod}}, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: {{classname}}#{{nickname}}" end - nil{{/returnType}} + return nil{{/returnType}} end {{/operation}} end diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 600ff190b279..e6cc8fac49a9 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -1,9 +1,13 @@ -require 'logger' +require 'date' require 'json' +require 'logger' +require 'tempfile' +require 'typhoeus' +require 'uri' module {{moduleName}} class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + attr_accessor :scheme, :host, :base_path, :user_agent # Defines the username used with HTTP basic authentication. # @@ -82,7 +86,6 @@ module {{moduleName}} # client.api_key['api_key'] = 'your key' # api key authentication # client.username = 'your username' # username for http basic authentication # client.password = 'your password' # password for http basic authentication - # client.format = 'json' # optional, defaults to 'json' # end def initialize(&block) @format = 'json' @@ -131,9 +134,255 @@ module {{moduleName}} @base_path = "" if @base_path == "/" end + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + # record as last response + @last_response = response + + if debugging + logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + + if opts[:return_type] + return deserialize(response, opts[:return_type]) + else + return nil + end + end + + def build_request(http_method, path, opts = {}) + url = build_request_url(path) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + + {{#hasAuthMethods}} + update_params_for_auth! header_params, query_params, opts[:auth_names] + {{/hasAuthMethods}} + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :ssl_verifypeer => @verify_ssl, + :cainfo => @ssl_ca_cert, + :verbose => @debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if debugging + logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + Typhoeus::Request.new(url, req_opts) + end + + # Deserialize the response to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(response, return_type) + body = response.body + return nil if body.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file(response) if return_type == 'File' + + # ensuring a default content type + content_type = response.headers['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)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'BOOLEAN' + data == true + when 'DateTime' + # parse date time (expecting ISO 8601 format) + DateTime.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + {{moduleName}}.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file(response) + tmp_file = Tempfile.new '', @temp_folder_path + content_disposition = response.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(response.body) } + logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + def build_request_url(path) + url = [host, base_path, path].join('/').gsub(/\/+/, '/') + url = "#{scheme}://#{url}" + URI.encode(url) + end + + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + return data + end + + {{#hasAuthMethods}} + # Update hearder and query params based on authentication settings. + def update_params_for_auth!(header_params, query_params, auth_names) + return unless auth_names + auth_names.each do |auth_name| + case auth_name + {{#authMethods}}when '{{name}}' + {{#isApiKey}}{{#isKeyInHeader}}header_params ||= {} + header_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}query_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}http_auth_header = 'Basic ' + ["#{@username}:#{@password}"].pack('m').delete("\r\n") + header_params['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} + {{/authMethods}} + end + end + end + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + {{/hasAuthMethods}} + def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + if accepts.empty? + return + elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } + 'application/json' # look for json data by default + else + accepts.join(',') + end + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + if content_types.empty? + 'application/json' # use application/json by default + elsif content_types.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_types[0] # otherwise, use the first one + end + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index 41f151590d98..37203162d6b7 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -1,8 +1,6 @@ # Common files require '{{gemName}}/api_client' require '{{gemName}}/api_error' -require '{{gemName}}/request' -require '{{gemName}}/response' require '{{gemName}}/version' # Models diff --git a/modules/swagger-codegen/src/main/resources/ruby/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/request.mustache deleted file mode 100644 index 6a7d2ac448e5..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/request.mustache +++ /dev/null @@ -1,208 +0,0 @@ -require 'uri' -require 'typhoeus' - -module {{moduleName}} - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(api_client, http_method, path, attributes = {}) - @api_client = api_client - - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= @api_client.format - @params ||= {} - - # Apply default headers - @headers = @api_client.default_headers.merge(@headers || {}) - {{#hasAuthMethods}} - update_params_for_auth! - {{/hasAuthMethods}} - end - - {{#hasAuthMethods}} - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}@headers ||= {} - @headers['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}@params ||= {} - @params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}@headers ||= {} - http_auth_header = 'Basic ' + ["#{@api_client.username}:#{@api_client.password}"].pack('m').delete("\r\n") - @headers['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} - end - end - end - {{/hasAuthMethods}} - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_client.api_key_prefix[param_name] - "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" - else - @api_client.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{@api_client.scheme}://#{@api_client.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if @api_client.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if @api_client.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if @api_client.debugging - @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => @api_client.verify_ssl, - :cainfo => @api_client.ssl_ca_cert, - :verbose => @api_client.debugging - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(@api_client, raw) - - if @api_client.debugging - @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - @api_client.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - end -end diff --git a/modules/swagger-codegen/src/main/resources/ruby/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/response.mustache deleted file mode 100644 index d3119437232f..000000000000 --- a/modules/swagger-codegen/src/main/resources/ruby/response.mustache +++ /dev/null @@ -1,155 +0,0 @@ -require 'json' -require 'date' -require 'tempfile' - -module {{moduleName}} - class Response - attr_accessor :raw - - def initialize(api_client, raw) - @api_client = api_client - @raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # 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.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['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)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - when 'String' - data.to_s - when 'Integer' - data.to_i - when 'Float' - data.to_f - when 'BOOLEAN' - data == true - when 'DateTime' - # parse date time (expecting ISO 8601 format) - DateTime.parse data - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - {{moduleName}}.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', @api_client.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end -end From 7af5db35659fbb0f9ed44e217e9318f08617770d Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 27 Jul 2015 16:37:26 +0800 Subject: [PATCH 008/219] Rebuild Ruby petstore sample --- samples/client/petstore/ruby/lib/petstore.rb | 2 - .../petstore/ruby/lib/petstore/api/pet_api.rb | 114 +++++--- .../ruby/lib/petstore/api/store_api.rb | 60 ++-- .../ruby/lib/petstore/api/user_api.rb | 116 +++++--- .../petstore/ruby/lib/petstore/api_client.rb | 256 +++++++++++++++++- .../petstore/ruby/lib/petstore/request.rb | 207 -------------- .../petstore/ruby/lib/petstore/response.rb | 155 ----------- .../petstore/ruby/spec/api_client_spec.rb | 51 ++++ .../client/petstore/ruby/spec/request_spec.rb | 113 -------- .../petstore/ruby/spec/response_spec.rb | 77 ------ 10 files changed, 499 insertions(+), 652 deletions(-) delete mode 100644 samples/client/petstore/ruby/lib/petstore/request.rb delete mode 100644 samples/client/petstore/ruby/lib/petstore/response.rb delete mode 100644 samples/client/petstore/ruby/spec/request_spec.rb delete mode 100644 samples/client/petstore/ruby/spec/response_spec.rb diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index f77710df1eab..9fa3a39f5f76 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -1,8 +1,6 @@ # Common files require 'petstore/api_client' require 'petstore/api_error' -require 'petstore/request' -require 'petstore/response' require 'petstore/version' # Models diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 419aec9f044c..5f21e703fb6d 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -30,25 +30,30 @@ def update_pet(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:PUT, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#update_pet" end - nil + return nil end # Add a new pet to the store @@ -72,25 +77,30 @@ def add_pet(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = ['petstore_auth'] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#add_pet" end - nil + return nil end # Finds Pets by status @@ -115,11 +125,11 @@ def find_pets_by_status(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -129,12 +139,17 @@ def find_pets_by_status(opts = {}) auth_names = ['petstore_auth'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Array') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Array') if @api_client.debugging @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end - result + return result end # Finds Pets by tags @@ -159,11 +174,11 @@ def find_pets_by_tags(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -173,12 +188,17 @@ def find_pets_by_tags(opts = {}) auth_names = ['petstore_auth'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Array') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Array') if @api_client.debugging @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end - result + return result end # Find pet by ID @@ -205,11 +225,11 @@ def get_pet_by_id(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -219,12 +239,17 @@ def get_pet_by_id(pet_id, opts = {}) auth_names = ['api_key', 'petstore_auth'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Pet') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Pet') if @api_client.debugging @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end - result + return result end # Updates a pet in the store with form data @@ -253,11 +278,11 @@ def update_pet_with_form(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['application/x-www-form-urlencoded'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -269,11 +294,16 @@ def update_pet_with_form(pet_id, opts = {}) auth_names = ['petstore_auth'] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#update_pet_with_form" end - nil + return nil end # Deletes a pet @@ -301,11 +331,11 @@ def delete_pet(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] # form parameters @@ -316,11 +346,16 @@ def delete_pet(pet_id, opts = {}) auth_names = ['petstore_auth'] - Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:DELETE, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#delete_pet" end - nil + return nil end # uploads an image @@ -349,11 +384,11 @@ def upload_file(pet_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = ['multipart/form-data'] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -365,11 +400,16 @@ def upload_file(pet_id, opts = {}) auth_names = ['petstore_auth'] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: PetApi#upload_file" end - nil + return nil end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index ada198f46a31..ec9f16001f25 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -29,11 +29,11 @@ def get_inventory(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -43,12 +43,17 @@ def get_inventory(opts = {}) auth_names = ['api_key'] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Hash') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Hash') if @api_client.debugging @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end - result + return result end # Place an order for a pet @@ -72,26 +77,31 @@ def place_order(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - response = Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Order') + result = @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Order') if @api_client.debugging @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end - result + return result end # Find purchase order by ID @@ -118,11 +128,11 @@ def get_order_by_id(order_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -132,12 +142,17 @@ def get_order_by_id(order_id, opts = {}) auth_names = [] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('Order') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'Order') if @api_client.debugging @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end - result + return result end # Delete purchase order by ID @@ -164,11 +179,11 @@ def delete_order(order_id, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -178,11 +193,16 @@ def delete_order(order_id, opts = {}) auth_names = [] - Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:DELETE, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: StoreApi#delete_order" end - nil + return nil end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 375baffc3eff..eda69c97282f 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -30,25 +30,30 @@ def create_user(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#create_user" end - nil + return nil end # Creates list of users with given input array @@ -72,25 +77,30 @@ def create_users_with_array_input(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#create_users_with_array_input" end - nil + return nil end # Creates list of users with given input array @@ -114,25 +124,30 @@ def create_users_with_list_input(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:POST, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#create_users_with_list_input" end - nil + return nil end # Logs user into the system @@ -159,11 +174,11 @@ def login_user(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -173,12 +188,17 @@ def login_user(opts = {}) auth_names = [] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('String') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'String') if @api_client.debugging @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end - result + return result end # Logs out current logged in user session @@ -201,11 +221,11 @@ def logout_user(opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -215,11 +235,16 @@ def logout_user(opts = {}) auth_names = [] - Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#logout_user" end - nil + return nil end # Get user by user name @@ -246,11 +271,11 @@ def get_user_by_name(username, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -260,12 +285,17 @@ def get_user_by_name(username, opts = {}) auth_names = [] - response = Request.new(@api_client, :GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make - result = response.deserialize('User') + result = @api_client.call_api(:GET, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => 'User') if @api_client.debugging @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end - result + return result end # Updated user @@ -293,25 +323,30 @@ def update_user(username, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = Request.object_to_http_body(opts[:'body']) + post_body = @api_client.object_to_http_body(opts[:'body']) auth_names = [] - Request.new(@api_client, :PUT, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:PUT, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#update_user" end - nil + return nil end # Delete user @@ -338,11 +373,11 @@ def delete_user(username, opts = {}) # HTTP header 'Accept' (if needed) _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + _header_accept_result = @api_client.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = Request.select_header_content_type(_header_content_type) + header_params['Content-Type'] = @api_client.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -352,11 +387,16 @@ def delete_user(username, opts = {}) auth_names = [] - Request.new(@api_client, :DELETE, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make + @api_client.call_api(:DELETE, path, + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names) if @api_client.debugging @api_client.logger.debug "API called: UserApi#delete_user" end - nil + return nil end end end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 2f4b76d54220..6d4dda8f939a 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -1,9 +1,13 @@ -require 'logger' +require 'date' require 'json' +require 'logger' +require 'tempfile' +require 'typhoeus' +require 'uri' module Petstore class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent, :format, :auth_token, :inject_format, :force_ending_format + attr_accessor :scheme, :host, :base_path, :user_agent # Defines the username used with HTTP basic authentication. # @@ -82,7 +86,6 @@ class ApiClient # client.api_key['api_key'] = 'your key' # api key authentication # client.username = 'your username' # username for http basic authentication # client.password = 'your password' # password for http basic authentication - # client.format = 'json' # optional, defaults to 'json' # end def initialize(&block) @format = 'json' @@ -131,9 +134,256 @@ def configure @base_path = "" if @base_path == "/" end + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + response = request.run + + # record as last response + @last_response = response + + if debugging + logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + + if opts[:return_type] + return deserialize(response, opts[:return_type]) + else + return nil + end + end + + def build_request(http_method, path, opts = {}) + url = build_request_url(path) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :ssl_verifypeer => @verify_ssl, + :cainfo => @ssl_ca_cert, + :verbose => @debugging + } + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if debugging + logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + Typhoeus::Request.new(url, req_opts) + end + + # Deserialize the response to the given return type. + # + # @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]" + def deserialize(response, return_type) + body = response.body + return nil if body.nil? || body.empty? + + # handle file downloading - save response body into a tmp file and return the File instance + return download_file(response) if return_type == 'File' + + # ensuring a default content type + content_type = response.headers['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)[0] + rescue JSON::ParserError => e + if %w(String Date DateTime).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'BOOLEAN' + data == true + when 'DateTime' + # parse date time (expecting ISO 8601 format) + DateTime.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object, return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map {|item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models, e.g. Pet + Petstore.const_get(return_type).new.tap do |model| + model.build_from_hash data + end + end + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # + # @see Configuration#temp_folder_path + # @return [File] the file downloaded + def download_file(response) + tmp_file = Tempfile.new '', @temp_folder_path + content_disposition = response.headers['Content-Disposition'] + if content_disposition + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + path = File.join File.dirname(tmp_file), filename + else + path = tmp_file.path + end + # close and delete temp file + tmp_file.close! + + File.open(path, 'w') { |file| file.write(response.body) } + logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + return File.new(path) + end + + def build_request_url(path) + url = [host, base_path, path].join('/').gsub(/\/+/, '/') + url = "#{scheme}://#{url}" + URI.encode(url) + end + + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + return data + end + + + # Update hearder and query params based on authentication settings. + def update_params_for_auth!(header_params, query_params, auth_names) + return unless auth_names + auth_names.each do |auth_name| + case auth_name + when 'api_key' + header_params ||= {} + header_params['api_key'] = get_api_key_with_prefix('api_key') + when 'petstore_auth' + # TODO: support oauth + + end + end + end + + # Get API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def get_api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + if accepts.empty? + return + elsif accepts.any?{ |s| s.casecmp('application/json') == 0 } + 'application/json' # look for json data by default + else + accepts.join(',') + end + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + if content_types.empty? + 'application/json' # use application/json by default + elsif content_types.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_types[0] # otherwise, use the first one + end + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end end end diff --git a/samples/client/petstore/ruby/lib/petstore/request.rb b/samples/client/petstore/ruby/lib/petstore/request.rb deleted file mode 100644 index af884537ff83..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/request.rb +++ /dev/null @@ -1,207 +0,0 @@ -require 'uri' -require 'typhoeus' - -module Petstore - class Request - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params, :auth_names, :response - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - def initialize(api_client, http_method, path, attributes = {}) - @api_client = api_client - - @http_method = http_method.to_sym.downcase - @path = path - - attributes.each { |name, value| send "#{name}=", value } - - @format ||= @api_client.format - @params ||= {} - - # Apply default headers - @headers = @api_client.default_headers.merge(@headers || {}) - - update_params_for_auth! - - end - - - # Update hearder and query params based on authentication settings. - def update_params_for_auth! - (@auth_names || []).each do |auth_name| - case auth_name - when 'api_key' - @headers ||= {} - @headers['api_key'] = get_api_key_with_prefix('api_key') - when 'petstore_auth' - # TODO: support oauth - - end - end - end - - - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_client.api_key_prefix[param_name] - "#{@api_client.api_key_prefix[param_name]} #{@api_client.api_key[param_name]}" - else - @api_client.api_key[param_name] - end - end - - # Construct the request URL. - def url(options = {}) - _path = self.interpreted_path - _path = "/#{_path}" unless _path.start_with?('/') - "#{@api_client.scheme}://#{@api_client.host}#{_path}" - end - - # Iterate over the params hash, injecting any path values into the path string - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if @api_client.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if @api_client.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [@api_client.base_path, p].join("/").gsub(/\/+/, '/') - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - elsif @body # http body is JSON - data = @body.is_a?(String) ? @body : @body.to_json - else - data = nil - end - - if @api_client.debugging - @api_client.logger.debug "HTTP request body param ~BEGIN~\n#{data}\n~END~\n" - end - - data - end - - def make - request_options = { - :method => self.http_method, - :headers => self.headers, - :params => self.params, - :ssl_verifypeer => @api_client.verify_ssl, - :cainfo => @api_client.ssl_ca_cert, - :verbose => @api_client.debugging - } - - if [:post, :patch, :put, :delete].include?(self.http_method) - request_options.update :body => self.outgoing_body - end - - raw = Typhoeus::Request.new(self.url, request_options).run - @response = Response.new(@api_client, raw) - - if @api_client.debugging - @api_client.logger.debug "HTTP response body ~BEGIN~\n#{@response.body}\n~END~\n" - end - - # record as last response - @api_client.last_response = @response - - unless @response.success? - fail ApiError.new(:code => @response.code, - :response_headers => @response.headers, - :response_body => @response.body), - @response.status_message - end - - @response - end - - def response_code_pretty - return unless @response - @response.code.to_s - end - - def response_headers_pretty - return unless @response - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - end -end diff --git a/samples/client/petstore/ruby/lib/petstore/response.rb b/samples/client/petstore/ruby/lib/petstore/response.rb deleted file mode 100644 index e54e13ac9515..000000000000 --- a/samples/client/petstore/ruby/lib/petstore/response.rb +++ /dev/null @@ -1,155 +0,0 @@ -require 'json' -require 'date' -require 'tempfile' - -module Petstore - class Response - attr_accessor :raw - - def initialize(api_client, raw) - @api_client = api_client - @raw = raw - end - - def code - raw.code - end - - def status_message - raw.status_message - end - - def body - raw.body - end - - def success? - raw.success? - end - - # 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.nil? || body.empty? - - # handle file downloading - save response body into a tmp file and return the File instance - return download_file if return_type == 'File' - - # ensuring a default content type - content_type = raw.headers['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)[0] - rescue JSON::ParserError => e - if %w(String Date DateTime).include?(return_type) - data = body - else - raise e - end - end - - convert_to_type data, return_type - end - - # Convert data to the given return type. - def convert_to_type(data, return_type) - return nil if data.nil? - case return_type - when 'String' - data.to_s - when 'Integer' - data.to_i - when 'Float' - data.to_f - when 'BOOLEAN' - data == true - when 'DateTime' - # parse date time (expecting ISO 8601 format) - DateTime.parse data - when 'Date' - # parse date time (expecting ISO 8601 format) - Date.parse data - when 'Object' - # generic object, return directly - data - when /\AArray<(.+)>\z/ - # e.g. Array - sub_type = $1 - data.map {|item| convert_to_type(item, sub_type) } - when /\AHash\\z/ - # e.g. Hash - sub_type = $1 - {}.tap do |hash| - data.each {|k, v| hash[k] = convert_to_type(v, sub_type) } - end - else - # models, e.g. Pet - Petstore.const_get(return_type).new.tap do |model| - model.build_from_hash data - end - end - end - - # Save response body into a file in (the defined) temporary folder, using the filename - # from the "Content-Disposition" header if provided, otherwise a random filename. - # - # @see Configuration#temp_folder_path - # @return [File] the file downloaded - def download_file - tmp_file = Tempfile.new '', @api_client.temp_folder_path - content_disposition = raw.headers['Content-Disposition'] - if content_disposition - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - path = File.join File.dirname(tmp_file), filename - else - path = tmp_file.path - end - # close and delete temp file - tmp_file.close! - - File.open(path, 'w') { |file| file.write(raw.body) } - @api_client.logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body - if format == 'json' - JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '
') - else - body - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end -end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index f66dcdd68fdb..69c4490c960a 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -50,4 +50,55 @@ end + describe "#update_params_for_auth!" do + it "sets header api-key parameter with prefix" do + api_client = Petstore::ApiClient.new do |c| + c.api_key_prefix['api_key'] = 'PREFIX' + c.api_key['api_key'] = 'special-key' + end + header_params = {} + query_params = {} + auth_names = ['api_key', 'unknown'] + api_client.update_params_for_auth! header_params, query_params, auth_names + header_params.should == {'api_key' => 'PREFIX special-key'} + query_params.should == {} + end + + it "sets header api-key parameter without prefix" do + api_client = Petstore::ApiClient.new do |c| + c.api_key_prefix['api_key'] = nil + c.api_key['api_key'] = 'special-key' + end + header_params = {} + query_params = {} + auth_names = ['api_key', 'unknown'] + api_client.update_params_for_auth! header_params, query_params, auth_names + header_params.should == {'api_key' => 'special-key'} + query_params.should == {} + end + end + + describe "#deserialize" do + it "handles Hash" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"message": "Hello"}') + data = api_client.deserialize(response, 'Hash') + data.should be_a(Hash) + data.should == {:message => 'Hello'} + end + + it "handles Hash" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"pet": {"id": 1}}') + data = api_client.deserialize(response, 'Hash') + data.should be_a(Hash) + data.keys.should == [:pet] + pet = data[:pet] + pet.should be_a(Petstore::Pet) + pet.id.should == 1 + end + end + end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb deleted file mode 100644 index b4bf64c8f39b..000000000000 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ /dev/null @@ -1,113 +0,0 @@ -require 'spec_helper' - -describe Petstore::Request do - - before(:each) do - @api_client = Petstore::ApiClient.new do |config| - inject_format = true - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' - end - - @default_http_method = :get - @default_path = "pet.{format}/fancy" - @default_params = { - :params => {:foo => "1", :bar => "2"} - } - @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, @default_params) - end - - describe "initialization" do - - it "sets default response format to json" do - @request.format.should == 'json' - end - - it "sets default headers correctly" do - @request.headers.should == {'Content-Type' => 'application/json', 'User-Agent' => 'ruby-swagger-1.0.0'} - end - - it "allows params to be nil" do - @request = Petstore::Request.new(@api_client, @default_http_method, @default_path, :params => nil) - @request.params.should == {} - end - - end - - describe "attr_accessors" do - - it "has working attributes" do - @request.format.to_s.should == 'json' - end - - it "allows attributes to be overwritten" do - @request.http_method.should == :get - @request.http_method = "post" - @request.http_method.should == 'post' - end - - end - - describe "url" do - - it "constructs a full url" do - @request.url.should == "http://petstore.swagger.io/v2/pet.json/fancy" - end - - end - - describe "path" do - - it "accounts for a total absence of format in the path string" do - @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ - :format => "xml", - :params => { - } - })) - @request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries" - end - - it "does string substitution (format) on path params" do - @request = Petstore::Request.new(@api_client, :get, "/word.{format}/cat/entries", @default_params.merge({ - :format => "xml", - :params => { - } - })) - @request.url.should == "http://petstore.swagger.io/v2/word.xml/cat/entries" - end - - it "URI encodes the path" do - @request = Petstore::Request.new(@api_client, :get, "word.{format}/bill gates/definitions", @default_params.merge({ - :params => { - :word => "bill gates" - } - })) - @request.url.should =~ /word.json\/bill\%20gates\/definitions/ - end - - end - - describe "#update_params_for_auth!" do - it "sets header api-key parameter with prefix" do - @api_client.configure do |config| - inject_format = true - config.api_key_prefix['api_key'] = 'PREFIX' - end - @request.auth_names = ['api_key', 'unknown'] - @request.update_params_for_auth! - @request.headers['api_key'].should == 'PREFIX special-key' - end - - it "sets header api-key parameter without prefix" do - @api_client.configure do |config| - inject_format = true - config.api_key_prefix['api_key'] = nil - end - @request.auth_names = ['api_key', 'unknown'] - @request.update_params_for_auth! - @request.headers['api_key'].should == 'special-key' - end - end - -end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb deleted file mode 100644 index 4aeea0ea832e..000000000000 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ /dev/null @@ -1,77 +0,0 @@ -require 'spec_helper' - -describe Petstore::Response do - - before(:each) do - VCR.use_cassette('pet_resource', :record => :new_episodes) do - @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") - end - - @response = Petstore::Response.new(API_CLIENT, @raw) - end - - describe "initialization" do - it "sets body" do - @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 - @response.code.should == 200 - end - - it "converts header string into a hash" do - @response.headers.class.should == Hash - end - end - - describe "format" do - it "recognizes json" do - @response.format.should == 'json' - @response.json?.should == true - end - - it "recognizes xml" do - VCR.use_cassette('xml_response_request', :record => :new_episodes) do - @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", - :headers => {'Accept'=> "application/xml"}) - end - @response = Petstore::Response.new(API_CLIENT, @raw) - @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(Petstore::Pet) - pet.id.should == 10002 - end - end - -end From a481db7486dacecb9e2251b55a62cdb0dfca9270 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 14 Aug 2015 16:19:43 +0800 Subject: [PATCH 009/219] Add configuration object in ruby client --- .../codegen/languages/RubyClientCodegen.java | 1 + .../src/main/resources/ruby/api.mustache | 19 +- .../main/resources/ruby/api_client.mustache | 161 +++------------- .../resources/ruby/configuration.mustache | 177 ++++++++++++++++++ .../src/main/resources/ruby/gem.mustache | 16 ++ samples/client/petstore/ruby/lib/petstore.rb | 16 ++ .../petstore/ruby/lib/petstore/api/pet_api.rb | 71 +++---- .../ruby/lib/petstore/api/store_api.rb | 39 ++-- .../ruby/lib/petstore/api/user_api.rb | 71 +++---- .../petstore/ruby/lib/petstore/api_client.rb | 162 +++------------- .../ruby/lib/petstore/configuration.rb | 164 ++++++++++++++++ .../petstore/ruby/spec/api_client_spec.rb | 39 ++-- 12 files changed, 542 insertions(+), 394 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/ruby/configuration.mustache create mode 100644 samples/client/petstore/ruby/lib/petstore/configuration.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 c82b5f7b6ceb..61fcd8240b59 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 @@ -110,6 +110,7 @@ public void processOpts() { String gemFolder = libFolder + File.separator + gemName; supportingFiles.add(new SupportingFile("api_client.mustache", gemFolder, "api_client.rb")); supportingFiles.add(new SupportingFile("api_error.mustache", gemFolder, "api_error.rb")); + supportingFiles.add(new SupportingFile("configuration.mustache", gemFolder, "configuration.rb")); supportingFiles.add(new SupportingFile("version.mustache", gemFolder, "version.rb")); String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index e1a6789c54fd..ad885dac94ee 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -6,9 +6,8 @@ module {{moduleName}} attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - {{#operation}} {{newline}} # {{summary}} @@ -18,8 +17,8 @@ module {{moduleName}} {{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}} {{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}] def {{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: {{classname}}#{{nickname}} ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: {{classname}}#{{nickname}} ..." end {{#allParams}}{{#required}} # verify the required parameter '{{paramName}}' is set @@ -71,8 +70,8 @@ module {{moduleName}} :body => post_body, :auth_names => auth_names, :return_type => '{{{returnType}}}') - if @api_client.debugging - @api_client.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: {{classname}}#{{nickname}}. Result: #{result.inspect}" end return result{{/returnType}}{{^returnType}}@api_client.call_api(:{{httpMethod}}, path, :header_params => header_params, @@ -80,8 +79,8 @@ module {{moduleName}} :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: {{classname}}#{{nickname}}" + if Configuration.debugging + Configuration.logger.debug "API called: {{classname}}#{{nickname}}" end return nil{{/returnType}} end @@ -89,3 +88,7 @@ module {{moduleName}} end {{/operations}} end + + + + diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index e6cc8fac49a9..6bc6df0430bc 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -7,69 +7,8 @@ require 'uri' module {{moduleName}} class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debugging - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path + attr_accessor :host # Defines the headers to be used in HTTP requests of all API calls by default. # @@ -79,59 +18,14 @@ module {{moduleName}} # Stores the HTTP response from the last API call using this API client. attr_accessor :last_response - # The constructor accepts a optional block to configure the API client. - # - # @example - # {{moduleName}}::ApiClient.new do |client| - # client.api_key['api_key'] = 'your key' # api key authentication - # client.username = 'your username' # username for http basic authentication - # client.password = 'your password' # password for http basic authentication - # end - def initialize(&block) + def initialize(host = nil) + @host = host || Configuration.base_url @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' @user_agent = "ruby-swagger-#{VERSION}" - @inject_format = false - @force_ending_format = false - @default_headers = { 'Content-Type' => "application/#{@format.downcase}", 'User-Agent' => @user_agent } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debugging = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - - configure(&block) - end - - # Default API client. - def self.default - @@default ||= ApiClient.new - end - - # Call this method to modify defaults in your initializers. - def configure - yield(self) if block_given? - - # remove :// from scheme - @scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - @host.sub!(/https?:\/\//, '') - @host = @host.split('/').first - - # Add leading and trailing slashes to base_path - @base_path = "/#{@base_path}".gsub(/\/+/, '/') - @base_path = "" if @base_path == "/" end def call_api(http_method, path, opts = {}) @@ -141,8 +35,8 @@ module {{moduleName}} # record as last response @last_response = response - if debugging - logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -153,9 +47,9 @@ module {{moduleName}} end if opts[:return_type] - return deserialize(response, opts[:return_type]) + deserialize(response, opts[:return_type]) else - return nil + nil end end @@ -183,8 +77,8 @@ module {{moduleName}} if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if debugging - logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end @@ -279,13 +173,13 @@ module {{moduleName}} File.open(path, 'w') { |file| file.write(response.body) } logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) + File.new(path) end def build_request_url(path) - url = [host, base_path, path].join('/').gsub(/\/+/, '/') - url = "#{scheme}://#{url}" - URI.encode(url) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + URI.encode(host + path) end def build_request_body(header_params, form_params, body) @@ -300,35 +194,22 @@ module {{moduleName}} else data = nil end - return data + data end - {{#hasAuthMethods}} # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) - return unless auth_names - auth_names.each do |auth_name| - case auth_name - {{#authMethods}}when '{{name}}' - {{#isApiKey}}{{#isKeyInHeader}}header_params ||= {} - header_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInHeader}}{{#isKeyInQuery}}query_params['{{keyParamName}}'] = get_api_key_with_prefix('{{keyParamName}}'){{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}http_auth_header = 'Basic ' + ["#{@username}:#{@password}"].pack('m').delete("\r\n") - header_params['Authorization'] = http_auth_header{{/isBasic}}{{#isOAuth}}# TODO: support oauth{{/isOAuth}} - {{/authMethods}} + Array(auth_names).each do |auth_name| + auth_setting = Configuration.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end end - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" - else - @api_key[param_name] - end - end - {{/hasAuthMethods}} - def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache new file mode 100644 index 000000000000..600f9b7bafb8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -0,0 +1,177 @@ +require 'uri' +require 'singleton' + +module {{moduleName}} + class Configuration + + include Singleton + + # Default api client + attr_accessor :api_client + + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + class << self + def method_missing(method_name, *args, &block) + config = Configuration.instance + if config.respond_to?(method_name) + config.send(method_name, *args, &block) + else + super + end + end + end + + def initialize + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @api_key = {} + @api_key_prefix = {} + @verify_ssl = true + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + end + + def api_client + @api_client ||= ApiClient.new + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def base_url + url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" + URI.encode(url) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { +{{#authMethods}} +{{#isApiKey}} + '{{name}}' => + { + type: 'api_key', + in: {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + key: '{{keyParamName}}', + value: api_key_with_prefix('{{keyParamName}}') + }, +{{/isApiKey}} +{{#isBasic}} + '{{name}}' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, +{{/isBasic}} +{{/authMethods}} + } + end + end +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache index 37203162d6b7..eb0b8cfbf0f9 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gem.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gem.mustache @@ -2,6 +2,7 @@ require '{{gemName}}/api_client' require '{{gemName}}/api_error' require '{{gemName}}/version' +require '{{gemName}}/configuration' # Models require '{{gemName}}/{{modelPackage}}/base_object' @@ -17,4 +18,19 @@ require '{{importPath}}' {{/apiInfo}} module {{moduleName}} + class << self + # Configure sdk using block. + # {{moduleName}}.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the configuration singleton instance. + def configure + if block_given? + yield Configuration.instance + else + Configuration.instance + end + end + end end diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 9fa3a39f5f76..61640d687ac7 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -2,6 +2,7 @@ require 'petstore/api_client' require 'petstore/api_error' require 'petstore/version' +require 'petstore/configuration' # Models require 'petstore/models/base_object' @@ -17,4 +18,19 @@ require 'petstore/api/store_api' module Petstore + class << self + # Configure sdk using block. + # Petstore.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the configuration singleton instance. + def configure + if block_given? + yield Configuration.instance + else + Configuration.instance + end + end + end end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 5f21e703fb6d..4b956aeadcc6 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -5,18 +5,17 @@ class PetApi attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - # Update an existing pet # # @param [Hash] opts the optional parameters # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] def update_pet(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#update_pet ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#update_pet ..." end # resource path @@ -50,8 +49,8 @@ def update_pet(opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#update_pet" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#update_pet" end return nil end @@ -62,8 +61,8 @@ def update_pet(opts = {}) # @option opts [Pet] :body Pet object that needs to be added to the store # @return [nil] def add_pet(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#add_pet ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#add_pet ..." end # resource path @@ -97,8 +96,8 @@ def add_pet(opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#add_pet" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#add_pet" end return nil end @@ -109,8 +108,8 @@ def add_pet(opts = {}) # @option opts [Array] :status Status values that need to be considered for filter # @return [Array] def find_pets_by_status(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#find_pets_by_status ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#find_pets_by_status ..." end # resource path @@ -146,8 +145,8 @@ def find_pets_by_status(opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#find_pets_by_status. Result: #{result.inspect}" end return result end @@ -158,8 +157,8 @@ def find_pets_by_status(opts = {}) # @option opts [Array] :tags Tags to filter by # @return [Array] def find_pets_by_tags(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#find_pets_by_tags ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#find_pets_by_tags ..." end # resource path @@ -195,8 +194,8 @@ def find_pets_by_tags(opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'Array') - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#find_pets_by_tags. Result: #{result.inspect}" end return result end @@ -207,8 +206,8 @@ def find_pets_by_tags(opts = {}) # @param [Hash] opts the optional parameters # @return [Pet] def get_pet_by_id(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#get_pet_by_id ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#get_pet_by_id ..." end # verify the required parameter 'pet_id' is set @@ -246,8 +245,8 @@ def get_pet_by_id(pet_id, opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'Pet') - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#get_pet_by_id. Result: #{result.inspect}" end return result end @@ -260,8 +259,8 @@ def get_pet_by_id(pet_id, opts = {}) # @option opts [String] :status Updated status of the pet # @return [nil] def update_pet_with_form(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#update_pet_with_form ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#update_pet_with_form ..." end # verify the required parameter 'pet_id' is set @@ -300,8 +299,8 @@ def update_pet_with_form(pet_id, opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#update_pet_with_form" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#update_pet_with_form" end return nil end @@ -313,8 +312,8 @@ def update_pet_with_form(pet_id, opts = {}) # @option opts [String] :api_key # @return [nil] def delete_pet(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#delete_pet ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#delete_pet ..." end # verify the required parameter 'pet_id' is set @@ -352,8 +351,8 @@ def delete_pet(pet_id, opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#delete_pet" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#delete_pet" end return nil end @@ -366,8 +365,8 @@ def delete_pet(pet_id, opts = {}) # @option opts [File] :file file to upload # @return [nil] def upload_file(pet_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: PetApi#upload_file ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: PetApi#upload_file ..." end # verify the required parameter 'pet_id' is set @@ -406,10 +405,14 @@ def upload_file(pet_id, opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: PetApi#upload_file" + if Configuration.debugging + Configuration.logger.debug "API called: PetApi#upload_file" end return nil end end end + + + + diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index ec9f16001f25..235ff1c41060 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -5,17 +5,16 @@ class StoreApi attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - # Returns pet inventories by status # Returns a map of status codes to quantities # @param [Hash] opts the optional parameters # @return [Hash] def get_inventory(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#get_inventory ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#get_inventory ..." end # resource path @@ -50,8 +49,8 @@ def get_inventory(opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'Hash') - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#get_inventory. Result: #{result.inspect}" end return result end @@ -62,8 +61,8 @@ def get_inventory(opts = {}) # @option opts [Order] :body order placed for purchasing the pet # @return [Order] def place_order(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#place_order ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#place_order ..." end # resource path @@ -98,8 +97,8 @@ def place_order(opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#place_order. Result: #{result.inspect}" end return result end @@ -110,8 +109,8 @@ def place_order(opts = {}) # @param [Hash] opts the optional parameters # @return [Order] def get_order_by_id(order_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#get_order_by_id ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#get_order_by_id ..." end # verify the required parameter 'order_id' is set @@ -149,8 +148,8 @@ def get_order_by_id(order_id, opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'Order') - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#get_order_by_id. Result: #{result.inspect}" end return result end @@ -161,8 +160,8 @@ def get_order_by_id(order_id, opts = {}) # @param [Hash] opts the optional parameters # @return [nil] def delete_order(order_id, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: StoreApi#delete_order ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: StoreApi#delete_order ..." end # verify the required parameter 'order_id' is set @@ -199,10 +198,14 @@ def delete_order(order_id, opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: StoreApi#delete_order" + if Configuration.debugging + Configuration.logger.debug "API called: StoreApi#delete_order" end return nil end end end + + + + diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index eda69c97282f..f4672e2a3585 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -5,18 +5,17 @@ class UserApi attr_accessor :api_client def initialize(api_client = nil) - @api_client = api_client || ApiClient.default + @api_client = api_client || Configuration.api_client end - # Create user # This can only be done by the logged in user. # @param [Hash] opts the optional parameters # @option opts [User] :body Created user object # @return [nil] def create_user(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#create_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#create_user ..." end # resource path @@ -50,8 +49,8 @@ def create_user(opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#create_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#create_user" end return nil end @@ -62,8 +61,8 @@ def create_user(opts = {}) # @option opts [Array] :body List of user object # @return [nil] def create_users_with_array_input(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#create_users_with_array_input ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#create_users_with_array_input ..." end # resource path @@ -97,8 +96,8 @@ def create_users_with_array_input(opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#create_users_with_array_input" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#create_users_with_array_input" end return nil end @@ -109,8 +108,8 @@ def create_users_with_array_input(opts = {}) # @option opts [Array] :body List of user object # @return [nil] def create_users_with_list_input(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#create_users_with_list_input ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#create_users_with_list_input ..." end # resource path @@ -144,8 +143,8 @@ def create_users_with_list_input(opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#create_users_with_list_input" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#create_users_with_list_input" end return nil end @@ -157,8 +156,8 @@ def create_users_with_list_input(opts = {}) # @option opts [String] :password The password for login in clear text # @return [String] def login_user(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#login_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#login_user ..." end # resource path @@ -195,8 +194,8 @@ def login_user(opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'String') - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#login_user. Result: #{result.inspect}" end return result end @@ -206,8 +205,8 @@ def login_user(opts = {}) # @param [Hash] opts the optional parameters # @return [nil] def logout_user(opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#logout_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#logout_user ..." end # resource path @@ -241,8 +240,8 @@ def logout_user(opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#logout_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#logout_user" end return nil end @@ -253,8 +252,8 @@ def logout_user(opts = {}) # @param [Hash] opts the optional parameters # @return [User] def get_user_by_name(username, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#get_user_by_name ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#get_user_by_name ..." end # verify the required parameter 'username' is set @@ -292,8 +291,8 @@ def get_user_by_name(username, opts = {}) :body => post_body, :auth_names => auth_names, :return_type => 'User') - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#get_user_by_name. Result: #{result.inspect}" end return result end @@ -305,8 +304,8 @@ def get_user_by_name(username, opts = {}) # @option opts [User] :body Updated user object # @return [nil] def update_user(username, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#update_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#update_user ..." end # verify the required parameter 'username' is set @@ -343,8 +342,8 @@ def update_user(username, opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#update_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#update_user" end return nil end @@ -355,8 +354,8 @@ def update_user(username, opts = {}) # @param [Hash] opts the optional parameters # @return [nil] def delete_user(username, opts = {}) - if @api_client.debugging - @api_client.logger.debug "Calling API: UserApi#delete_user ..." + if Configuration.debugging + Configuration.logger.debug "Calling API: UserApi#delete_user ..." end # verify the required parameter 'username' is set @@ -393,10 +392,14 @@ def delete_user(username, opts = {}) :form_params => form_params, :body => post_body, :auth_names => auth_names) - if @api_client.debugging - @api_client.logger.debug "API called: UserApi#delete_user" + if Configuration.debugging + Configuration.logger.debug "API called: UserApi#delete_user" end return nil end end end + + + + diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 6d4dda8f939a..33b53238b024 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -7,69 +7,8 @@ module Petstore class ApiClient - attr_accessor :scheme, :host, :base_path, :user_agent - # Defines the username used with HTTP basic authentication. - # - # @return [String] - attr_accessor :username - - # Defines the password used with HTTP basic authentication. - # - # @return [String] - attr_accessor :password - - # Defines API keys used with API Key authentications. - # - # @return [Hash] key: parameter name, value: parameter value (API key) - # - # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) - # config.api_key['api_key'] = 'xxx' - attr_accessor :api_key - - # Defines API key prefixes used with API Key authentications. - # - # @return [Hash] key: parameter name, value: API key prefix - # - # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) - # config.api_key_prefix['api_key'] = 'Token' - attr_accessor :api_key_prefix - - # Set this to false to skip verifying SSL certificate when calling API from https server. - # Default to true. - # - # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. - # - # @return [true, false] - attr_accessor :verify_ssl - - # Set this to customize the certificate file to verify the peer. - # - # @return [String] the path to the certificate file - # - # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: - # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 - attr_accessor :ssl_ca_cert - - # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response - # details will be logged with `logger.debug` (see the `logger` attribute). - # Default to false. - # - # @return [true, false] - attr_accessor :debugging - - # Defines the logger used for debugging. - # Default to `Rails.logger` (when in Rails) or logging to STDOUT. - # - # @return [#debug] - attr_accessor :logger - - # Defines the temporary folder to store downloaded files - # (for API endpoints that have file response). - # Default to use `Tempfile`. - # - # @return [String] - attr_accessor :temp_folder_path + attr_accessor :host # Defines the headers to be used in HTTP requests of all API calls by default. # @@ -79,59 +18,14 @@ class ApiClient # Stores the HTTP response from the last API call using this API client. attr_accessor :last_response - # The constructor accepts a optional block to configure the API client. - # - # @example - # Petstore::ApiClient.new do |client| - # client.api_key['api_key'] = 'your key' # api key authentication - # client.username = 'your username' # username for http basic authentication - # client.password = 'your password' # password for http basic authentication - # end - def initialize(&block) + def initialize(host = nil) + @host = host || Configuration.base_url @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' @user_agent = "ruby-swagger-#{VERSION}" - @inject_format = false - @force_ending_format = false - @default_headers = { 'Content-Type' => "application/#{@format.downcase}", 'User-Agent' => @user_agent } - - # keys for API key authentication (param-name => api-key) - @api_key = {} - @api_key_prefix = {} - - @verify_ssl = true - - @debugging = false - @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) - - configure(&block) - end - - # Default API client. - def self.default - @@default ||= ApiClient.new - end - - # Call this method to modify defaults in your initializers. - def configure - yield(self) if block_given? - - # remove :// from scheme - @scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - @host.sub!(/https?:\/\//, '') - @host = @host.split('/').first - - # Add leading and trailing slashes to base_path - @base_path = "/#{@base_path}".gsub(/\/+/, '/') - @base_path = "" if @base_path == "/" end def call_api(http_method, path, opts = {}) @@ -141,8 +35,8 @@ def call_api(http_method, path, opts = {}) # record as last response @last_response = response - if debugging - logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" end unless response.success? @@ -153,9 +47,9 @@ def call_api(http_method, path, opts = {}) end if opts[:return_type] - return deserialize(response, opts[:return_type]) + deserialize(response, opts[:return_type]) else - return nil + nil end end @@ -183,8 +77,8 @@ def build_request(http_method, path, opts = {}) if [:post, :patch, :put, :delete].include?(http_method) req_body = build_request_body(header_params, form_params, opts[:body]) req_opts.update :body => req_body - if debugging - logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + if Configuration.debugging + Configuration.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" end end @@ -279,13 +173,13 @@ def download_file(response) File.open(path, 'w') { |file| file.write(response.body) } logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" - return File.new(path) + File.new(path) end def build_request_url(path) - url = [host, base_path, path].join('/').gsub(/\/+/, '/') - url = "#{scheme}://#{url}" - URI.encode(url) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + URI.encode(host + path) end def build_request_body(header_params, form_params, body) @@ -300,36 +194,22 @@ def build_request_body(header_params, form_params, body) else data = nil end - return data + data end - # Update hearder and query params based on authentication settings. def update_params_for_auth!(header_params, query_params, auth_names) - return unless auth_names - auth_names.each do |auth_name| - case auth_name - when 'api_key' - header_params ||= {} - header_params['api_key'] = get_api_key_with_prefix('api_key') - when 'petstore_auth' - # TODO: support oauth - + Array(auth_names).each do |auth_name| + auth_setting = Configuration.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end end - # Get API key (with prefix if set). - # @param [String] param_name the parameter name of API key auth - def get_api_key_with_prefix(param_name) - if @api_key_prefix[param_name] - "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" - else - @api_key[param_name] - end - end - - def user_agent=(user_agent) @user_agent = user_agent @default_headers['User-Agent'] = @user_agent diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb new file mode 100644 index 000000000000..83df41b5e05a --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -0,0 +1,164 @@ +require 'uri' +require 'singleton' + +module Petstore + class Configuration + + include Singleton + + # Default api client + attr_accessor :api_client + + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + class << self + def method_missing(method_name, *args, &block) + config = Configuration.instance + if config.respond_to?(method_name) + config.send(method_name, *args, &block) + else + super + end + end + end + + def initialize + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @api_key = {} + @api_key_prefix = {} + @verify_ssl = true + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + end + + def api_client + @api_client ||= ApiClient.new + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = "" if @base_path == "/" + end + + def base_url + url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" + URI.encode(url) + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name) + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{@api_key[param_name]}" + else + @api_key[param_name] + end + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key', + value: api_key_with_prefix('api_key') + }, + } + end + end +end diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index 69c4490c960a..b63ec94ccaac 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -9,40 +9,35 @@ context 'host' do it 'removes http from host' do - c = Petstore::ApiClient.new - c.configure {|c| c.host = 'http://example.com' } - c.host.should == 'example.com' + Petstore.configure { |c| c.host = 'http://example.com' } + Petstore.configure.host.should == 'example.com' end it 'removes https from host' do - c = Petstore::ApiClient.new {|c| c.host = 'https://wookiee.com' } - c.host.should == 'wookiee.com' + Petstore.configure { |c| c.host = 'https://wookiee.com' } + Petstore.configure.host.should == 'wookiee.com' end it 'removes trailing path from host' do - c = Petstore::ApiClient.new - c.configure {|c| c.host = 'hobo.com/v4' } - c.host.should == 'hobo.com' + Petstore.configure { |c| c.host = 'hobo.com/v4' } + Petstore.configure.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do - c = Petstore::ApiClient.new - c.configure {|c| c.base_path = 'v4/dog' } - c.base_path.should == '/v4/dog' + Petstore.configure { |c| c.base_path = 'v4/dog' } + Petstore.configure.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do - c = Petstore::ApiClient.new - c.configure {|c| c.base_path = '/v4/dog' } - c.base_path.should == '/v4/dog' + Petstore.configure { |c| c.base_path = '/v4/dog' } + Petstore.configure.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do - c = Petstore::ApiClient.new - c.configure {|c| c.base_path = nil } - c.base_path.should == '' + Petstore.configure { |c| c.base_path = nil } + Petstore.configure.base_path.should == '' end end @@ -52,10 +47,13 @@ describe "#update_params_for_auth!" do it "sets header api-key parameter with prefix" do - api_client = Petstore::ApiClient.new do |c| + Petstore.configure do |c| c.api_key_prefix['api_key'] = 'PREFIX' c.api_key['api_key'] = 'special-key' end + + api_client = Petstore::ApiClient.new + header_params = {} query_params = {} auth_names = ['api_key', 'unknown'] @@ -65,10 +63,13 @@ end it "sets header api-key parameter without prefix" do - api_client = Petstore::ApiClient.new do |c| + Petstore.configure do |c| c.api_key_prefix['api_key'] = nil c.api_key['api_key'] = 'special-key' end + + api_client = Petstore::ApiClient.new + header_params = {} query_params = {} auth_names = ['api_key', 'unknown'] From 31d948fc16594b66e21ad27ca23b041067d6f780 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 18 Aug 2015 14:35:54 +0800 Subject: [PATCH 010/219] Update readme of ruby client --- samples/client/petstore/ruby/README.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index ad85f74315bf..dd6258ec6964 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -42,12 +42,12 @@ ruby -Ilib script.rb ```ruby require 'petstore' -Petstore::ApiClient.default.configure do |client| - client.api_key['api_key'] = 'special-key' - client.host = 'petstore.swagger.io' - client.base_path = '/v2' +Petstore.configure do |config| + config.api_key['api_key'] = 'special-key' + config.host = 'petstore.swagger.io' + config.base_path = '/v2' # enable debugging (default is disabled) - client.debugging = true + config.debugging = true end pet_api = Petstore::PetApi.new From 828f8694c86ae12702d976d064f305c8a84e4d99 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 18 Aug 2015 16:13:32 +0800 Subject: [PATCH 011/219] Fix typo in ruby client --- .../swagger-codegen/src/main/resources/ruby/api_client.mustache | 2 +- samples/client/petstore/ruby/lib/petstore/api_client.rb | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 6bc6df0430bc..31c5035f5595 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -204,7 +204,7 @@ module {{moduleName}} next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] - when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 33b53238b024..68fa5f9d9f18 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -204,7 +204,7 @@ def update_params_for_auth!(header_params, query_params, auth_names) next unless auth_setting case auth_setting[:in] when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] - when 'query' then query_params[auth_setting[:key]] = auth_settings[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] else fail ArgumentError, 'Authentication token must be in `query` of `header`' end end From 7be6e971fac73efabb95c81fc1bac05e660a9e37 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 18 Aug 2015 20:21:56 +0800 Subject: [PATCH 012/219] Update api client of ruby client. Update ApiClient#build_request, change `@verify_ssl`, `@ssl_ca_cert`, `@debugging` to `Configuration.verify_ssl`, `Configuration.ssl_ca_cert`, `Configuration.debugging`. --- .../src/main/resources/ruby/api_client.mustache | 6 +++--- samples/client/petstore/ruby/lib/petstore/api_client.rb | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 31c5035f5595..ea98307aead5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -69,9 +69,9 @@ module {{moduleName}} :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => @verify_ssl, - :cainfo => @ssl_ca_cert, - :verbose => @debugging + :ssl_verifypeer => Configuration.verify_ssl, + :cainfo => Configuration.ssl_ca_cert, + :verbose => Configuration.debugging } if [:post, :patch, :put, :delete].include?(http_method) diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 68fa5f9d9f18..4cb8934efe42 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -69,9 +69,9 @@ def build_request(http_method, path, opts = {}) :method => http_method, :headers => header_params, :params => query_params, - :ssl_verifypeer => @verify_ssl, - :cainfo => @ssl_ca_cert, - :verbose => @debugging + :ssl_verifypeer => Configuration.verify_ssl, + :cainfo => Configuration.ssl_ca_cert, + :verbose => Configuration.debugging } if [:post, :patch, :put, :delete].include?(http_method) From 030e45982cd61cba0cdabd619b8cd30c109fd019 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 20 Aug 2015 10:45:40 +0800 Subject: [PATCH 013/219] Add back support of file uploading to Ruby client --- .../src/main/resources/ruby/swagger/request.mustache | 3 ++- samples/client/petstore/ruby/lib/petstore/swagger/request.rb | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache index dd39449e1f31..98e0a62fcd58 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -95,7 +95,8 @@ module {{moduleName}} # For form parameters, remove empty value def outgoing_body # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' + if headers['Content-Type'] == 'application/x-www-form-urlencoded' || + headers['Content-Type'] == 'multipart/form-data' data = form_params.dup data.each do |key, value| data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter diff --git a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb index ecb8cff56435..8bb05af70783 100644 --- a/samples/client/petstore/ruby/lib/petstore/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/petstore/swagger/request.rb @@ -94,7 +94,8 @@ def interpreted_path # For form parameters, remove empty value def outgoing_body # http form - if headers['Content-Type'] == 'application/x-www-form-urlencoded' + if headers['Content-Type'] == 'application/x-www-form-urlencoded' || + headers['Content-Type'] == 'multipart/form-data' data = form_params.dup data.each do |key, value| data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter From 0d399d3f6a37340065d245cfc1e12a44a003112b Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 20 Aug 2015 11:07:20 +0800 Subject: [PATCH 014/219] Add spec for file uploading --- samples/client/petstore/ruby/spec/pet_spec.rb | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 8c33c3a9cde8..6aa148f91a20 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -105,5 +105,16 @@ pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end + + it "should upload a file to a pet" do + pet = Petstore::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") + result = Petstore::PetApi.add_pet(:body => pet) + # nothing is returned + result.should be_nil + + result = Petstore::PetApi.upload_file(10002, file: File.new('hello.txt')) + # nothing is returned + result.should be_nil + end end end From 2e3f94c2a5c4f07e11e0b7f0d502b999ce2b2a53 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 20 Aug 2015 11:18:05 +0800 Subject: [PATCH 015/219] Add file used in test: hello.txt --- samples/client/petstore/ruby/hello.txt | 1 + 1 file changed, 1 insertion(+) create mode 100644 samples/client/petstore/ruby/hello.txt diff --git a/samples/client/petstore/ruby/hello.txt b/samples/client/petstore/ruby/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/ruby/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file From b3afbe73b94f5dff327013ec7f41bcf238152ed1 Mon Sep 17 00:00:00 2001 From: Robin Eggenkamp Date: Thu, 20 Aug 2015 16:50:02 +0200 Subject: [PATCH 016/219] [Swift] Add missing checks for usePromiseKit --- .../main/resources/swift/Cartfile.mustache | 4 ++-- .../src/main/resources/swift/Podspec.mustache | 20 +++++++++++++++++++ .../src/main/resources/swift/api.mustache | 6 +++--- 3 files changed, 25 insertions(+), 5 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/swift/Podspec.mustache diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index af74617bcf20..f870554a505c 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 1.2 -github "mxcl/PromiseKit" >=1.5.3 +github "Alamofire/Alamofire" >= 1.3{{#usePromiseKit}} +github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache new file mode 100644 index 000000000000..f597a5de688b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -0,0 +1,20 @@ +Pod::Spec.new do |s| + s.name = '{{projectName}}'{{#projectDescription}} + s.summary = '{{projectDescription}}'{{/projectDescription}} + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '{{#podVersion}}{{podVersion}}{{/podVersion}}{{^podVersion}}0.0.1{{/podVersion}}' + s.source = {{#podSource}}{{& podSource}}{{/podSource}}{{^podSource}}{ :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' }{{/podSource}}{{#podAuthors}} + s.authors = {{& podAuthors}}{{/podAuthors}}{{#podSocialMediaURL}} + s.social_media_url = '{{podSocialMediaURL}}'{{/podSocialMediaURL}}{{#podDocsetURL}} + s.docset_url = '{{podDocsetURL}}'{{/podDocsetURL}} + s.license = {{#podLicense}}{{& podLicense}}{{/podLicense}}{{^podLicense}}'Apache License, Version 2.0'{{/podLicense}}{{#podHomepage}} + s.homepage = '{{podHomepage}}'{{/podHomepage}}{{#podSummary}} + s.summary = '{{podSummary}}'{{/podSummary}}{{#podDescription}} + s.description = '{{podDescription}}'{{/podDescription}}{{#podScreenshots}} + s.screenshots = {{& podScreenshots}}{{/podScreenshots}}{{#podDocumentationURL}} + s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} + s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} + s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} + s.dependency 'Alamofire', '~> 1.3' +end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index e24bdae6773c..0dd6cd2ecc1e 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -5,8 +5,8 @@ // https://github.com/swagger-api/swagger-codegen // -import Alamofire -import PromiseKit +import Alamofire{{#usePromiseKit}} +import PromiseKit{{/usePromiseKit}} extension {{projectName}}API { {{#description}} @@ -28,7 +28,7 @@ extension {{projectName}}API { {{/hasParams}}{{#allParams}} :param: {{paramName}} ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} - :returns: Promise> {{description}} + :returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} From e9564956654bc965ae62cc7cd02fdcedad2439d9 Mon Sep 17 00:00:00 2001 From: Robin Eggenkamp Date: Thu, 20 Aug 2015 17:44:11 +0200 Subject: [PATCH 017/219] [Swift] Update to new Swift 2.0 syntax and Xcode 7 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Note: configs with responseAs: “PromiseKit” won’t work yet --- .../src/main/resources/swift/APIs.mustache | 4 +- .../swift/AlamofireImplementations.mustache | 58 +++++++++++++++---- .../src/main/resources/swift/Models.mustache | 20 +++---- .../src/main/resources/swift/Podspec.mustache | 2 +- .../src/main/resources/swift/api.mustache | 8 +-- 5 files changed, 63 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index aa39ccfcbdd0..de14b2afa908 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -19,7 +19,7 @@ class APIBase { if encoded! is [AnyObject] { var dictionary = [String:AnyObject]() - for (index, item) in enumerate(encoded as! [AnyObject]) { + for (index, item) in (encoded as! [AnyObject]).enumerate() { dictionary["\(index)"] = item } return dictionary @@ -46,7 +46,7 @@ class RequestBuilder { func execute() -> Promise> { fatalError("Not implemented") } - func addHeader(#name: String, value: String) -> Self { + public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { headers[name] = value } diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 244d816332cd..320cb4633314 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -30,23 +30,57 @@ class AlamofireRequestBuilder: RequestBuilder { managerStore[managerId] = manager let encoding = isBody ? Alamofire.ParameterEncoding.JSON : Alamofire.ParameterEncoding.URL - let request = manager.request(Alamofire.Method(rawValue: method)!, URLString, parameters: parameters, encoding: encoding) + let xMethod = Alamofire.Method(rawValue: method) + let fileKeys = parameters == nil ? [] : parameters!.filter { $1.isKindOfClass(NSURL) } + .map { $0.0 } + + if fileKeys.count > 0 { + manager.upload( + xMethod!, URLString, headers: nil, + multipartFormData: { mpForm in + for (k, v) in self.parameters! { + switch v { + case let fileURL as NSURL: + mpForm.appendBodyPart(fileURL: fileURL, name: k) + break + case let string as NSString: + mpForm.appendBodyPart(data: string.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + case let number as NSNumber: + mpForm.appendBodyPart(data: number.stringValue.dataUsingEncoding(NSUTF8StringEncoding)!, name: k) + break + default: + fatalError("Unprocessable value \(v) with key \(k)") + break + } + } + }, + encodingMemoryThreshold: Manager.MultipartFormDataEncodingMemoryThreshold, + encodingCompletion: { encodingResult in + switch encodingResult { + case .Success(let upload, _, _): + self.processRequest(upload, managerId, completion) + case .Failure(let encodingError): + completion(response: nil, erorr: encodingError) + } + } + ) + } else { + processRequest(manager.request(xMethod!, URLString, parameters: parameters, encoding: encoding), managerId, completion) + } + + } + + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: NSError?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } - let defer = Promise>.defer() - request.responseJSON(options: .AllowFragments) { (req, res, json, error) in + request.responseJSON(options: .AllowFragments) { (req, res, result) in managerStore.removeValueForKey(managerId) - if let error = error { - defer.reject(error) - return - } - if res!.statusCode >= 400 { - //TODO: Add error entity - let error = NSError(domain: res!.URL!.URLString, code: res!.statusCode, userInfo: [:]) - defer.reject(error) + if result.isFailure { + completion(response: nil, erorr: result.error) return } @@ -55,7 +89,7 @@ class AlamofireRequestBuilder: RequestBuilder { defer.fulfill(response) return } - if let json: AnyObject = json { + if let json: AnyObject = result.value { let body = Decoders.decode(clazz: T.self, source: json) let response = Response(response: res!, body: body) defer.fulfill(response) diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 37c497ddcb9b..4eed292f1d11 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -35,17 +35,17 @@ private var once = dispatch_once_t() class Decoders { static private var decoders = Dictionary AnyObject)>() - static func addDecoder(#clazz: T.Type, decoder: ((AnyObject) -> T)) { + static func addDecoder(clazz clazz: T.Type, decoder: ((AnyObject) -> T)) { let key = "\(T.self)" decoders[key] = { decoder($0) as! AnyObject } } - static func decode(#clazz: [T].Type, source: AnyObject) -> [T] { + static func decode(clazz clazz: [T].Type, source: AnyObject) -> [T] { let array = source as! [AnyObject] return array.map { Decoders.decode(clazz: T.self, source: $0) } } - static func decode(#clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { + static func decode(clazz clazz: [Key:T].Type, source: AnyObject) -> [Key:T] { let sourceDictinoary = source as! [Key: AnyObject] var dictionary = [Key:T]() for (key, value) in sourceDictinoary { @@ -54,7 +54,7 @@ class Decoders { return dictionary } - static func decode(#clazz: T.Type, source: AnyObject) -> T { + static func decode(clazz clazz: T.Type, source: AnyObject) -> T { initialize() if source is T { return source as! T @@ -68,7 +68,7 @@ class Decoders { } } - static func decodeOptional(#clazz: T.Type, source: AnyObject?) -> T? { + static func decodeOptional(clazz clazz: T.Type, source: AnyObject?) -> T? { if source is NSNull { return nil } @@ -77,7 +77,7 @@ class Decoders { } } - static func decodeOptional(#clazz: [T].Type, source: AnyObject?) -> [T]? { + static func decodeOptional(clazz clazz: [T].Type, source: AnyObject?) -> [T]? { if source is NSNull { return nil } @@ -86,7 +86,7 @@ class Decoders { } } - static func decodeOptional(#clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { + static func decodeOptional(clazz clazz: [Key:T].Type, source: AnyObject?) -> [Key:T]? { if source is NSNull { return nil } @@ -113,9 +113,9 @@ class Decoders { // Decoder for {{{classname}}} Decoders.addDecoder(clazz: {{{classname}}}.self) { (source: AnyObject) -> {{{classname}}} in let sourceDictionary = source as! [NSObject:AnyObject] - var instance = {{classname}}(){{#vars}}{{#isEnum}} - instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#required}}!{{/required}} {{/isEnum}}{{^isEnum}} - instance.{{name}} = Decoders.decode{{^required}}Optional{{/required}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#required}}!{{/required}}){{/isEnum}}{{/vars}} + let instance = {{classname}}(){{#vars}}{{#isEnum}} + instance.{{name}} = (sourceDictionary["{{name}}"] as? String).map { {{classname}}.{{datatypeWithEnum}}(rawValue: $0)! }{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}} {{/isEnum}}{{^isEnum}} + instance.{{name}} = Decoders.decode{{^unwrapRequired}}Optional{{/unwrapRequired}}{{#unwrapRequired}}{{^required}}Optional{{/required}}{{/unwrapRequired}}(clazz: {{{baseType}}}.self, source: sourceDictionary["{{name}}"]{{#unwrapRequired}}{{#required}}!{{/required}}{{/unwrapRequired}}){{/isEnum}}{{/vars}} return instance }{{/model}} {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index f597a5de688b..72fff39d6f61 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 1.3' + s.dependency 'Alamofire', '~> 2.0.0-beta.1' end diff --git a/modules/swagger-codegen/src/main/resources/swift/api.mustache b/modules/swagger-codegen/src/main/resources/swift/api.mustache index 0dd6cd2ecc1e..5c2428488d64 100644 --- a/modules/swagger-codegen/src/main/resources/swift/api.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/api.mustache @@ -26,11 +26,11 @@ extension {{projectName}}API { - examples: {{{examples}}}{{/examples}}{{#externalDocs}} - externalDocs: {{externalDocs}}{{/externalDocs}}{{#hasParams}} {{/hasParams}}{{#allParams}} - :param: {{paramName}} ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} + - parameter {{paramName}}: ({{#isFormParam}}form{{/isFormParam}}{{#isQueryParam}}query{{/isQueryParam}}{{#isPathParam}}path{{/isPathParam}}{{#isHeaderParam}}header{{/isHeaderParam}}{{#isBodyParam}}body{{/isBodyParam}}) {{description}}{{/allParams}} - :returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} + - returns: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{description}} */ - func {{operationId}}({{#allParams}}{{^secondaryParam}}#{{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { + public class func {{operationId}}({{#allParams}}{{^secondaryParam}}{{paramName}} {{/secondaryParam}}{{paramName}}: {{{dataType}}}{{^required}}?{{/required}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{^secondaryParam}}var{{/secondaryParam}}{{/pathParams}} path = "{{path}}"{{#pathParams}} path = path.stringByReplacingOccurrencesOfString("{{=<% %>=}}{<%paramName%>}<%={{ }}=%>", withString: "\({{paramName}})", options: .LiteralSearch, range: nil){{/pathParams}} let url = {{projectName}}API.basePath + path @@ -43,7 +43,7 @@ extension {{projectName}}API { let requestBuilder: RequestBuilder<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}>.Type = {{projectName}}API.requestBuilderFactory.getBuilder() - return requestBuilder(method: "{{httpMethod}}", URLString: url, parameters: parameters, isBody: {{^queryParams}}true{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}) + return requestBuilder.init(method: "{{httpMethod}}", URLString: URLString, parameters: parameters, isBody: {{^queryParams}}{{^formParams}}true{{/formParams}}{{/queryParams}}{{#queryParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/queryParams}}{{#formParams}}{{^secondaryParam}}false{{/secondaryParam}}{{/formParams}}) } {{/operation}} } From 810bf58c3a0cb5cf05f68467a0e3d828baa93bf9 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 27 Aug 2015 15:40:33 -0700 Subject: [PATCH 018/219] first draft of CodegenConfigurator --- .../codegen/config/CodegenConfigurator.java | 340 ++++++++++++++++++ 1 file changed, 340 insertions(+) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java new file mode 100644 index 000000000000..48faa3a771fd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -0,0 +1,340 @@ +package io.swagger.codegen.config; + +import io.swagger.codegen.ClientOptInput; +import io.swagger.codegen.ClientOpts; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.CodegenConstants; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; +import org.apache.commons.lang3.Validate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + +/** + * A class that contains all configuration properties you would want to manipulate. + * An instance could be created by deserializing a JSON file or being populated from CLI or Maven plugin parameters. + * It also has a convenience method for creating a ClientOptInput class which is THE object DefaultGenerator.java needs + * to generate code. + */ +public class CodegenConfigurator { + + public static final Logger LOG = LoggerFactory.getLogger(CodegenConfigurator.class); + + //required config values + private final String lang; + private final String inputSpec; + + private String outputDir; + private boolean verbose = false; + private boolean skipOverwrite; + private String templateDir; + private String auth; + private String apiPackage; + private String modelPackage; + private String invokerPackage; + private String groupId; + private String artifactId; + private String artifactVersion; + private Map systemProperties = new HashMap(); + private Map instantiationTypes = new HashMap(); + private Map typeMappings = new HashMap(); + private Map additionalProperties = new HashMap(); + private Map importMappings = new HashMap(); + private Set languageSpecificPrimitives = new HashSet(); + + public CodegenConfigurator(String lang, String inputSpec) { + + Validate.notEmpty(lang, "language must be specified"); + Validate.notEmpty(lang, "input spec must be specified"); + + this.lang = lang; + this.inputSpec = inputSpec; + + this.setOutputDir("."); + } + + public String getInputSpec() { + return inputSpec; + } + + public String getOutputDir() { + return outputDir; + } + + public CodegenConfigurator setOutputDir(String outputDir) { + this.outputDir = toAbsolutePathStr(outputDir); + return this; + } + + public String getModelPackage() { + return modelPackage; + } + + public CodegenConfigurator setModelPackage(String modelPackage) { + this.modelPackage = modelPackage; + return this; + } + + public boolean isVerbose() { + return verbose; + } + + public CodegenConfigurator setVerbose(boolean verbose) { + this.verbose = verbose; + return this; + } + + public boolean isSkipOverwrite() { + return skipOverwrite; + } + + public CodegenConfigurator setSkipOverwrite(boolean skipOverwrite) { + this.skipOverwrite = skipOverwrite; + return this; + } + + public String getLang() { + return lang; + } + + public String getTemplateDir() { + return templateDir; + } + + public CodegenConfigurator setTemplateDir(String templateDir) { + this.templateDir = new File(templateDir).getAbsolutePath(); + return this; + } + + public String getAuth() { + return auth; + } + + public CodegenConfigurator setAuth(String auth) { + this.auth = auth; + return this; + } + + public String getApiPackage() { + return apiPackage; + } + + public CodegenConfigurator setApiPackage(String apiPackage) { + this.apiPackage = apiPackage; + return this; + } + + public String getInvokerPackage() { + return invokerPackage; + } + + public CodegenConfigurator setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + return this; + } + + public String getGroupId() { + return groupId; + } + + public CodegenConfigurator setGroupId(String groupId) { + this.groupId = groupId; + return this; + } + + public String getArtifactId() { + return artifactId; + } + + public CodegenConfigurator setArtifactId(String artifactId) { + this.artifactId = artifactId; + return this; + } + + public String getArtifactVersion() { + return artifactVersion; + } + + public CodegenConfigurator setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + return this; + } + + public Map getSystemProperties() { + return systemProperties; + } + + public CodegenConfigurator setSystemProperties(Map systemProperties) { + this.systemProperties = systemProperties; + return this; + } + + public CodegenConfigurator addSystemProperty(String key, String value) { + this.systemProperties.put(key, value); + return this; + } + + public Map getInstantiationTypes() { + return instantiationTypes; + } + + public CodegenConfigurator setInstantiationTypes(Map instantiationTypes) { + this.instantiationTypes = instantiationTypes; + return this; + } + + public CodegenConfigurator addInstantiationType(String key, String value) { + this.instantiationTypes.put(key, value); + return this; + } + + public Map getTypeMappings() { + return typeMappings; + } + + public CodegenConfigurator setTypeMappings(Map typeMappings) { + this.typeMappings = typeMappings; + return this; + } + + public CodegenConfigurator addTypeMapping(String key, String value) { + this.typeMappings.put(key, value); + return this; + } + + public Map getAdditionalProperties() { + return additionalProperties; + } + + public CodegenConfigurator setAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + public CodegenConfigurator addAdditionalProperty(String key, String value) { + this.additionalProperties.put(key, value); + return this; + } + + public Map getImportMappings() { + return importMappings; + } + + public CodegenConfigurator setImportMappings(Map importMappings) { + this.importMappings = importMappings; + return this; + } + + public CodegenConfigurator addImportMapping(String key, String value) { + this.importMappings.put(key, value); + return this; + } + + public Set getLanguageSpecificPrimitives() { + return languageSpecificPrimitives; + } + + public CodegenConfigurator setLanguageSpecificPrimitives(Set languageSpecificPrimitives) { + this.languageSpecificPrimitives = languageSpecificPrimitives; + return this; + } + + public CodegenConfigurator addLanguageSpecificPrimitive(String value) { + this.languageSpecificPrimitives.add(value); + return this; + } + + public ClientOptInput toClientOptInput() { + setVerboseFlags(); + setSystemProperties(); + + CodegenConfig config = CodegenConfigLoader.forName(lang); + + config.setOutputDir(outputDir); + config.setSkipOverwrite(skipOverwrite); + + config.instantiationTypes().putAll(instantiationTypes); + config.typeMapping().putAll(typeMappings); + config.importMapping().putAll(importMappings); + config.languageSpecificPrimitives().addAll(languageSpecificPrimitives); + + checkAndSetAdditionalProperty(apiPackage, CodegenConstants.API_PACKAGE); + checkAndSetAdditionalProperty(modelPackage, CodegenConstants.MODEL_PACKAGE); + checkAndSetAdditionalProperty(invokerPackage, CodegenConstants.INVOKER_PACKAGE); + checkAndSetAdditionalProperty(groupId, CodegenConstants.GROUP_ID); + checkAndSetAdditionalProperty(artifactId, CodegenConstants.ARTIFACT_ID); + checkAndSetAdditionalProperty(artifactVersion, CodegenConstants.ARTIFACT_VERSION); + checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR); + + final String library = additionalProperties.remove(CodegenConstants.LIBRARY); + if (isNotEmpty(library)) { + config.setLibrary(library); + } + + config.additionalProperties().putAll(additionalProperties); + + ClientOptInput input = new ClientOptInput() + .config(config) + .auth(auth); + + Swagger swagger = new SwaggerParser().read(inputSpec, input.getAuthorizationValues(), true); + + input.opts(new ClientOpts()) + .swagger(swagger); + + return input; + + } + + private void setVerboseFlags() { + if (!verbose) { + return; + } + LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" + + "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + + "\n - [debugModels] prints models passed to the template engine" + + "\n - [debugOperations] prints operations passed to the template engine" + + "\n - [debugSupportingFiles] prints additional data passed to the template engine"); + + System.setProperty("debugSwagger", ""); + System.setProperty("debugModels", ""); + System.setProperty("debugOperations", ""); + System.setProperty("debugSupportingFiles", ""); + } + + private void setSystemProperties() { + for (Map.Entry entry : systemProperties.entrySet()) { + System.setProperty(entry.getKey(), entry.getValue()); + } + } + + private static String toAbsolutePathStr(String path) { + if (isNotEmpty(path)) { + return Paths.get(path).toAbsolutePath().toString(); + } + + return path; + + } + + private void checkAndSetAdditionalProperty(String property, String propertyKey) { + checkAndSetAdditionalProperty(property, property, propertyKey); + } + + private void checkAndSetAdditionalProperty(String property, String valueToSet, String propertyKey) { + if (isNotEmpty(property)) { + additionalProperties.put(propertyKey, valueToSet); + } + } + +} From a59c128f90f91e546ef2d61d515b2d34aeb64ba2 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 27 Aug 2015 15:40:56 -0700 Subject: [PATCH 019/219] curse you github desktop client for not refreshing when i want you to --- .../src/main/java/io/swagger/codegen/ClientOptInput.java | 9 ++++++++- .../main/java/io/swagger/codegen/CodegenConstants.java | 1 + 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java index 56c4c66835a2..456c7799065d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java @@ -9,6 +9,8 @@ import java.util.ArrayList; import java.util.List; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + public class ClientOptInput { private CodegenConfig config; private ClientOpts opts; @@ -30,6 +32,11 @@ public ClientOptInput config(CodegenConfig codegenConfig) { return this; } + public ClientOptInput auth(String urlEncodedAuthString) { + this.setAuth(urlEncodedAuthString); + return this; + } + public String getAuth() { if (auths != null) { StringBuilder b = new StringBuilder(); @@ -54,7 +61,7 @@ public String getAuth() { public void setAuth(String urlEncodedAuthString) { List auths = new ArrayList(); - if (urlEncodedAuthString != null && !"".equals(urlEncodedAuthString)) { + if (isNotEmpty(urlEncodedAuthString)) { String[] parts = urlEncodedAuthString.split(","); for (String part : parts) { String[] kvPair = part.split(":"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index c4bdad9c6eab..569e445b07da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -33,4 +33,5 @@ public class CodegenConstants { public static final String SERIALIZABLE_MODEL = "serializableModel"; public static final String SERIALIZABLE_MODEL_DESC = "boolean - toggle \"implements Serializable\" for generated models"; + public static final String LIBRARY = "library"; } From 5c74146879cd1816b9893b96b2197fab7ffcedaa Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 27 Aug 2015 15:56:58 -0700 Subject: [PATCH 020/219] a few tweaks --- .../codegen/config/CodegenConfigurator.java | 25 +++++++++++-------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 48faa3a771fd..1d98399a5393 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -30,10 +30,8 @@ public class CodegenConfigurator { public static final Logger LOG = LoggerFactory.getLogger(CodegenConfigurator.class); - //required config values - private final String lang; - private final String inputSpec; - + private String lang; + private String inputSpec; private String outputDir; private boolean verbose = false; private boolean skipOverwrite; @@ -52,15 +50,18 @@ public class CodegenConfigurator { private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); - public CodegenConfigurator(String lang, String inputSpec) { - - Validate.notEmpty(lang, "language must be specified"); - Validate.notEmpty(lang, "input spec must be specified"); + public CodegenConfigurator() { + this.setOutputDir("."); + } + public CodegenConfigurator setLang(String lang) { this.lang = lang; - this.inputSpec = inputSpec; + return this; + } - this.setOutputDir("."); + public CodegenConfigurator setInputSpec(String inputSpec) { + this.inputSpec = inputSpec; + return this; } public String getInputSpec() { @@ -255,6 +256,10 @@ public CodegenConfigurator addLanguageSpecificPrimitive(String value) { } public ClientOptInput toClientOptInput() { + + Validate.notEmpty(lang, "language must be specified"); + Validate.notEmpty(inputSpec, "input spec must be specified"); + setVerboseFlags(); setSystemProperties(); From acbf3d3cc5f886d82ff6f6282eb16299eed87f80 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 27 Aug 2015 15:59:10 -0700 Subject: [PATCH 021/219] comment twak --- .../java/io/swagger/codegen/config/CodegenConfigurator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 1d98399a5393..acc55f3c3144 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -21,7 +21,7 @@ import static org.apache.commons.lang3.StringUtils.isNotEmpty; /** - * A class that contains all configuration properties you would want to manipulate. + * A class that contains all codegen configuration properties a user would want to manipulate. * An instance could be created by deserializing a JSON file or being populated from CLI or Maven plugin parameters. * It also has a convenience method for creating a ClientOptInput class which is THE object DefaultGenerator.java needs * to generate code. From 32ffab45192ee0101c7cda55ed0a75585bf3f7b3 Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Thu, 27 Aug 2015 19:17:40 +0200 Subject: [PATCH 022/219] fix issue #1143: add another null check. The problem was trying to iterate over a null list. --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 2 ++ 1 file changed, 2 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 fe9b9ed2e57d..93ca1911c572 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 @@ -342,6 +342,8 @@ public Map postProcessModels(Map objs) { continue; List values = (List) allowableValues.get("values"); // put "enumVars" map into `allowableValues", including `name` and `value` + if (values == null) + continue; List> enumVars = new ArrayList>(); for (String value : values) { Map enumVar = new HashMap(); From be84f03d1404a53b66a22358e81b6eef5f82df0c Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Fri, 28 Aug 2015 18:40:14 +0200 Subject: [PATCH 023/219] Issue #1146: do not escape newlines in generated javadocs. For this, we add a property `unescapedDescription` to CodegenModel + CodegenProperty, and use them for the Javadoc generation, while the annotation uses the escaped `description`. --- .../src/main/java/io/swagger/codegen/CodegenModel.java | 3 ++- .../main/java/io/swagger/codegen/CodegenProperty.java | 2 ++ .../main/java/io/swagger/codegen/DefaultCodegen.java | 2 ++ .../src/main/resources/JavaJaxRS/model.mustache | 10 +++++----- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java index 6a84274774cc..f4dcd074404f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenModel.java @@ -10,9 +10,10 @@ public class CodegenModel { public String parent; public String name, classname, description, classVarName, modelJson; + public String unescapedDescription; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; public ExternalDocs externalDocs; -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 076d6cbfbdbe..ce47eabacec3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -7,6 +7,8 @@ public class CodegenProperty { public String baseName, complexType, getter, setter, description, datatype, datatypeWithEnum, name, min, max, defaultValue, baseType, containerType; + public String unescapedDescription; + /** * maxLength validation for strings, see http://json-schema.org/latest/json-schema-validation.html#rfc.section.5.2.1 */ diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index aeca659e42a9..c092889c0b52 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -533,6 +533,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe m.name = name; } m.description = escapeText(model.getDescription()); + m.unescapedDescription = model.getDescription(); m.classname = toModelName(name); m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); @@ -629,6 +630,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.name = toVarName(name); property.baseName = name; property.description = escapeText(p.getDescription()); + property.unescapedDescription = p.getDescription(); property.getter = "get" + getterAndSetterCapitalize(name); property.setter = "set" + getterAndSetterCapitalize(name); property.example = p.getExample(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index db2480a85403..a959c224498e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -7,10 +7,10 @@ import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; {{#models}} -{{#model}}{{#description}} +{{#model}}{{#unescapedDescription}} /** - * {{description}} - **/{{/description}} + * {{unescapedDescription}} + **/{{/unescapedDescription}} @ApiModel(description = "{{{description}}}") {{>generatedAnnotation}} public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { @@ -22,8 +22,8 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} {{#vars}} - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} + /**{{#unescapedDescription}} + * {{{unescapedDescription}}}{{/unescapedDescription}}{{#minimum}} * minimum: {{minimum}}{{/minimum}}{{#maximum}} * maximum: {{maximum}}{{/maximum}} **/ From cdd104d3fb28b508113e0e73abee76ada3e9878f Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Fri, 28 Aug 2015 19:39:01 +0200 Subject: [PATCH 024/219] Issue #1146: escape the response description. This prevents line breaks in string literals, which are not allowed in Java. --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index aeca659e42a9..b1b6566d0e9e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -963,7 +963,7 @@ public CodegenResponse fromResponse(String responseCode, Response response) { } else { r.code = responseCode; } - r.message = response.getDescription(); + r.message = escapeText(response.getDescription()); r.schema = response.getSchema(); r.examples = toExamples(response.getExamples()); r.jsonSchema = Json.pretty(response); From 74bffbaadb89c9cde6fc2c27cf7c4755d9e024a5 Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Fri, 28 Aug 2015 19:41:32 +0200 Subject: [PATCH 025/219] Issue #1146: fix indentation in the generated API file. --- .../swagger-codegen/src/main/resources/JavaJaxRS/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index a2213ea60860..65dfa6835bfd 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -45,7 +45,7 @@ public class {{classname}} { public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws NotFoundException { - return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); } {{/operation}} } From 930c5191e0f4d251c795023799566a49a28ff8a0 Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Fri, 28 Aug 2015 19:56:37 +0200 Subject: [PATCH 026/219] Issue #1146: trim string before escaping This removes leading and trailing whitespace before escaping strings. This gets rid of annoying `\n` in some string literals (e.g. in annotations). --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index aeca659e42a9..f2f90665b1b0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -126,6 +126,7 @@ public void processSwagger(Swagger swagger) { // override with any special text escaping logic public String escapeText(String input) { if (input != null) { + input = input.trim(); String output = input.replaceAll("\n", "\\\\n"); output = output.replace("\"", "\\\""); return output; From 4477009ef80df7f8a10c29b16a358c99b3d66aae Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 29 Aug 2015 16:19:43 +0800 Subject: [PATCH 027/219] Handle special characters in parameter names in ruby client --- .../io/swagger/codegen/languages/RubyClientCodegen.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 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 6c6d073e9c9b..59b62b0be6ad 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 @@ -196,8 +196,10 @@ public String toDefaultValue(Property p) { @Override public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); + // remove trailing special characters, e.g. "post[created-at]!!" => "post[created-at" + name = name.replaceAll("\\W+\\z", ""); + // replace special characters with _, e.g. "post[created-at" => "post_created_at" + name = name.replaceAll("\\W+", "_"); // if it's all uppper case, convert to lower case if (name.matches("^[A-Z_]*$")) { From 265de9654bf0cfb45d9c19f67a057df76a2d15cb Mon Sep 17 00:00:00 2001 From: cbornet Date: Sat, 29 Aug 2015 18:14:33 +0200 Subject: [PATCH 028/219] add authorizations to retrofit client added basic auth, api key and oauth support to the service generator using okhttp interceptors Fix #962 --- .../languages/RetrofitClientCodegen.java | 10 + .../src/main/resources/retrofit/api.mustache | 22 +- .../resources/retrofit/auth/apikey.mustache | 68 +++++ .../resources/retrofit/auth/basic.mustache | 49 ++++ .../resources/retrofit/auth/oauth.mustache | 148 ++++++++++ .../retrofit/auth/oauthflow.mustache | 5 + .../retrofit/auth/oauthokclient.mustache | 69 +++++ .../src/main/resources/retrofit/pom.mustache | 18 +- .../main/resources/retrofit/service.mustache | 264 +++++++++++++++-- samples/client/petstore/retrofit/pom.xml | 18 +- .../io/swagger/client/ServiceGenerator.java | 265 ++++++++++++++++-- .../java/io/swagger/client/api/PetApi.java | 181 ++++++++++-- .../java/io/swagger/client/api/StoreApi.java | 66 ++++- .../java/io/swagger/client/api/UserApi.java | 134 ++++++++- .../client/auth/ApiKeyAuthorization.java | 68 +++++ .../client/auth/BasicAuthorization.java | 49 ++++ .../client/auth/OauthAuthorization.java | 148 ++++++++++ .../io/swagger/client/auth/OauthFlow.java | 5 + .../client/auth/OauthOkHttpClient.java | 69 +++++ .../io/swagger/client/model/ApiResponse.java | 63 +++++ .../java/io/swagger/client/model/Pet.java | 2 +- .../io/swagger/petstore/test/PetApiTest.java | 4 +- .../swagger/petstore/test/StoreApiTest.java | 8 +- .../io/swagger/petstore/test/UserApiTest.java | 2 +- 24 files changed, 1629 insertions(+), 106 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache create mode 100644 modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache create mode 100644 modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache create mode 100644 modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache create mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java create mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java create mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java create mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java create mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java create mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java index 66d3f19f948b..54f461fe21c3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java @@ -52,6 +52,16 @@ public RetrofitClientCodegen() { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("service.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ServiceGenerator.java")); + supportingFiles.add(new SupportingFile("auth/basic.mustache", + (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "BasicAuthorization.java")); + supportingFiles.add(new SupportingFile("auth/apikey.mustache", + (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "ApiKeyAuthorization.java")); + supportingFiles.add(new SupportingFile("auth/oauth.mustache", + (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "OauthAuthorization.java")); + supportingFiles.add(new SupportingFile("auth/oauthflow.mustache", + (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "OauthFlow.java")); + supportingFiles.add(new SupportingFile("auth/oauthokclient.mustache", + (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "OauthOkHttpClient.java")); languageSpecificPrimitives = new HashSet( Arrays.asList( diff --git a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache index 1f49b4a7cbad..9d3094e38bd3 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache @@ -2,6 +2,7 @@ package {{package}}; import {{modelPackage}}.*; +import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; import java.util.*; @@ -14,6 +15,7 @@ public interface {{classname}} { {{#operation}} /** * {{summary}} + * Sync method * {{notes}} {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} @@ -22,8 +24,22 @@ public interface {{classname}} { {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} - );{{/hasMore}}{{/allParams}} + {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + );{{/hasMore}}{{/allParams}} + + /** + * {{summary}} + * Async method +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @param cb callback method + * @return void + */ + {{#formParams}}{{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + @{{httpMethod}}("{{path}}") + void {{nickname}}( + {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}} Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb + ); {{/operation}} } -{{/operations}} +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache b/modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache new file mode 100644 index 000000000000..9f5eaef7fdcb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache @@ -0,0 +1,68 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class ApiKeyAuthorization implements Interceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuthorization(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); + + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } + + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } + + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache b/modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache new file mode 100644 index 000000000000..f1c88fe90530 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache @@ -0,0 +1,49 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; + +import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class BasicAuthorization implements Interceptor { + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); + } + return chain.proceed(request); + } +} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache new file mode 100644 index 000000000000..a1a2ecabfaaf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache @@ -0,0 +1,148 @@ +package {{invokerPackage}}.auth; + +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.io.IOException; +import java.util.Map; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OauthAuthorization implements Interceptor { + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + public OauthAuthorization( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OauthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OauthAuthorization(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OauthAuthorization(OauthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OauthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { + + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response.code() == HTTP_UNAUTHORIZED ) { + updateAccessToken(requestAccessToken); + return intercept( chain ); + } + return response; + } + + public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse; + accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + setAccessToken(accessTokenResponse.getAccessToken()); + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + +} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache b/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache new file mode 100644 index 000000000000..6d18cb3aa848 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache @@ -0,0 +1,5 @@ +package {{invokerPackage}}.auth; + +public enum OauthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache b/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache new file mode 100644 index 000000000000..61f651f76969 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache @@ -0,0 +1,69 @@ +package {{invokerPackage}}.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OauthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OauthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OauthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache index 7d999db86caf..8ed9335b4eea 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache @@ -112,18 +112,22 @@ swagger-annotations ${swagger-annotations-version} - - com.google.code.gson - gson - ${gson-version} - compile - com.squareup.retrofit retrofit ${retrofit-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} compile + + com.squareup.okhttp + okhttp + ${okhttp-version} + @@ -137,6 +141,8 @@ 1.5.0 2.3.1 1.9.0 + 2.4.0 + 1.0.0 1.0.0 4.12 diff --git a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache b/modules/swagger-codegen/src/main/resources/retrofit/service.mustache index df6d61b7ab85..aa7b73f21474 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/service.mustache @@ -1,15 +1,17 @@ package {{invokerPackage}}; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; - import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; import retrofit.RestAdapter; +import retrofit.client.OkClient; import retrofit.converter.ConversionException; import retrofit.converter.Converter; import retrofit.converter.GsonConverter; @@ -17,21 +19,245 @@ import retrofit.mime.TypedByteArray; import retrofit.mime.TypedInput; import retrofit.mime.TypedOutput; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; + +import {{invokerPackage}}.auth.BasicAuthorization; +import {{invokerPackage}}.auth.ApiKeyAuthorization; +import {{invokerPackage}}.auth.OauthAuthorization; +import {{invokerPackage}}.auth.OauthFlow; + + public class ServiceGenerator { - // No need to instantiate this class. - private ServiceGenerator() { } - - public static S createService(Class serviceClass) { - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .create(); - RestAdapter adapter = new RestAdapter.Builder() - .setEndpoint("{{basePath}}") - .setConverter(new GsonConverterWrapper(gson)) - .build(); - - return adapter.create(serviceClass); - } + + private Map apiAuthorizations; + private OkHttpClient okClient; + private RestAdapter.Builder adapterBuilder; + + public ServiceGenerator() { + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ServiceGenerator(String[] authNames) { + this(); + okClient = new OkHttpClient(); + adapterBuilder.setClient(new OkClient(okClient)); + for(String authName : authNames) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + Interceptor auth;{{#authMethods}} + if (authName == "{{name}}") { {{#isBasic}} + auth = new BasicAuthorization();{{/isBasic}}{{#isApiKey}} + auth = new ApiKeyAuthorization({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} + auth = new OauthAuthorization(OauthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{^-first}}, {{/-first}}{{this}}{{/scopes}}");{{/isOAuth}} + } else {{/authMethods}}{ + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + apiAuthorizations.put(authName, auth); + } + addAuthsToOkClient(okClient); + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ServiceGenerator(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ServiceGenerator(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ServiceGenerator(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ServiceGenerator(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); + + adapterBuilder = new RestAdapter + .Builder() + .setEndpoint("{{basePath}}") + .setConverter(new GsonConverterWrapper(gson)); + } + + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + + } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuthorization) { + ApiKeyAuthorization keyAuth = (ApiKeyAuthorization) apiAuthorization; + keyAuth.setApiKey(apiKey); + return; + } + } + } + + /** + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password + */ + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof BasicAuthorization) { + BasicAuthorization basicAuth = (BasicAuthorization) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + */ + public void setAccessToken(String accessToken) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + oauth.setAccessToken(accessToken); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public RestAdapter.Builder getAdapterBuilder() { + return adapterBuilder; + } + + public void setAdapterBuilder(RestAdapter.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; + } + + public OkHttpClient getOkClient() { + return okClient; + } + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); + } + } + + /** + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter + * @param okClient + */ + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.setClient(new OkClient(clone)); + } } /** diff --git a/samples/client/petstore/retrofit/pom.xml b/samples/client/petstore/retrofit/pom.xml index 45463b449bd1..0c090b0b85ea 100644 --- a/samples/client/petstore/retrofit/pom.xml +++ b/samples/client/petstore/retrofit/pom.xml @@ -112,18 +112,22 @@ swagger-annotations ${swagger-annotations-version} - - com.google.code.gson - gson - ${gson-version} - compile - com.squareup.retrofit retrofit ${retrofit-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} compile + + com.squareup.okhttp + okhttp + ${okhttp-version} + @@ -137,6 +141,8 @@ 1.5.0 2.3.1 1.9.0 + 2.4.0 + 1.0.0 1.0.0 4.12 diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java index 1ffb0c58b0c1..244b9f50f843 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java @@ -1,15 +1,17 @@ package io.swagger.client; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; - import java.io.ByteArrayOutputStream; -import java.io.InputStream; import java.io.IOException; +import java.io.InputStream; import java.lang.reflect.Type; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; import retrofit.RestAdapter; +import retrofit.client.OkClient; import retrofit.converter.ConversionException; import retrofit.converter.Converter; import retrofit.converter.GsonConverter; @@ -17,21 +19,246 @@ import retrofit.mime.TypedInput; import retrofit.mime.TypedOutput; +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; + +import io.swagger.client.auth.BasicAuthorization; +import io.swagger.client.auth.ApiKeyAuthorization; +import io.swagger.client.auth.OauthAuthorization; +import io.swagger.client.auth.OauthFlow; + + public class ServiceGenerator { - // No need to instantiate this class. - private ServiceGenerator() { } - - public static S createService(Class serviceClass) { - Gson gson = new GsonBuilder() - .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") - .create(); - RestAdapter adapter = new RestAdapter.Builder() - .setEndpoint("http://petstore.swagger.io/v2") - .setConverter(new GsonConverterWrapper(gson)) - .build(); - - return adapter.create(serviceClass); - } + + private Map apiAuthorizations; + private OkHttpClient okClient; + private RestAdapter.Builder adapterBuilder; + + public ServiceGenerator() { + apiAuthorizations = new LinkedHashMap(); + createDefaultAdapter(); + } + + public ServiceGenerator(String[] authNames) { + this(); + okClient = new OkHttpClient(); + adapterBuilder.setClient(new OkClient(okClient)); + for(String authName : authNames) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + Interceptor auth; + if (authName == "petstore_auth") { + auth = new OauthAuthorization(OauthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else + if (authName == "api_key") { + auth = new ApiKeyAuthorization("header", "api_key"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + apiAuthorizations.put(authName, auth); + } + addAuthsToOkClient(okClient); + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ServiceGenerator(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ServiceGenerator(String authName, String apiKey) { + this(authName); + this.setApiKey(apiKey); + } + + /** + * Helper constructor for single basic auth or password oauth2 + * @param authName + * @param username + * @param password + */ + public ServiceGenerator(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); + } + + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ServiceGenerator(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + + public void createDefaultAdapter() { + Gson gson = new GsonBuilder() + .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ") + .create(); + + adapterBuilder = new RestAdapter + .Builder() + .setEndpoint("http://petstore.swagger.io/v2") + .setConverter(new GsonConverterWrapper(gson)); + } + + public S createService(Class serviceClass) { + return adapterBuilder.build().create(serviceClass); + + } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + private void setApiKey(String apiKey) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuthorization) { + ApiKeyAuthorization keyAuth = (ApiKeyAuthorization) apiAuthorization; + keyAuth.setApiKey(apiKey); + return; + } + } + } + + /** + * Helper method to configure the username/password for basic auth or password oauth + * @param username + * @param password + */ + private void setCredentials(String username, String password) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof BasicAuthorization) { + BasicAuthorization basicAuth = (BasicAuthorization) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public TokenRequestBuilder getTokenEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + return oauth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return + */ + public AuthenticationRequestBuilder getAuthorizationEndPoint() { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + return oauth.getAuthenticationRequestBuilder(); + } + } + return null; + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken + */ + public void setAccessToken(String accessToken) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + oauth.setAccessToken(accessToken); + return; + } + } + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId + * @param clientSecret + * @param redirectURI + */ + public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OauthAuthorization) { + OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + + public RestAdapter.Builder getAdapterBuilder() { + return adapterBuilder; + } + + public void setAdapterBuilder(RestAdapter.Builder adapterBuilder) { + this.adapterBuilder = adapterBuilder; + } + + public OkHttpClient getOkClient() { + return okClient; + } + + public void addAuthsToOkClient(OkHttpClient okClient) { + for(Interceptor apiAuthorization : apiAuthorizations.values()) { + okClient.interceptors().add(apiAuthorization); + } + } + + /** + * Clones the okClient given in parameter, adds the auth interceptors and uses it to configure the RestAdapter + * @param okClient + */ + public void configureFromOkclient(OkHttpClient okClient) { + OkHttpClient clone = okClient.clone(); + addAuthsToOkClient(clone); + adapterBuilder.setClient(new OkClient(clone)); + } } /** diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java index cca8370a1812..dd485d7dcefb 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -2,116 +2,237 @@ import io.swagger.client.model.*; +import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; import java.util.*; import io.swagger.client.model.Pet; import java.io.File; +import io.swagger.client.model.ApiResponse; public interface PetApi { - + /** * Update an existing pet - * + * Sync method + * * @param body Pet object that needs to be added to the store * @return Void */ - - @PUT("/pet") + + @PUT("/pet") Void updatePet( @Body Pet body ); + /** + * Update an existing pet + * Async method + * @param body Pet object that needs to be added to the store + * @param cb callback method + * @return void + */ + + @PUT("/pet") + void updatePet( + @Body Pet body, Callback cb + ); + /** * Add a new pet to the store - * + * Sync method + * * @param body Pet object that needs to be added to the store * @return Void */ - - @POST("/pet") + + @POST("/pet") Void addPet( @Body Pet body ); + /** + * Add a new pet to the store + * Async method + * @param body Pet object that needs to be added to the store + * @param cb callback method + * @return void + */ + + @POST("/pet") + void addPet( + @Body Pet body, Callback cb + ); + /** * Finds Pets by status + * Sync method * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter * @return List */ - - @GET("/pet/findByStatus") + + @GET("/pet/findByStatus") List findPetsByStatus( @Query("status") List status ); + /** + * Finds Pets by status + * Async method + * @param status Status values that need to be considered for filter + * @param cb callback method + * @return void + */ + + @GET("/pet/findByStatus") + void findPetsByStatus( + @Query("status") List status, Callback> cb + ); + /** * Finds Pets by tags + * Sync method * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by * @return List */ - - @GET("/pet/findByTags") + + @GET("/pet/findByTags") List findPetsByTags( @Query("tags") List tags ); + /** + * Finds Pets by tags + * Async method + * @param tags Tags to filter by + * @param cb callback method + * @return void + */ + + @GET("/pet/findByTags") + void findPetsByTags( + @Query("tags") List tags, Callback> cb + ); + /** * 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 + * Sync method + * Returns a single pet + * @param petId ID of pet to return * @return Pet */ - - @GET("/pet/{petId}") + + @GET("/pet/{petId}") Pet getPetById( @Path("petId") Long petId ); + /** + * Find pet by ID + * Async method + * @param petId ID of pet to return + * @param cb callback method + * @return void + */ + + @GET("/pet/{petId}") + void getPetById( + @Path("petId") Long petId, Callback cb + ); + /** * Updates a pet in the store with form data - * + * Sync method + * * @param petId ID of pet that needs to be updated * @param name Updated name of the pet * @param status Updated status of the pet * @return Void */ - + @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") Void updatePetWithForm( - @Path("petId") String petId, @Field("name") String name, @Field("status") String status + @Path("petId") Long petId,@Field("name") String name,@Field("status") String status ); + /** + * Updates a pet in the store with form data + * Async method + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param cb callback method + * @return void + */ + + @FormUrlEncoded + @POST("/pet/{petId}") + void updatePetWithForm( + @Path("petId") Long petId,@Field("name") String name,@Field("status") String status, Callback cb + ); + /** * Deletes a pet - * + * Sync method + * * @param petId Pet id to delete - * @param apiKey + * @param apiKey * @return Void */ - - @DELETE("/pet/{petId}") + + @DELETE("/pet/{petId}") Void deletePet( - @Path("petId") Long petId, @Header("api_key") String apiKey + @Path("petId") Long petId,@Header("api_key") String apiKey ); + /** + * Deletes a pet + * Async method + * @param petId Pet id to delete + * @param apiKey + * @param cb callback method + * @return void + */ + + @DELETE("/pet/{petId}") + void deletePet( + @Path("petId") Long petId,@Header("api_key") String apiKey, Callback cb + ); + /** * uploads an image - * + * Sync method + * * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @return Void + * @return ApiResponse */ - + @Multipart - @POST("/pet/{petId}/uploadImage") - Void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file + @POST("/pet/{petId}/uploadImage") + ApiResponse uploadFile( + @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file ); + /** + * uploads an image + * Async method + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param cb callback method + * @return void + */ + + @Multipart + @POST("/pet/{petId}/uploadImage") + void uploadFile( + @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file, Callback cb + ); + } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index fcd47b4b7350..c9944dfc1ffb 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -2,6 +2,7 @@ import io.swagger.client.model.*; +import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; import java.util.*; @@ -13,16 +14,30 @@ public interface StoreApi { /** * Returns pet inventories by status + * Sync method * Returns a map of status codes to quantities * @return Map */ @GET("/store/inventory") Map getInventory(); - + + + /** + * Returns pet inventories by status + * Async method + * @param cb callback method + * @return void + */ + + @GET("/store/inventory") + void getInventory( + Callback> cb + ); /** * Place an order for a pet + * Sync method * * @param body order placed for purchasing the pet * @return Order @@ -31,10 +46,24 @@ public interface StoreApi { @POST("/store/order") Order placeOrder( @Body Order body - ); + ); + + /** + * Place an order for a pet + * Async method + * @param body order placed for purchasing the pet + * @param cb callback method + * @return void + */ + + @POST("/store/order") + void placeOrder( + @Body Order body, Callback cb + ); /** * Find purchase order by ID + * Sync method * 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 Order @@ -42,11 +71,25 @@ Order placeOrder( @GET("/store/order/{orderId}") Order getOrderById( - @Path("orderId") String orderId - ); + @Path("orderId") Long orderId + ); + + /** + * Find purchase order by ID + * Async method + * @param orderId ID of pet that needs to be fetched + * @param cb callback method + * @return void + */ + + @GET("/store/order/{orderId}") + void getOrderById( + @Path("orderId") Long orderId, Callback cb + ); /** * Delete purchase order by ID + * Sync method * 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 Void @@ -55,6 +98,19 @@ Order getOrderById( @DELETE("/store/order/{orderId}") Void deleteOrder( @Path("orderId") String orderId - ); + ); + + /** + * Delete purchase order by ID + * Async method + * @param orderId ID of the order that needs to be deleted + * @param cb callback method + * @return void + */ + + @DELETE("/store/order/{orderId}") + void deleteOrder( + @Path("orderId") String orderId, Callback cb + ); } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java index b80f9e5fa205..b17769c54e72 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -2,6 +2,7 @@ import io.swagger.client.model.*; +import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; import java.util.*; @@ -13,6 +14,7 @@ public interface UserApi { /** * Create user + * Sync method * This can only be done by the logged in user. * @param body Created user object * @return Void @@ -21,10 +23,24 @@ public interface UserApi { @POST("/user") Void createUser( @Body User body - ); + ); + + /** + * Create user + * Async method + * @param body Created user object + * @param cb callback method + * @return void + */ + + @POST("/user") + void createUser( + @Body User body, Callback cb + ); /** * Creates list of users with given input array + * Sync method * * @param body List of user object * @return Void @@ -33,10 +49,24 @@ Void createUser( @POST("/user/createWithArray") Void createUsersWithArrayInput( @Body List body - ); + ); + + /** + * Creates list of users with given input array + * Async method + * @param body List of user object + * @param cb callback method + * @return void + */ + + @POST("/user/createWithArray") + void createUsersWithArrayInput( + @Body List body, Callback cb + ); /** * Creates list of users with given input array + * Sync method * * @param body List of user object * @return Void @@ -45,10 +75,24 @@ Void createUsersWithArrayInput( @POST("/user/createWithList") Void createUsersWithListInput( @Body List body - ); + ); + + /** + * Creates list of users with given input array + * Async method + * @param body List of user object + * @param cb callback method + * @return void + */ + + @POST("/user/createWithList") + void createUsersWithListInput( + @Body List body, Callback cb + ); /** * Logs user into the system + * Sync method * * @param username The user name for login * @param password The password for login in clear text @@ -57,21 +101,49 @@ Void createUsersWithListInput( @GET("/user/login") String loginUser( - @Query("username") String username, @Query("password") String password - ); + @Query("username") String username,@Query("password") String password + ); + + /** + * Logs user into the system + * Async method + * @param username The user name for login + * @param password The password for login in clear text + * @param cb callback method + * @return void + */ + + @GET("/user/login") + void loginUser( + @Query("username") String username,@Query("password") String password, Callback cb + ); /** * Logs out current logged in user session + * Sync method * * @return Void */ @GET("/user/logout") Void logoutUser(); - + + + /** + * Logs out current logged in user session + * Async method + * @param cb callback method + * @return void + */ + + @GET("/user/logout") + void logoutUser( + Callback cb + ); /** * Get user by user name + * Sync method * * @param username The name that needs to be fetched. Use user1 for testing. * @return User @@ -80,10 +152,24 @@ String loginUser( @GET("/user/{username}") User getUserByName( @Path("username") String username - ); + ); + + /** + * Get user by user name + * Async method + * @param username The name that needs to be fetched. Use user1 for testing. + * @param cb callback method + * @return void + */ + + @GET("/user/{username}") + void getUserByName( + @Path("username") String username, Callback cb + ); /** * Updated user + * Sync method * This can only be done by the logged in user. * @param username name that need to be deleted * @param body Updated user object @@ -92,11 +178,26 @@ User getUserByName( @PUT("/user/{username}") Void updateUser( - @Path("username") String username, @Body User body - ); + @Path("username") String username,@Body User body + ); + + /** + * Updated user + * Async method + * @param username name that need to be deleted + * @param body Updated user object + * @param cb callback method + * @return void + */ + + @PUT("/user/{username}") + void updateUser( + @Path("username") String username,@Body User body, Callback cb + ); /** * Delete user + * Sync method * This can only be done by the logged in user. * @param username The name that needs to be deleted * @return Void @@ -105,6 +206,19 @@ Void updateUser( @DELETE("/user/{username}") Void deleteUser( @Path("username") String username - ); + ); + + /** + * Delete user + * Async method + * @param username The name that needs to be deleted + * @param cb callback method + * @return void + */ + + @DELETE("/user/{username}") + void deleteUser( + @Path("username") String username, Callback cb + ); } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java new file mode 100644 index 000000000000..a1292c1d7f14 --- /dev/null +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java @@ -0,0 +1,68 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class ApiKeyAuthorization implements Interceptor { + private final String location; + private final String paramName; + + private String apiKey; + + public ApiKeyAuthorization(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + @Override + public Response intercept(Chain chain) throws IOException { + String paramValue; + Request request = chain.request(); + + if (location == "query") { + String newQuery = request.uri().getQuery(); + paramValue = paramName + "=" + apiKey; + if (newQuery == null) { + newQuery = paramValue; + } else { + newQuery += "&" + paramValue; + } + + URI newUri; + try { + newUri = new URI(request.uri().getScheme(), request.uri().getAuthority(), + request.uri().getPath(), newQuery, request.uri().getFragment()); + } catch (URISyntaxException e) { + throw new IOException(e); + } + + request = request.newBuilder().url(newUri.toURL()).build(); + } else if (location == "header") { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build(); + } + return chain.proceed(request); + } +} \ No newline at end of file diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java new file mode 100644 index 000000000000..80903d49a341 --- /dev/null +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java @@ -0,0 +1,49 @@ +package io.swagger.client.auth; + +import java.io.IOException; + +import com.squareup.okhttp.Credentials; +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; + +public class BasicAuthorization implements Interceptor { + + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public void setCredentials(String username, String password) { + this.username = username; + this.password = password; + } + + @Override + public Response intercept(Chain chain) throws IOException { + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") == null) { + String credentials = Credentials.basic(username, password); + request = request.newBuilder() + .addHeader("Authorization", credentials) + .build(); + } + return chain.proceed(request); + } +} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java new file mode 100644 index 000000000000..01c2d3e09165 --- /dev/null +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java @@ -0,0 +1,148 @@ +package io.swagger.client.auth; + +import static java.net.HttpURLConnection.HTTP_UNAUTHORIZED; + +import java.io.IOException; +import java.util.Map; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import com.squareup.okhttp.Interceptor; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Request.Builder; +import com.squareup.okhttp.Response; + +public class OauthAuthorization implements Interceptor { + + private volatile String accessToken; + private OAuthClient oauthClient; + + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + + public OauthAuthorization( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OauthOkHttpClient(client)); + this.tokenRequestBuilder = requestBuilder; + } + + public OauthAuthorization(TokenRequestBuilder requestBuilder ) { + this(new OkHttpClient(), requestBuilder); + } + + public OauthAuthorization(OauthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public void setFlow(OauthFlow flow) { + switch(flow) { + case accessCode: + case implicit: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) + throws IOException { + + Request request = chain.request(); + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // If first time, get the token + OAuthClientRequest oAuthRequest; + if (getAccessToken() == null) { + updateAccessToken(null); + } + + // Build the request + Builder rb = request.newBuilder(); + + String requestAccessToken = new String(getAccessToken()); + try { + oAuthRequest = new OAuthBearerClientRequest(request.urlString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + for ( Map.Entry header : oAuthRequest.getHeaders().entrySet() ) { + rb.addHeader(header.getKey(), header.getValue()); + } + rb.url( oAuthRequest.getLocationUri()); + + //Execute the request + Response response = chain.proceed(rb.build()); + + // 401 most likely indicates that access token has expired. + // Time to refresh and resend the request + if ( response.code() == HTTP_UNAUTHORIZED ) { + updateAccessToken(requestAccessToken); + return intercept( chain ); + } + return response; + } + + public synchronized void updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse; + accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()); + setAccessToken(accessTokenResponse.getAccessToken()); + } catch (OAuthSystemException e) { + throw new IOException(e); + } catch (OAuthProblemException e) { + throw new IOException(e); + } + } + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public AuthenticationRequestBuilder getAuthenticationRequestBuilder() { + return authenticationRequestBuilder; + } + + public void setAuthenticationRequestBuilder(AuthenticationRequestBuilder authenticationRequestBuilder) { + this.authenticationRequestBuilder = authenticationRequestBuilder; + } + +} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java new file mode 100644 index 000000000000..ba0a8f39f35c --- /dev/null +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java @@ -0,0 +1,5 @@ +package io.swagger.client.auth; + +public enum OauthFlow { + accessCode, implicit, password, application +} \ No newline at end of file diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java new file mode 100644 index 000000000000..a66bec0b1584 --- /dev/null +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java @@ -0,0 +1,69 @@ +package io.swagger.client.auth; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.Response; + + +public class OauthOkHttpClient implements HttpClient { + + private OkHttpClient client; + + public OauthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OauthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(mediaType, request.getBody()) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + public void shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java new file mode 100644 index 000000000000..a929a54dc81f --- /dev/null +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java @@ -0,0 +1,63 @@ +package io.swagger.client.model; + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + +@ApiModel(description = "") +public class ApiResponse { + + + /** + **/ + @ApiModelProperty(value = "") + @SerializedName("code") + private Integer code = null; + + /** + **/ + @ApiModelProperty(value = "") + @SerializedName("type") + private String type = null; + + /** + **/ + @ApiModelProperty(value = "") + @SerializedName("message") + private String message = null; + + + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + 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/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java index 7d1368a74e0a..f74264708e35 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -1,8 +1,8 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java index e7613f189a3a..d015095b5c95 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -22,7 +22,7 @@ public class PetApiTest { @Before public void setup() { - api = ServiceGenerator.createService(PetApi.class); + api = new ServiceGenerator().createService(PetApi.class); } @Test @@ -108,7 +108,7 @@ public void testUpdatePetWithForm() throws Exception { Pet fetched = api.getPetById(pet.getId()); - api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + api.updatePetWithForm(fetched.getId(), "furt", null); Pet updated = api.getPetById(fetched.getId()); assertEquals(updated.getName(), "furt"); diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 3b406cac0b5e..629a24cc7755 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -16,7 +16,7 @@ public class StoreApiTest { @Before public void setup() { - api = ServiceGenerator.createService(StoreApi.class); + api = new ServiceGenerator().createService(StoreApi.class); } @Test @@ -30,7 +30,7 @@ public void testPlaceOrder() throws Exception { Order order = createOrder(); api.placeOrder(order); - Order fetched = api.getOrderById(String.valueOf(order.getId())); + Order fetched = api.getOrderById(order.getId()); assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); @@ -41,13 +41,13 @@ public void testDeleteOrder() throws Exception { Order order = createOrder(); api.placeOrder(order); - Order fetched = api.getOrderById(String.valueOf(order.getId())); + Order fetched = api.getOrderById(order.getId()); assertEquals(fetched.getId(), order.getId()); api.deleteOrder(String.valueOf(order.getId())); try { - api.getOrderById(String.valueOf(order.getId())); + api.getOrderById(order.getId()); // fail("expected an error"); } catch (RetrofitError e) { // ok diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java index 6613f0c03add..45a5f1160e10 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -15,7 +15,7 @@ public class UserApiTest { @Before public void setup() { - api = ServiceGenerator.createService(UserApi.class); + api = new ServiceGenerator().createService(UserApi.class); } @Test From a207251b292b947c38a9e187840a7f3c60d0d231 Mon Sep 17 00:00:00 2001 From: cbornet Date: Sat, 29 Aug 2015 18:41:16 +0200 Subject: [PATCH 029/219] minor changes removed gson version in pom and added a space between the parameters --- .../src/main/resources/retrofit/api.mustache | 4 ++-- .../src/main/resources/retrofit/pom.mustache | 2 -- samples/client/petstore/retrofit/pom.xml | 2 -- .../src/main/java/io/swagger/client/api/PetApi.java | 12 ++++++------ .../main/java/io/swagger/client/api/StoreApi.java | 2 +- .../src/main/java/io/swagger/client/api/UserApi.java | 10 +++++----- 6 files changed, 14 insertions(+), 18 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache index 9d3094e38bd3..db4a997196fd 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/api.mustache @@ -24,7 +24,7 @@ public interface {{classname}} { {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}},{{/hasMore}}{{^hasMore}} + {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} /** @@ -38,7 +38,7 @@ public interface {{classname}} { {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") void {{nickname}}( - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}},{{/allParams}} Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb + {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb ); {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache index 8ed9335b4eea..651c9bd6a641 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache @@ -121,7 +121,6 @@ org.apache.oltu.oauth2 org.apache.oltu.oauth2.client ${oltu-version} - compile com.squareup.okhttp @@ -139,7 +138,6 @@ 1.5.0 - 2.3.1 1.9.0 2.4.0 1.0.0 diff --git a/samples/client/petstore/retrofit/pom.xml b/samples/client/petstore/retrofit/pom.xml index 0c090b0b85ea..bcbfdbf797db 100644 --- a/samples/client/petstore/retrofit/pom.xml +++ b/samples/client/petstore/retrofit/pom.xml @@ -121,7 +121,6 @@ org.apache.oltu.oauth2 org.apache.oltu.oauth2.client ${oltu-version} - compile com.squareup.okhttp @@ -139,7 +138,6 @@ 1.5.0 - 2.3.1 1.9.0 2.4.0 1.0.0 diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java index dd485d7dcefb..5efddc75dc40 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -156,7 +156,7 @@ void getPetById( @FormUrlEncoded @POST("/pet/{petId}") Void updatePetWithForm( - @Path("petId") Long petId,@Field("name") String name,@Field("status") String status + @Path("petId") Long petId, @Field("name") String name, @Field("status") String status ); /** @@ -172,7 +172,7 @@ Void updatePetWithForm( @FormUrlEncoded @POST("/pet/{petId}") void updatePetWithForm( - @Path("petId") Long petId,@Field("name") String name,@Field("status") String status, Callback cb + @Path("petId") Long petId, @Field("name") String name, @Field("status") String status, Callback cb ); /** @@ -186,7 +186,7 @@ void updatePetWithForm( @DELETE("/pet/{petId}") Void deletePet( - @Path("petId") Long petId,@Header("api_key") String apiKey + @Path("petId") Long petId, @Header("api_key") String apiKey ); /** @@ -200,7 +200,7 @@ Void deletePet( @DELETE("/pet/{petId}") void deletePet( - @Path("petId") Long petId,@Header("api_key") String apiKey, Callback cb + @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb ); /** @@ -216,7 +216,7 @@ void deletePet( @Multipart @POST("/pet/{petId}/uploadImage") ApiResponse uploadFile( - @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file ); /** @@ -232,7 +232,7 @@ ApiResponse uploadFile( @Multipart @POST("/pet/{petId}/uploadImage") void uploadFile( - @Path("petId") Long petId,@Part("additionalMetadata") String additionalMetadata,@Part("file") TypedFile file, Callback cb + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb ); } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index c9944dfc1ffb..9fecd5c98d0e 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -32,7 +32,7 @@ public interface StoreApi { @GET("/store/inventory") void getInventory( - Callback> cb + Callback> cb ); /** diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java index b17769c54e72..c74265f53fd8 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -101,7 +101,7 @@ void createUsersWithListInput( @GET("/user/login") String loginUser( - @Query("username") String username,@Query("password") String password + @Query("username") String username, @Query("password") String password ); /** @@ -115,7 +115,7 @@ String loginUser( @GET("/user/login") void loginUser( - @Query("username") String username,@Query("password") String password, Callback cb + @Query("username") String username, @Query("password") String password, Callback cb ); /** @@ -138,7 +138,7 @@ void loginUser( @GET("/user/logout") void logoutUser( - Callback cb + Callback cb ); /** @@ -178,7 +178,7 @@ void getUserByName( @PUT("/user/{username}") Void updateUser( - @Path("username") String username,@Body User body + @Path("username") String username, @Body User body ); /** @@ -192,7 +192,7 @@ Void updateUser( @PUT("/user/{username}") void updateUser( - @Path("username") String username,@Body User body, Callback cb + @Path("username") String username, @Body User body, Callback cb ); /** From 3c84847adbdd6cde13286994e1c0ed12c165d0c4 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 31 Aug 2015 18:42:09 +0800 Subject: [PATCH 030/219] Add a new library template to Java client: okhttp-gson which uses OkHttp as HTTP library and Gson as JSON processing library --- bin/java-petstore-okhttp-gson.json | 4 + bin/java-petstore-okhttp-gson.sh | 31 + .../codegen/languages/JavaClientCodegen.java | 11 +- .../main/resources/Java/StringUtil.mustache | 9 + .../main/resources/Java/apiException.mustache | 37 +- .../okhttp-gson/ApiCallback.mustache | 22 + .../libraries/okhttp-gson/ApiClient.mustache | 762 ++++++++++++++++++ .../Java/libraries/okhttp-gson/JSON.mustache | 102 +++ .../Java/libraries/okhttp-gson/api.mustache | 116 +++ .../libraries/okhttp-gson/enumClass.mustache | 17 + .../Java/libraries/okhttp-gson/model.mustache | 58 ++ .../Java/libraries/okhttp-gson/pom.mustache | 146 ++++ .../src/main/resources/Java/model.mustache | 7 +- 13 files changed, 1310 insertions(+), 12 deletions(-) create mode 100644 bin/java-petstore-okhttp-gson.json create mode 100755 bin/java-petstore-okhttp-gson.sh create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache diff --git a/bin/java-petstore-okhttp-gson.json b/bin/java-petstore-okhttp-gson.json new file mode 100644 index 000000000000..b894d1726305 --- /dev/null +++ b/bin/java-petstore-okhttp-gson.json @@ -0,0 +1,4 @@ +{ + "library": "okhttp-gson", + "artifactId": "swagger-petstore-okhttp-gson" +} diff --git a/bin/java-petstore-okhttp-gson.sh b/bin/java-petstore-okhttp-gson.sh new file mode 100755 index 000000000000..17a48ddee53a --- /dev/null +++ b/bin/java-petstore-okhttp-gson.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-okhttp-gson.json -o samples/client/petstore/java/okhttp-gson" + +java $JAVA_OPTS -jar $executable $ags 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 aad744dd1ce4..eab4dffa8e30 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 @@ -83,6 +83,7 @@ public JavaClientCodegen() { supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); + supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); cliOptions.add(buildLibraryCliOption(supportedLibraries)); } @@ -159,7 +160,15 @@ public void processOpts() { supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); + + // library-specific files + if ("okhttp-gson".equals(getLibrary())) { + // the "okhttp-gson" library template requires "ApiCallback.mustache" + // and does not require "TypeRef.mustache" + supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); + } else { + supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); + } final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache index 073966b0c217..c9583f1bc636 100644 --- a/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/StringUtil.mustache @@ -39,4 +39,13 @@ public class StringUtil { } return out.toString(); } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } } diff --git a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache index bb3b53b0aeb2..b9a62a6b231d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiException.mustache @@ -6,20 +6,45 @@ import java.util.List; {{>generatedAnnotation}} public class ApiException extends Exception { private int code = 0; - private String message = null; private Map> responseHeaders = null; private String responseBody = null; public ApiException() {} + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + public ApiException(int code, String message) { + super(message); this.code = code; - this.message = message; } public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this.code = code; - this.message = message; + this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } @@ -28,10 +53,6 @@ public class ApiException extends Exception { return code; } - public String getMessage() { - return message; - } - /** * Get the HTTP response headers. */ diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache new file mode 100644 index 000000000000..4af16c9faa90 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache @@ -0,0 +1,22 @@ +package {{invokerPackage}}; + +import java.io.IOException; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + */ + void onFailure(ApiException e); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + */ + void onSuccess(T result); +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache new file mode 100644 index 000000000000..069aa273b142 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -0,0 +1,762 @@ +package {{invokerPackage}}; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; + +public class ApiClient { + private String basePath = "{{basePath}}"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + + private Map authentications; + + private String dateFormat; + private DateFormat dateFormatter; + private int dateLength; + + private String datetimeFormat; + private DateFormat datetimeFormatter; + + private OkHttpClient httpClient; + private JSON json; + + public ApiClient() { + httpClient = new OkHttpClient(); + + json = new JSON(this); + + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + setDateFormat("yyyy-MM-dd"); + setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public OkHttpClient getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public JSON getJSON() { + return json; + } + + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + public String getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + + this.dateFormatter = new SimpleDateFormat(dateFormat); + // Use UTC as the default time zone. + this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.dateLength = this.dateFormatter.format(new Date()).length(); + + return this; + } + + public String getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(String datetimeFormat) { + this.datetimeFormat = datetimeFormat; + + this.datetimeFormatter = new SimpleDateFormat(datetimeFormat); + // Note: The datetime formatter uses the system's default time zone. + + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given date-time string into Date object. + * The default datetimeFormat supports these ISO 8601 datetime formats: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) { + /* + * When the default datetime format is used, process the given string + * to support various formats defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + } + + try { + return datetimeFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormatter.format(date); + } + + /** + * Format the given Date object into string. + */ + public String formatDatetime(Date date) { + return datetimeFormatter.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according the Content-Type + * response header. + * + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) + return null; + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) + return null; + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (contentType.startsWith("application/json")) { + return json.deserialize(respBody, returnType); + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported", + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body string, according to the + * request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized string + */ + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + if (obj != null) + return json.serialize(obj); + else + return null; + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * @see #execute(Call, Type) + */ + public T execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @return The Java object deserialized from response body. Returns null if returnType is null. + */ + public T execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + return handleResponse(response, returnType); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * #see executeAsync(Call, Type, ApiCallback) + */ + public void executeAsync(Call call, ApiCallback callback) throws ApiException { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param The callback to be executed when the API call finishes + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e)); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e); + return; + } + callback.onSuccess(result); + } + }); + } + + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @return The HTTP call + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) contentType = "application/json"; + + RequestBody reqBody; + if ("GET".equals(method) || "HEAD".equals(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); + } + + Request request; + if ("GET".equals(method)) { + request = reqBuilder.get().build(); + } else if ("HEAD".equals(method)) { + request = reqBuilder.head().build(); + } else if ("POST".equals(method)) { + request = reqBuilder.post(reqBody).build(); + } else if ("PUT".equals(method)) { + request = reqBuilder.put(reqBody).build(); + } else if ("PATCH".equals(method)) { + request = reqBuilder.patch(reqBody).build(); + } else if ("DELETE".equals(method)) { + if (reqBody == null) { + // calling DELETE without sending a request body + request = reqBuilder.delete().build(); + } else { + request = reqBuilder.delete(reqBody).build(); + } + } else { + throw new ApiException("unknown method type: " + method); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + StringBuilder query = new StringBuilder(); + if (queryParams != null) { + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (query.toString().length() == 0) + query.append("?"); + else + query.append("&"); + String value = parameterToString(param.getValue()); + query.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + return basePath + path + query.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The Content-Type guessed + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache new file mode 100644 index 000000000000..10a43d97de07 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/JSON.mustache @@ -0,0 +1,102 @@ +package {{invokerPackage}}; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.stream.JsonReader; + +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .serializeNulls() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .create(); + } + + public Gson getGson() { + return gson; + } + + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache new file mode 100644 index 000000000000..b272687c7fde --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -0,0 +1,116 @@ +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; + +import {{modelPackage}}.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /* Build call for {{nickname}} */ + private Call {{nickname}}Call({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{nickname}}(Async)"); + } + {{/required}}{{/allParams}} + + // create path and map variables + String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + List {{localVariablePrefix}}queryParams = new ArrayList();{{#queryParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} + + Map {{localVariablePrefix}}headerParams = new HashMap();{{#headerParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} + + Map {{localVariablePrefix}}formParams = new HashMap();{{#formParams}} + if ({{paramName}} != null) + {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}} + + final String[] {{localVariablePrefix}}accepts = { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}accept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}accepts); + if ({{localVariablePrefix}}accept != null) {{localVariablePrefix}}headerParams.put("Accept", {{localVariablePrefix}}accept); + + final String[] {{localVariablePrefix}}contentTypes = { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); + {{localVariablePrefix}}headerParams.put("Content-Type", {{localVariablePrefix}}contentType); + + String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + return {{localVariablePrefix}}apiClient.buildCall({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}authNames); + } + + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}}{{#returnType}} + * @return {{{returnType}}}{{/returnType}} + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return {{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call, {{localVariablePrefix}}returnType);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.execute({{localVariablePrefix}}call);{{/returnType}} + } + + /** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{/allParams}} + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call {{nickname}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}ApiCallback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{localVariablePrefix}}callback) throws ApiException { + Call {{localVariablePrefix}}call = {{nickname}}Call({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{#returnType}}Type {{localVariablePrefix}}returnType = new TypeToken<{{{returnType}}}>(){}.getType(); + {{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}returnType, {{localVariablePrefix}}callback);{{/returnType}}{{^returnType}}{{localVariablePrefix}}apiClient.executeAsync({{localVariablePrefix}}call, {{localVariablePrefix}}callback);{{/returnType}} + return {{localVariablePrefix}}call; + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache new file mode 100644 index 000000000000..cc00e9d392ee --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache @@ -0,0 +1,17 @@ +public enum {{datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}}@SerializedName("{{value}}") + {{name}}("{{value}}"){{^-last}}, + + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache new file mode 100644 index 000000000000..0987aa68f34e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/model.mustache @@ -0,0 +1,58 @@ +package {{package}}; + +import {{invokerPackage}}.StringUtil; +{{#imports}}import {{import}}; +{{/imports}} + +import com.google.gson.annotations.SerializedName; + +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + +import io.swagger.annotations.*; + +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache new file mode 100644 index 000000000000..67fc10e8323d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -0,0 +1,146 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.4.0 + 2.3.1 + 1.0.0 + 4.8.1 + + diff --git a/modules/swagger-codegen/src/main/resources/Java/model.mustache b/modules/swagger-codegen/src/main/resources/Java/model.mustache index bfb65a3d4195..f5e48ba997fd 100644 --- a/modules/swagger-codegen/src/main/resources/Java/model.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/model.mustache @@ -1,5 +1,6 @@ package {{package}}; +import {{invokerPackage}}.StringUtil; {{#imports}}import {{import}}; {{/imports}} @@ -45,9 +46,9 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}}sb.append("}\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); return sb.toString(); } } From e35be1bd40e6188b575bc66a7a1bac6077e168e8 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 31 Aug 2015 19:59:17 +0800 Subject: [PATCH 031/219] Generate Java petstore sample for okhttp-gson --- bin/all-petstore.sh | 1 + pom.xml | 13 + .../petstore/java/okhttp-gson/hello.txt | 1 + .../client/petstore/java/okhttp-gson/pom.xml | 146 ++++ .../java/io/swagger/client/ApiCallback.java | 22 + .../java/io/swagger/client/ApiClient.java | 761 ++++++++++++++++++ .../java/io/swagger/client/ApiException.java | 69 ++ .../java/io/swagger/client/Configuration.java | 22 + .../src/main/java/io/swagger/client/JSON.java | 102 +++ .../src/main/java/io/swagger/client/Pair.java | 39 + .../java/io/swagger/client/StringUtil.java | 51 ++ .../java/io/swagger/client/api/PetApi.java | 527 ++++++++++++ .../java/io/swagger/client/api/StoreApi.java | 277 +++++++ .../java/io/swagger/client/api/UserApi.java | 500 ++++++++++++ .../io/swagger/client/auth/ApiKeyAuth.java | 59 ++ .../swagger/client/auth/Authentication.java | 12 + .../io/swagger/client/auth/HttpBasicAuth.java | 41 + .../java/io/swagger/client/auth/OAuth.java | 14 + .../io/swagger/client/model/Category.java | 57 ++ .../java/io/swagger/client/model/Order.java | 142 ++++ .../java/io/swagger/client/model/Pet.java | 144 ++++ .../java/io/swagger/client/model/Tag.java | 57 ++ .../java/io/swagger/client/model/User.java | 148 ++++ .../java/io/swagger/client/ApiClientTest.java | 193 +++++ .../io/swagger/client/ConfigurationTest.java | 15 + .../io/swagger/client/StringUtilTest.java | 33 + .../swagger/client/auth/ApiKeyAuthTest.java | 47 ++ .../client/auth/HttpBasicAuthTest.java | 52 ++ .../io/swagger/petstore/test/PetApiTest.java | 192 +++++ .../swagger/petstore/test/StoreApiTest.java | 72 ++ .../io/swagger/petstore/test/UserApiTest.java | 86 ++ 31 files changed, 3895 insertions(+) create mode 100644 samples/client/petstore/java/okhttp-gson/hello.txt create mode 100644 samples/client/petstore/java/okhttp-gson/pom.xml create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 23c2935ed2ae..5b044167e7b6 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -25,6 +25,7 @@ cd $APP_DIR ./bin/html-petstore.sh ./bin/java-petstore.sh ./bin/java-petstore-jersey2.sh +./bin/java-petstore-okhttp-gson.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh diff --git a/pom.xml b/pom.xml index 2ff111c57452..2d96cb5a760a 100644 --- a/pom.xml +++ b/pom.xml @@ -328,6 +328,18 @@ samples/client/petstore/java/jersey2 + + java-client-okhttp-gson + + + env + java + + + + samples/client/petstore/java/okhttp-gson + + scala-client @@ -412,6 +424,7 @@ samples/client/petstore/android-java samples/client/petstore/java/default samples/client/petstore/java/jersey2 + samples/client/petstore/java/okhttp-gson samples/client/petstore/scala samples/server/petstore/spring-mvc diff --git a/samples/client/petstore/java/okhttp-gson/hello.txt b/samples/client/petstore/java/okhttp-gson/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml new file mode 100644 index 000000000000..2442e1c318e8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -0,0 +1,146 @@ + + 4.0.0 + io.swagger + swagger-petstore-okhttp-gson + jar + swagger-petstore-okhttp-gson + 1.0.0 + + scm:git:git@github.com:swagger-api/swagger-mustache.git + scm:git:git@github.com:swagger-api/swagger-codegen.git + https://github.com/swagger-api/swagger-codegen + + + 2.2.0 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + + + + + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + + + com.squareup.okhttp + okhttp + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + com.brsanthu + migbase64 + 2.2 + + + + + junit + junit + ${junit-version} + test + + + + 1.5.0 + 2.4.0 + 2.3.1 + 1.0.0 + 4.8.1 + + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java new file mode 100644 index 000000000000..f8254311bce8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +import java.io.IOException; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + */ + void onFailure(ApiException e); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + */ + void onSuccess(T result); +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java new file mode 100644 index 000000000000..f189ea102384 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -0,0 +1,761 @@ +package io.swagger.client; + +import com.squareup.okhttp.Call; +import com.squareup.okhttp.Callback; +import com.squareup.okhttp.OkHttpClient; +import com.squareup.okhttp.Request; +import com.squareup.okhttp.Response; +import com.squareup.okhttp.RequestBody; +import com.squareup.okhttp.FormEncodingBuilder; +import com.squareup.okhttp.MultipartBuilder; +import com.squareup.okhttp.MediaType; +import com.squareup.okhttp.Headers; + +import java.lang.reflect.Type; + +import java.util.Collection; +import java.util.Collections; +import java.util.Map; +import java.util.Map.Entry; +import java.util.HashMap; +import java.util.List; +import java.util.ArrayList; +import java.util.Date; +import java.util.TimeZone; +import java.util.regex.Pattern; + +import java.net.URLEncoder; +import java.net.URLConnection; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; + +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.text.ParseException; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; + +public class ApiClient { + private String basePath = "http://petstore.swagger.io/v2"; + private boolean lenientOnJson = false; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + + private Map authentications; + + private String dateFormat; + private DateFormat dateFormatter; + private int dateLength; + + private String datetimeFormat; + private DateFormat datetimeFormatter; + + private OkHttpClient httpClient; + private JSON json; + + public ApiClient() { + httpClient = new OkHttpClient(); + + json = new JSON(this); + + // Use ISO 8601 format for date and datetime. + // See https://en.wikipedia.org/wiki/ISO_8601 + setDateFormat("yyyy-MM-dd"); + setDatetimeFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + // Set default User-Agent. + setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + public OkHttpClient getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(OkHttpClient httpClient) { + this.httpClient = httpClient; + return this; + } + + public JSON getJSON() { + return json; + } + + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + public String getDateFormat() { + return dateFormat; + } + + public ApiClient setDateFormat(String dateFormat) { + this.dateFormat = dateFormat; + + this.dateFormatter = new SimpleDateFormat(dateFormat); + // Use UTC as the default time zone. + this.dateFormatter.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.dateLength = this.dateFormatter.format(new Date()).length(); + + return this; + } + + public String getDatetimeFormat() { + return datetimeFormat; + } + + public ApiClient setDatetimeFormat(String datetimeFormat) { + this.datetimeFormat = datetimeFormat; + + this.datetimeFormatter = new SimpleDateFormat(datetimeFormat); + // Note: The datetime formatter uses the system's default time zone. + + return this; + } + + /** + * Parse the given date string into Date object. + * The default dateFormat supports these ISO 8601 date formats: + * 2015-08-16 + * 2015-8-16 + */ + public Date parseDate(String str) { + if (str == null) + return null; + try { + return dateFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Parse the given date-time string into Date object. + * The default datetimeFormat supports these ISO 8601 datetime formats: + * 2015-08-16T08:20:05Z + * 2015-8-16T8:20:05Z + * 2015-08-16T08:20:05+00:00 + * 2015-08-16T08:20:05+0000 + * 2015-08-16T08:20:05.376Z + * 2015-08-16T08:20:05.376+00:00 + * 2015-08-16T08:20:05.376+00 + * Note: The 3-digit milli-seconds is optional. Time zone is required and can be in one of + * these formats: + * Z (same with +0000) + * +08:00 (same with +0800) + * -02 (same with -0200) + * -0200 + * @see https://en.wikipedia.org/wiki/ISO_8601 + */ + public Date parseDatetime(String str) { + if (str == null) + return null; + + if ("yyyy-MM-dd'T'HH:mm:ss.SSSZ".equals(datetimeFormat)) { + /* + * When the default datetime format is used, process the given string + * to support various formats defined by ISO 8601. + */ + // normalize time zone + // trailing "Z": 2015-08-16T08:20:05Z => 2015-08-16T08:20:05+0000 + str = str.replaceAll("[zZ]\\z", "+0000"); + // remove colon: 2015-08-16T08:20:05+00:00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2}):(\\d{2})\\z", "$1$2"); + // expand time zone: 2015-08-16T08:20:05+00 => 2015-08-16T08:20:05+0000 + str = str.replaceAll("([+-]\\d{2})\\z", "$100"); + // add milliseconds when missing + // 2015-08-16T08:20:05+0000 => 2015-08-16T08:20:05.000+0000 + str = str.replaceAll("(:\\d{1,2})([+-]\\d{4})\\z", "$1.000$2"); + } + + try { + return datetimeFormatter.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + public Date parseDateOrDatetime(String str) { + if (str == null) + return null; + else if (str.length() <= dateLength) + return parseDate(str); + else + return parseDatetime(str); + } + + /** + * Format the given Date object into string. + */ + public String formatDate(Date date) { + return dateFormatter.format(date); + } + + /** + * Format the given Date object into string. + */ + public String formatDatetime(Date date) { + return datetimeFormatter.format(date); + } + + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * @see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + */ + public boolean isLenientOnJson() { + return lenientOnJson; + } + + public ApiClient setLenientOnJson(boolean lenient) { + this.lenientOnJson = lenient; + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + return this; + } + + /** + * Format the given parameter object into string. + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDatetime((Date) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection)param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) return null; + if (StringUtil.containsIgnoreCase(accepts, "application/json")) return "application/json"; + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) return "application/json"; + if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according the Content-Type + * response header. + * + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + */ + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) + return null; + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) + return null; + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (contentType.startsWith("application/json")) { + return json.deserialize(respBody, returnType); + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported", + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body string, according to the + * request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized string + */ + public String serialize(Object obj, String contentType) throws ApiException { + if (contentType.startsWith("application/json")) { + if (obj != null) + return json.serialize(obj); + else + return null; + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * @see #execute(Call, Type) + */ + public T execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @return The Java object deserialized from response body. Returns null if returnType is null. + */ + public T execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + return handleResponse(response, returnType); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * #see executeAsync(Call, Type, ApiCallback) + */ + public void executeAsync(Call call, ApiCallback callback) throws ApiException { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @see #execute(Call, Type) + * @param The callback to be executed when the API call finishes + */ + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Request request, IOException e) { + callback.onFailure(new ApiException(e)); + } + + @Override + public void onResponse(Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e); + return; + } + callback.onSuccess(result); + } + }); + } + + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @return The HTTP call + */ + public Call buildCall(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String[] authNames) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams); + + final String url = buildUrl(path, queryParams); + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + + String contentType = (String) headerParams.get("Content-Type"); + // ensuring a default content type + if (contentType == null) contentType = "application/json"; + + RequestBody reqBody; + if ("GET".equals(method) || "HEAD".equals(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create(MediaType.parse(contentType), ""); + } + } else { + reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); + } + + Request request; + if ("GET".equals(method)) { + request = reqBuilder.get().build(); + } else if ("HEAD".equals(method)) { + request = reqBuilder.head().build(); + } else if ("POST".equals(method)) { + request = reqBuilder.post(reqBody).build(); + } else if ("PUT".equals(method)) { + request = reqBuilder.put(reqBody).build(); + } else if ("PATCH".equals(method)) { + request = reqBuilder.patch(reqBody).build(); + } else if ("DELETE".equals(method)) { + if (reqBody == null) { + // calling DELETE without sending a request body + request = reqBuilder.delete().build(); + } else { + request = reqBuilder.delete(reqBody).build(); + } + } else { + throw new ApiException("unknown method type: " + method); + } + + return httpClient.newCall(request); + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams) { + StringBuilder query = new StringBuilder(); + if (queryParams != null) { + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (query.toString().length() == 0) + query.append("?"); + else + query.append("&"); + String value = parameterToString(param.getValue()); + query.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + return basePath + path + query.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + FormEncodingBuilder formBuilder = new FormEncodingBuilder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBuilder mpBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(mediaType, file)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(null, parameterToString(param.getValue()))); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The Content-Type guessed + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java new file mode 100644 index 000000000000..d19aa8ebb3a4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -0,0 +1,69 @@ +package io.swagger.client; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + */ + public String getResponseBody() { + return responseBody; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 000000000000..07c97e116d7e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,22 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class Configuration { + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java new file mode 100644 index 000000000000..f88639b9c82d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/JSON.java @@ -0,0 +1,102 @@ +package io.swagger.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonNull; +import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.stream.JsonReader; + +import java.io.StringReader; +import java.lang.reflect.Type; +import java.util.Date; + +public class JSON { + private ApiClient apiClient; + private Gson gson; + + public JSON(ApiClient apiClient) { + this.apiClient = apiClient; + gson = new GsonBuilder() + .serializeNulls() + .registerTypeAdapter(Date.class, new DateAdapter(apiClient)) + .create(); + } + + public Gson getGson() { + return gson; + } + + public void setGson(Gson gson) { + this.gson = gson; + } + + /** + * Serialize the given Java object into JSON string. + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param body The JSON string + * @param returnType The type to deserialize inot + * @return The deserialized Java object + */ + public T deserialize(String body, Type returnType) { + try { + if (apiClient.isLenientOnJson()) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + // parse response body into date or datetime for the Date return type. + if (returnType.equals(String.class)) + return (T) body; + else if (returnType.equals(Date.class)) + return (T) apiClient.parseDateOrDatetime(body); + else throw(e); + } + } +} + +class DateAdapter implements JsonSerializer, JsonDeserializer { + private final ApiClient apiClient; + + public DateAdapter(ApiClient apiClient) { + super(); + this.apiClient = apiClient; + } + + @Override + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + if (src == null) { + return JsonNull.INSTANCE; + } else { + return new JsonPrimitive(apiClient.formatDatetime(src)); + } + } + + @Override + public Date deserialize(JsonElement json, Type date, JsonDeserializationContext context) throws JsonParseException { + String str = json.getAsJsonPrimitive().getAsString(); + try { + return apiClient.parseDateOrDatetime(str); + } catch (RuntimeException e) { + throw new JsonParseException(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java new file mode 100644 index 000000000000..bb0cd8237915 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -0,0 +1,39 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) return; + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) return; + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) return false; + if (arg.trim().isEmpty()) return false; + + return true; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 000000000000..9a58d6d5558f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java new file mode 100644 index 000000000000..debe576dc9dc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -0,0 +1,527 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import io.swagger.client.model.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +import io.swagger.client.model.Pet; +import java.io.File; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +public class PetApi { + private ApiClient apiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /* Build call for updatePet */ + private Call updatePetCall(Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + */ + public void updatePet(Pet body) throws ApiException { + Call call = updatePetCall(body); + apiClient.execute(call); + } + + /** + * Update an existing pet (asynchronously) + * + * @param body Pet object that needs to be added to the store + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call updatePetAsync(Pet body, ApiCallback callback) throws ApiException { + Call call = updatePetCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for addPet */ + private Call addPetCall(Pet body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/json", "application/xml" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + */ + public void addPet(Pet body) throws ApiException { + Call call = addPetCall(body); + apiClient.execute(call); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param body Pet object that needs to be added to the store + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call addPetAsync(Pet body, ApiCallback callback) throws ApiException { + Call call = addPetCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for findPetsByStatus */ + private Call findPetsByStatusCall(List status) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + if (status != null) + queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * 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 List + */ + public List findPetsByStatus(List status) throws ApiException { + Call call = findPetsByStatusCall(status); + Type returnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma seperated strings + * @param status Status values that need to be considered for filter + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call findPetsByStatusAsync(List status, ApiCallback> callback) throws ApiException { + Call call = findPetsByStatusCall(status); + Type returnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for findPetsByTags */ + private Call findPetsByTagsCall(List tags) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + if (tags != null) + queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * 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 List + */ + public List findPetsByTags(List tags) throws ApiException { + Call call = findPetsByTagsCall(tags); + Type returnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call findPetsByTagsAsync(List tags, ApiCallback> callback) throws ApiException { + Call call = findPetsByTagsCall(tags); + Type returnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for getPetById */ + private Call getPetByIdCall(Long petId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth", "api_key" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Find pet by ID + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched + * @return Pet + */ + public Pet getPetById(Long petId) throws ApiException { + Call call = getPetByIdCall(petId); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Find pet by ID (asynchronously) + * 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 + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getPetByIdAsync(Long petId, ApiCallback callback) throws ApiException { + Call call = getPetByIdCall(petId); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for updatePetWithForm */ + private Call updatePetWithFormCall(String petId, String name, String status) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + if (name != null) + formParams.put("name", name); + if (status != null) + formParams.put("status", status); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "application/x-www-form-urlencoded" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * 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 + */ + public void updatePetWithForm(String petId, String name, String status) throws ApiException { + Call call = updatePetWithFormCall(petId, name, status); + apiClient.execute(call); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call updatePetWithFormAsync(String petId, String name, String status, ApiCallback callback) throws ApiException { + Call call = updatePetWithFormCall(petId, name, status); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for deletePet */ + private Call deletePetCall(Long petId, String apiKey) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + if (apiKey != null) + headerParams.put("api_key", apiClient.parameterToString(apiKey)); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + Call call = deletePetCall(petId, apiKey); + apiClient.execute(call); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete + * @param apiKey + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call deletePetAsync(Long petId, String apiKey, ApiCallback callback) throws ApiException { + Call call = deletePetCall(petId, apiKey); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for uploadFile */ + private Call uploadFileCall(Long petId, String additionalMetadata, File file) throws ApiException { + Object postBody = null; + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + if (additionalMetadata != null) + formParams.put("additionalMetadata", additionalMetadata); + if (file != null) + formParams.put("file", file); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + "multipart/form-data" + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "petstore_auth" }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + public void uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + Call call = uploadFileCall(petId, additionalMetadata, file); + apiClient.execute(call); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call uploadFileAsync(Long petId, String additionalMetadata, File file, ApiCallback callback) throws ApiException { + Call call = uploadFileCall(petId, additionalMetadata, file); + apiClient.executeAsync(call, callback); + return call; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java new file mode 100644 index 000000000000..a3fb14bb5210 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -0,0 +1,277 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import io.swagger.client.model.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +import java.util.Map; +import io.swagger.client.model.Order; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +public class StoreApi { + private ApiClient apiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /* Build call for getInventory */ + private Call getInventoryCall() throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { "api_key" }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map + */ + public Map getInventory() throws ApiException { + Call call = getInventoryCall(); + Type returnType = new TypeToken>(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getInventoryAsync(ApiCallback> callback) throws ApiException { + Call call = getInventoryCall(); + Type returnType = new TypeToken>(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for placeOrder */ + private Call placeOrderCall(Order body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/store/order".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + public Order placeOrder(Order body) throws ApiException { + Call call = placeOrderCall(body); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param body order placed for purchasing the pet + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call placeOrderAsync(Order body, ApiCallback callback) throws ApiException { + Call call = placeOrderCall(body); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for getOrderById */ + private Call getOrderByIdCall(String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * 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 Order + */ + public Order getOrderById(String orderId) throws ApiException { + Call call = getOrderByIdCall(orderId); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Find purchase order by ID (asynchronously) + * 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 + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getOrderByIdAsync(String orderId, ApiCallback callback) throws ApiException { + Call call = getOrderByIdCall(orderId); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for deleteOrder */ + private Call deleteOrderCall(String orderId) throws ApiException { + Object postBody = null; + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * 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 + */ + public void deleteOrder(String orderId) throws ApiException { + Call call = deleteOrderCall(orderId); + apiClient.execute(call); + } + + /** + * Delete purchase order by ID (asynchronously) + * 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 + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call deleteOrderAsync(String orderId, ApiCallback callback) throws ApiException { + Call call = deleteOrderCall(orderId); + apiClient.executeAsync(call, callback); + return call; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java new file mode 100644 index 000000000000..274297650694 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -0,0 +1,500 @@ +package io.swagger.client.api; + +import io.swagger.client.ApiCallback; +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; +import io.swagger.client.Pair; + +import io.swagger.client.model.*; + +import com.google.gson.reflect.TypeToken; + +import com.squareup.okhttp.Call; + +import java.lang.reflect.Type; + +import java.util.*; + +import io.swagger.client.model.User; +import java.util.*; + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +public class UserApi { + private ApiClient apiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + + /* Build call for createUser */ + private Call createUserCall(User body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + */ + public void createUser(User body) throws ApiException { + Call call = createUserCall(body); + apiClient.execute(call); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param body Created user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call createUserAsync(User body, ApiCallback callback) throws ApiException { + Call call = createUserCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for createUsersWithArrayInput */ + private Call createUsersWithArrayInputCall(List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public void createUsersWithArrayInput(List body) throws ApiException { + Call call = createUsersWithArrayInputCall(body); + apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call createUsersWithArrayInputAsync(List body, ApiCallback callback) throws ApiException { + Call call = createUsersWithArrayInputCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for createUsersWithListInput */ + private Call createUsersWithListInputCall(List body) throws ApiException { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "POST", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + */ + public void createUsersWithListInput(List body) throws ApiException { + Call call = createUsersWithListInputCall(body); + apiClient.execute(call); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param body List of user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call createUsersWithListInputAsync(List body, ApiCallback callback) throws ApiException { + Call call = createUsersWithListInputCall(body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for loginUser */ + private Call loginUserCall(String username, String password) throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + if (username != null) + queryParams.addAll(apiClient.parameterToPairs("", "username", username)); + if (password != null) + queryParams.addAll(apiClient.parameterToPairs("", "password", password)); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return String + */ + public String loginUser(String username, String password) throws ApiException { + Call call = loginUserCall(username, password); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login + * @param password The password for login in clear text + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call loginUserAsync(String username, String password, ApiCallback callback) throws ApiException { + Call call = loginUserCall(username, password); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for logoutUser */ + private Call logoutUserCall() throws ApiException { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("\\{format\\}","json"); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Logs out current logged in user session + * + */ + public void logoutUser() throws ApiException { + Call call = logoutUserCall(); + apiClient.execute(call); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call logoutUserAsync(ApiCallback callback) throws ApiException { + Call call = logoutUserCall(); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for getUserByName */ + private Call getUserByNameCall(String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + public User getUserByName(String username) throws ApiException { + Call call = getUserByNameCall(username); + Type returnType = new TypeToken(){}.getType(); + return apiClient.execute(call, returnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call getUserByNameAsync(String username, ApiCallback callback) throws ApiException { + Call call = getUserByNameCall(username); + Type returnType = new TypeToken(){}.getType(); + apiClient.executeAsync(call, returnType, callback); + return call; + } + + /* Build call for updateUser */ + private Call updateUserCall(String username, User body) throws ApiException { + Object postBody = body; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "PUT", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * 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 + */ + public void updateUser(String username, User body) throws ApiException { + Call call = updateUserCall(username, body); + apiClient.execute(call); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call updateUserAsync(String username, User body, ApiCallback callback) throws ApiException { + Call call = updateUserCall(username, body); + apiClient.executeAsync(call, callback); + return call; + } + + /* Build call for deleteUser */ + private Call deleteUserCall(String username) throws ApiException { + Object postBody = null; + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + // create path and map variables + String path = "/user/{username}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); + + List queryParams = new ArrayList(); + + Map headerParams = new HashMap(); + + Map formParams = new HashMap(); + + final String[] accepts = { + "application/json", "application/xml" + }; + final String accept = apiClient.selectHeaderAccept(accepts); + if (accept != null) headerParams.put("Accept", accept); + + final String[] contentTypes = { + + }; + final String contentType = apiClient.selectHeaderContentType(contentTypes); + headerParams.put("Content-Type", contentType); + + String[] authNames = new String[] { }; + return apiClient.buildCall(path, "DELETE", queryParams, postBody, headerParams, formParams, authNames); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + */ + public void deleteUser(String username) throws ApiException { + Call call = deleteUserCall(username); + apiClient.execute(call); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param callback The callback to be executed when the API call finishes + * @return The request call + */ + public Call deleteUserAsync(String username, ApiCallback callback) throws ApiException { + Call call = deleteUserCall(username); + apiClient.executeAsync(call, callback); + return call; + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..20ebbf17e742 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,59 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.add(new Pair(paramName, value)); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 000000000000..9197d04b1b75 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,12 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public interface Authentication { + /** Apply authentication settings to header and query params. */ + void applyToParams(List queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..83d41d5ec08c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 000000000000..184b9e82ca7c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,14 @@ +package io.swagger.client.auth; + +import io.swagger.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +public class OAuth implements Authentication { + @Override + public void applyToParams(List queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..0a7023ac7a52 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Category { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..df8e77b6fb35 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,142 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import java.util.Date; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Order { + + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private Date shipDate = null; + + +public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 000000000000..9ab5457e26ac --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,144 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import io.swagger.client.model.Category; +import java.util.*; +import io.swagger.client.model.Tag; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Pet { + + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + +public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 000000000000..9935b744f2dd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Tag { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 000000000000..cba6abef8dd4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,148 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class User { + + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 000000000000..802c0cae3b97 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,193 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import java.util.*; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Test + public void testSetUsername() { + try { + apiClient.setUsername("my-username"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetPassword() { + try { + apiClient.setPassword("my-password"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key"); + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPairs("csv", null, new Integer(1)); + List pairs_b = apiClient.parameterToPairs("csv", "", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + + // single empty string + List pairs = apiClient.parameterToPairs("csv", "param-a", " "); + assertEquals(1, pairs.size()); + + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPairs("csv", name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "\\|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 000000000000..b95eb74605ea --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java new file mode 100644 index 000000000000..4b03c7a98120 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package io.swagger.client; + +import org.junit.*; +import static org.junit.Assert.*; + + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..5bdb4fb78fba --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,47 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..52c5497ba83e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,52 @@ +package io.swagger.client.auth; + +import java.util.HashMap; +import java.util.ArrayList; +import java.util.Map; +import java.util.List; + +import io.swagger.client.Pair; +import org.junit.*; +import static org.junit.Assert.*; + + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 000000000000..0a8f8a1665d2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,192 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiClient; +import io.swagger.client.ApiException; +import io.swagger.client.Configuration; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.*; +import static org.junit.Assert.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals("http://petstore.swagger.io/v2", api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(fetched.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 000000000000..a1fd7e345a81 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,72 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; + +import io.swagger.client.*; +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Map; + +import org.junit.*; +import static org.junit.Assert.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.PLACED); + order.setComplete(true); + + return order; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 000000000000..26e46bfa6024 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,86 @@ +package io.swagger.petstore.test; + +import io.swagger.client.api.*; +import io.swagger.client.auth.*; +import io.swagger.client.model.*; + +import java.util.Arrays; + +import org.junit.*; +import static org.junit.Assert.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} From 2fd8b8ff16943415f57f7ec366f5c5ebfe2ebd9a Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 31 Aug 2015 20:10:29 +0800 Subject: [PATCH 032/219] Update help text of config options in README --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index b43351aa6197..f288e847b09b 100644 --- a/README.md +++ b/README.md @@ -264,6 +264,7 @@ CONFIG OPTIONS library template (sub-template) to use: - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 jersey2 - HTTP client: Jersey client 2.6 + okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 ``` Your config file for java can look like From e0679c0b145eb82863682dcc33f2194b47824a23 Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Mon, 31 Aug 2015 13:45:24 +0200 Subject: [PATCH 033/219] Issue #1142: sanitize the class name for Java model classes. This builds on #1139, calling the new sanitizeName() method before camelizing it when generating model names. --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 2 ++ 1 file changed, 2 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 aad744dd1ce4..643e6fc92e1a 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 @@ -237,6 +237,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { + name = sanitizeName(name); + // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); From 39b403495807cdf3cd3e5ae31c2f82abb5503c00 Mon Sep 17 00:00:00 2001 From: Robin Eggenkamp Date: Mon, 31 Aug 2015 15:03:56 +0200 Subject: [PATCH 034/219] Replace NSError by ErrorType --- .../swagger-codegen/src/main/resources/swift/APIs.mustache | 2 +- .../main/resources/swift/AlamofireImplementations.mustache | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache index 85cd8fa61490..495752f624da 100644 --- a/modules/swagger-codegen/src/main/resources/swift/APIs.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/APIs.mustache @@ -43,7 +43,7 @@ public class RequestBuilder { self.isBody = isBody } - public func execute(completion: (response: Response?, erorr: NSError?) -> Void) { } + public func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { } public func addHeader(name name: String, value: String) -> Self { if !value.isEmpty { diff --git a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache index 9753dfbfd34f..21791168ab2f 100644 --- a/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/AlamofireImplementations.mustache @@ -20,7 +20,7 @@ class AlamofireRequestBuilder: RequestBuilder { super.init(method: method, URLString: URLString, parameters: parameters, isBody: isBody) } - override func execute(completion: (response: Response?, erorr: NSError?) -> Void) { + override func execute(completion: (response: Response?, erorr: ErrorType?) -> Void) { let managerId = NSUUID().UUIDString // Create a new manager for each request to customize its request header let configuration = NSURLSessionConfiguration.defaultSessionConfiguration() @@ -70,7 +70,7 @@ class AlamofireRequestBuilder: RequestBuilder { } - private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: NSError?) -> Void) { + private func processRequest(request: Request, _ managerId: String, _ completion: (response: Response?, erorr: ErrorType?) -> Void) { if let credential = self.credential { request.authenticate(usingCredential: credential) } From 5b12379a0715031490e7829c0493bdf948b65853 Mon Sep 17 00:00:00 2001 From: Robin Eggenkamp Date: Mon, 31 Aug 2015 15:04:37 +0200 Subject: [PATCH 035/219] Add missing NSDateFormatter --- modules/swagger-codegen/src/main/resources/swift/Models.mustache | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/resources/swift/Models.mustache b/modules/swagger-codegen/src/main/resources/swift/Models.mustache index 87e55eb42282..f6df790ea94e 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Models.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Models.mustache @@ -100,6 +100,7 @@ class Decoders { let formatters = [ "yyyy-MM-dd", "yyyy-MM-dd'T'HH:mm:ssZZZZZ", + "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ", "yyyy-MM-dd'T'HH:mm:ss'Z'" ].map { (format: String) -> NSDateFormatter in let formatter = NSDateFormatter() From 92f9b33eb6c1cf7af246f1449c2b9c1372c21bad Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Mon, 31 Aug 2015 15:14:54 +0200 Subject: [PATCH 036/219] Issue #1142: sanitize api name before camelizing. This builds on #1139 in order to solve another part of #1142: When the first component of a path contained a dash, the generated class name contained this dash too (for the "language" spring-mvc). --- .../io/swagger/codegen/languages/JaxRSServerCodegen.java | 2 +- .../codegen/languages/SpringMVCServerCodegen.java | 9 +++++++++ 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java index 3966cb9bea71..eb0f6be03e9d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -163,7 +163,7 @@ public String toApiName(String name) { if (name.length() == 0) { return "DefaultApi"; } - name = name.replaceAll("[^a-zA-Z0-9]+", "_"); + name = sanitizeName(name); return camelize(name) + "Api"; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 597fd1f19367..863a1aef2e70 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -175,6 +175,15 @@ public Map postProcessOperations(Map objs) { return objs; } + @Override + public String toApiName(String name) { + if (name.length() == 0) { + return "DefaultApi"; + } + name = sanitizeName(name); + return camelize(name) + "Api"; + } + public void setConfigPackage(String configPackage) { this.configPackage = configPackage; } From 3112e4ad063c2894c3d2e35fdb07cf184e6ffbf1 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 1 Sep 2015 11:20:44 +0800 Subject: [PATCH 037/219] Add build files for Gradle and SBT --- .../codegen/languages/JavaClientCodegen.java | 8 ++++-- .../okhttp-gson/build.gradle.mustache | 28 +++++++++++++++++++ .../libraries/okhttp-gson/build.sbt.mustache | 18 ++++++++++++ .../petstore/java/okhttp-gson/build.gradle | 28 +++++++++++++++++++ .../petstore/java/okhttp-gson/build.sbt | 18 ++++++++++++ 5 files changed, 98 insertions(+), 2 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache create mode 100644 samples/client/petstore/java/okhttp-gson/build.gradle create mode 100644 samples/client/petstore/java/okhttp-gson/build.sbt 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 eab4dffa8e30..fa01d0e459f8 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 @@ -163,9 +163,13 @@ public void processOpts() { // library-specific files if ("okhttp-gson".equals(getLibrary())) { - // the "okhttp-gson" library template requires "ApiCallback.mustache" - // and does not require "TypeRef.mustache" + // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); + // "build.gradle" is for development with Gradle + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + // "build.sbt" is for development with SBT + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + // and does not require "TypeRef.mustache" } else { supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache new file mode 100644 index 000000000000..1113d8b4ee9e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -0,0 +1,28 @@ +apply plugin: 'java' +apply plugin: 'maven' + +repositories { + mavenCentral() +} + +dependencies { + compile 'io.swagger:swagger-annotations:1.5.0' + compile 'com.squareup.okhttp:okhttp:2.4.0' + compile 'com.google.code.gson:gson:2.3.1' + compile 'com.brsanthu:migbase64:2.2' + testCompile 'junit:junit:4.8.1' +} + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } +} + +task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache new file mode 100644 index 000000000000..b748f53e48d6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -0,0 +1,18 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.0", + "com.squareup.okhttp" % "okhttp" % "2.4.0", + "com.google.code.gson" % "gson" % "2.3.1", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.8.1" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle new file mode 100644 index 000000000000..96c8f7718d3b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -0,0 +1,28 @@ +apply plugin: 'java' +apply plugin: 'maven' + +repositories { + mavenCentral() +} + +dependencies { + compile 'io.swagger:swagger-annotations:1.5.0' + compile 'com.squareup.okhttp:okhttp:2.4.0' + compile 'com.google.code.gson:gson:2.3.1' + compile 'com.brsanthu:migbase64:2.2' + testCompile 'junit:junit:4.8.1' +} + +group = 'io.swagger' +version = '1.0.0' + +install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } +} + +task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath +} diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt new file mode 100644 index 000000000000..f70c7ea41c77 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -0,0 +1,18 @@ +lazy val root = (project in file(".")). + settings( + organization := "io.swagger", + name := "swagger-petstore-okhttp-gson", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.0", + "com.squareup.okhttp" % "okhttp" % "2.4.0", + "com.google.code.gson" % "gson" % "2.3.1", + "com.brsanthu" % "migbase64" % "2.2", + "junit" % "junit" % "4.8.1" % "test" + ) + ) From 3c79a692aa755f58a2ff879e0cd645f4f8c777d6 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 1 Sep 2015 19:56:06 +0800 Subject: [PATCH 038/219] Use a separate library for base64-encoding in the okhttp-gson template --- .../okhttp-gson/auth/HttpBasicAuth.mustache | 41 +++++++++++++++++++ .../io/swagger/client/auth/HttpBasicAuth.java | 6 +-- 2 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache new file mode 100644 index 000000000000..5b4070fcafb6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBasicAuth.mustache @@ -0,0 +1,41 @@ +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; + +import com.migcomponents.migbase64.Base64; + +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + try { + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 83d41d5ec08c..d2b564331694 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -2,13 +2,13 @@ import io.swagger.client.Pair; +import com.migcomponents.migbase64.Base64; + import java.util.Map; import java.util.List; import java.io.UnsupportedEncodingException; -import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; @@ -33,7 +33,7 @@ public void setPassword(String password) { public void applyToParams(List queryParams, Map headerParams) { String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { - headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); + headerParams.put("Authorization", "Basic " + Base64.encodeToString(str.getBytes("UTF-8"), false)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } From 2c64e0893b86e7105cf97a4159ccfd64fca6a1d7 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 1 Sep 2015 20:04:47 +0800 Subject: [PATCH 039/219] Fix bug of hard-coded enum name in Java client --- .../swagger-codegen/src/main/resources/Java/enumClass.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache index 1cef90b75a4a..68fc07aae7d7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache @@ -3,7 +3,7 @@ public enum {{datatypeWithEnum}} { private String value; - StatusEnum(String value) { + {{datatypeWithEnum}}(String value) { this.value = value; } From 31e8aca357898c11e5e0cb2ded002e48057a7e23 Mon Sep 17 00:00:00 2001 From: b_sapir Date: Tue, 1 Sep 2015 18:26:15 +0300 Subject: [PATCH 040/219] Handle correctly the case of no default response (see comment in #1124) --- .../java/io/swagger/codegen/CodegenOperation.java | 2 +- .../java/io/swagger/codegen/CodegenResponse.java | 2 +- .../java/io/swagger/codegen/DefaultCodegen.java | 3 +++ .../src/main/resources/Java/api.mustache | 13 +++++-------- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 4f30cc01ccba..bd218b4e1203 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -12,7 +12,7 @@ public class CodegenOperation { public final List responseHeaders = new ArrayList(); public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, - hasMore = Boolean.TRUE, isMultipart; + hasMore = Boolean.TRUE, isMultipart, isResponseBinary = Boolean.FALSE; public String path, operationId, returnType, httpMethod, returnBaseType, returnContainer, summary, notes, baseName, defaultResponse; public List> consumes, produces; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index 1929bcf52dc3..e20735b14185 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -15,7 +15,7 @@ public class CodegenResponse { public Boolean primitiveType; public Boolean isMapContainer; public Boolean isListContainer; - public Boolean isBinary; + public Boolean isBinary = Boolean.FALSE; public Object schema; public String jsonSchema; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 687e37a35221..5d9d3d056db9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -835,6 +835,9 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation } r.isDefault = response == methodResponse; op.responses.add(r); + if (r.isBinary && r.isDefault){ + op.isResponseBinary = Boolean.TRUE; + } } op.responses.get(op.responses.size() - 1).hasMore = false; diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 8ffc355072a5..ad957261f2a4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -86,26 +86,23 @@ public class {{classname}} { final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; - {{#responses}} - {{#isDefault}} - {{#isBinary}} + {{#isResponseBinary}} byte[] {{localVariablePrefix}}response = null; {{localVariablePrefix}}response = {{localVariablePrefix}}apiClient.invokeBinaryAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams,{{localVariablePrefix}} postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames); return {{localVariablePrefix}}response; - {{/isBinary}} + {{/isResponseBinary}} - {{^isBinary}} + {{^isResponseBinary}} {{#returnType}} TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); {{/returnType}}{{^returnType}} {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}postBinaryBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); {{/returnType}} - {{/isBinary}} + {{/isResponseBinary}} + - {{/isDefault}} - {{/responses}} } {{/operation}} } From b099d1e7a25465fdc48d771d8c3fce52993e3141 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 1 Sep 2015 15:53:58 -0700 Subject: [PATCH 041/219] added configuration to superclass for overriding param reordering for #1171 --- .../io/swagger/codegen/DefaultCodegen.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 687e37a35221..b798fa9a4b1f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -85,6 +85,7 @@ public class DefaultCodegen { protected boolean supportsInheritance = false; protected Map supportedLibraries = new LinkedHashMap(); protected String library = null; + protected Boolean sortParamsByRequiredFlag = true; public List cliOptions() { return cliOptions; @@ -928,16 +929,19 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.bodyParam = bodyParam; op.httpMethod = httpMethod.toUpperCase(); // move "required" parameters in front of "optional" parameters - Collections.sort(allParams, new Comparator() { - @Override - public int compare(CodegenParameter one, CodegenParameter another) { - boolean oneRequired = one.required == null ? false : one.required; - boolean anotherRequired = another.required == null ? false : another.required; - if (oneRequired == anotherRequired) return 0; - else if (oneRequired) return -1; - else return 1; - } - }); + + if(sortParamsByRequiredFlag) { + Collections.sort(allParams, new Comparator() { + @Override + public int compare(CodegenParameter one, CodegenParameter another) { + boolean oneRequired = one.required == null ? false : one.required; + boolean anotherRequired = another.required == null ? false : another.required; + if (oneRequired == anotherRequired) return 0; + else if (oneRequired) return -1; + else return 1; + } + }); + } op.allParams = addHasMore(allParams); op.bodyParams = addHasMore(bodyParams); op.pathParams = addHasMore(pathParams); From 7c60e2097f887f9d7cbb95b015b3b1c4d301eeb3 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 2 Sep 2015 12:00:27 +0800 Subject: [PATCH 042/219] Update API client initialization in Ruby test --- samples/client/petstore/ruby/spec/spec_helper.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index f8e5992a342a..b8ba0f739756 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -36,11 +36,7 @@ def help # help #end -API_CLIENT = Petstore::ApiClient.new do |config| - config.api_key['api_key'] = 'special-key' - config.host = 'petstore.swagger.io' - config.base_path = '/v2' -end +API_CLIENT = Petstore::ApiClient.new # always delete and then re-create the pet object with 10002 def prepare_pet(pet_api) From 5940f46f56df78227c330eb7d93d600bdcec9199 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 1 Sep 2015 23:04:33 -0700 Subject: [PATCH 043/219] added vendor extensions on parameters per #1173 --- .../io/swagger/codegen/CodegenParameter.java | 3 + .../io/swagger/codegen/DefaultCodegen.java | 97 +++++++++++++++++++ pom.xml | 4 +- 3 files changed, 102 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index 4447915de4da..e9383f48c6bc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -13,6 +13,8 @@ public class CodegenParameter { public boolean isEnum; public List _enum; public Map allowableValues; + public Map vendorExtensions; + /** * Determines whether this parameter is mandatory. If the parameter is in "path", @@ -50,6 +52,7 @@ public CodegenParameter copy() { if (this.allowableValues != null) { output.allowableValues = new HashMap(this.allowableValues); } + output.vendorExtensions = this.vendorExtensions; return output; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index b798fa9a4b1f..99db99bd9625 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -674,7 +674,102 @@ public CodegenProperty fromProperty(String name, Property p) { property.allowableValues = allowableValues; } } + if(p instanceof IntegerProperty) { + IntegerProperty sp = (IntegerProperty) p; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = new ArrayList(); + for(Integer i : _enum) { + property._enum.add(i.toString()); + } + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + if(p instanceof LongProperty) { + LongProperty sp = (LongProperty) p; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = new ArrayList(); + for(Long i : _enum) { + property._enum.add(i.toString()); + } + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + if(p instanceof DoubleProperty) { + DoubleProperty sp = (DoubleProperty) p; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = new ArrayList(); + for(Double i : _enum) { + property._enum.add(i.toString()); + } + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + if(p instanceof FloatProperty) { + FloatProperty sp = (FloatProperty) p; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = new ArrayList(); + for(Float i : _enum) { + property._enum.add(i.toString()); + } + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + if(p instanceof DateProperty) { + DateProperty sp = (DateProperty) p; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = new ArrayList(); + for(String i : _enum) { + property._enum.add(i.toString()); + } + property.isEnum = true; + + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } + if(p instanceof DateTimeProperty) { + DateTimeProperty sp = (DateTimeProperty) p; + if(sp.getEnum() != null) { + List _enum = sp.getEnum(); + property._enum = new ArrayList(); + for(String i : _enum) { + property._enum.add(i.toString()); + } + property.isEnum = true; + // legacy support + Map allowableValues = new HashMap(); + allowableValues.put("values", _enum); + property.allowableValues = allowableValues; + } + } property.datatype = getTypeDeclaration(p); // this can cause issues for clients which don't support enums @@ -1033,6 +1128,8 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p.defaultValue = ((FormParameter) param).getDefaultValue(); } + p.vendorExtensions = param.getVendorExtensions(); + if (param instanceof SerializableParameter) { SerializableParameter qp = (SerializableParameter) param; Property property = null; diff --git a/pom.xml b/pom.xml index 4f0d717140aa..e7a93c0e0526 100644 --- a/pom.xml +++ b/pom.xml @@ -502,10 +502,10 @@ - 1.0.10 + 1.0.11-SNAPSHOT 2.11.1 2.3.4 - 1.5.3 + 1.5.4-SNAPSHOT 2.1.4 2.3 1.2 From 1520ec536e1d0b7abd1927b20e9d120a807acf2f Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 1 Sep 2015 23:34:29 -0700 Subject: [PATCH 044/219] formatting, vendor extensions on operations --- .../io/swagger/codegen/CodegenOperation.java | 1 + .../io/swagger/codegen/CodegenParameter.java | 1 - .../io/swagger/codegen/DefaultCodegen.java | 45 ++++++++++--------- 3 files changed, 24 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 4f30cc01ccba..3bc1744446a8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -29,6 +29,7 @@ public class CodegenOperation { public Set imports = new HashSet(); public List> examples; public ExternalDocs externalDocs; + public Map vendorExtensions; private boolean nonempty(List params) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index e9383f48c6bc..6dd85d10c272 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -15,7 +15,6 @@ public class CodegenParameter { public Map allowableValues; public Map vendorExtensions; - /** * Determines whether this parameter is mandatory. If the parameter is in "path", * this property is required and its value MUST be true. Otherwise, the property diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 99db99bd9625..f4198d11c40a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -781,28 +781,28 @@ public CodegenProperty fromProperty(String name, Property p) { property.baseType = getSwaggerType(p); - if (p instanceof ArrayProperty) { - property.isContainer = true; - property.containerType = "array"; - ArrayProperty ap = (ArrayProperty) p; - CodegenProperty cp = fromProperty(property.name, ap.getItems()); - if (cp == null) { - LOGGER.warn("skipping invalid property " + Json.pretty(p)); - } else { - property.baseType = getSwaggerType(p); - if (!languageSpecificPrimitives.contains(cp.baseType)) { - property.complexType = cp.baseType; - } else { - property.isPrimitiveType = true; - } - property.items = cp; - if (property.items.isEnum) { - property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, - property.items.datatypeWithEnum); - property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); - } - } - } else if (p instanceof MapProperty) { + if (p instanceof ArrayProperty) { + property.isContainer = true; + property.containerType = "array"; + ArrayProperty ap = (ArrayProperty) p; + CodegenProperty cp = fromProperty(property.name, ap.getItems()); + if (cp == null) { + LOGGER.warn("skipping invalid property " + Json.pretty(p)); + } else { + property.baseType = getSwaggerType(p); + if (!languageSpecificPrimitives.contains(cp.baseType)) { + property.complexType = cp.baseType; + } else { + property.isPrimitiveType = true; + } + property.items = cp; + if (property.items.isEnum) { + property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, + property.items.datatypeWithEnum); + property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); + } + } + } else if (p instanceof MapProperty) { property.isContainer = true; property.containerType = "map"; MapProperty ap = (MapProperty) p; @@ -848,6 +848,7 @@ private Response findMethodResponse(Map responses) { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); + op.vendorExtensions = operation.getVendorExtensions(); String operationId = operation.getOperationId(); if (operationId == null) { From 027e4c5a200b600b42ff1fb28304164d6345d2be Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 2 Sep 2015 18:35:58 +0800 Subject: [PATCH 045/219] Set source and target compatibility to 1.7 in build.gradle to make it work with Android --- .../resources/Java/libraries/okhttp-gson/build.gradle.mustache | 3 +++ samples/client/petstore/java/okhttp-gson/build.gradle | 3 +++ 2 files changed, 6 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 1113d8b4ee9e..73ea697ac139 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -1,6 +1,9 @@ apply plugin: 'java' apply plugin: 'maven' +sourceCompatibility = 1.7 +targetCompatibility = 1.7 + repositories { mavenCentral() } diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 96c8f7718d3b..53e92e5fe169 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -1,6 +1,9 @@ apply plugin: 'java' apply plugin: 'maven' +sourceCompatibility = 1.7 +targetCompatibility = 1.7 + repositories { mavenCentral() } From 9af16c0d79f65879d77c209422390dbf98efd7e4 Mon Sep 17 00:00:00 2001 From: Cameron Date: Wed, 2 Sep 2015 13:36:35 +0100 Subject: [PATCH 046/219] Support dots in output folder for C# generator --- .../io/swagger/codegen/languages/CSharpClientCodegen.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 09ec05b078bf..f10d9a0f2990 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -137,11 +137,12 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); + + return outputFolder + File.separator + (sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); } public String modelFileFolder() { - return (outputFolder + File.separator + sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); + return outputFolder + File.separator + (sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); } @Override From 6d7557971ba24f44bf088948b338041a37ea2795 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Wed, 2 Sep 2015 09:28:40 -0700 Subject: [PATCH 047/219] switch Generate to use CodegenConfigurator --- .../java/io/swagger/codegen/cmd/Generate.java | 192 +++++---- .../io/swagger/codegen/cmd/GenerateTest.java | 395 +++++++++--------- modules/swagger-codegen/pom.xml | 6 + .../io/swagger/codegen/ClientOptInput.java | 37 +- .../io/swagger/codegen/CodegenConstants.java | 3 + .../io/swagger/codegen/auth/AuthParser.java | 50 +++ .../codegen/config/CodegenConfigurator.java | 65 ++- .../config/CodegenConfiguratorTest.java | 347 +++++++++++++++ .../src/test/resources/sampleConfig.json | 33 ++ 9 files changed, 814 insertions(+), 314 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java create mode 100644 modules/swagger-codegen/src/test/resources/sampleConfig.json diff --git a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java index d6790a6aa8ff..d72295f4ca97 100644 --- a/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java +++ b/modules/swagger-codegen-cli/src/main/java/io/swagger/codegen/cmd/Generate.java @@ -1,24 +1,18 @@ package io.swagger.codegen.cmd; -import config.Config; -import config.ConfigParser; import io.airlift.airline.Command; import io.airlift.airline.Option; -import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; -import io.swagger.codegen.ClientOpts; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConfigLoader; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.cmd.utils.OptionUtils; -import io.swagger.models.Swagger; -import io.swagger.parser.SwaggerParser; +import io.swagger.codegen.config.CodegenConfigurator; import org.apache.commons.lang3.tuple.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import java.io.File; +import java.util.HashMap; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -37,7 +31,7 @@ public class Generate implements Runnable { public static final Logger LOG = LoggerFactory.getLogger(Generate.class); @Option(name = {"-v", "--verbose"}, description = "verbose mode") - private boolean verbose; + private Boolean verbose; @Option(name = {"-l", "--lang"}, title = "language", required = true, description = "client language to generate (maybe class name in classpath, required)") @@ -71,7 +65,7 @@ public class Generate implements Runnable { @Option(name = {"-s", "--skip-overwrite"}, title = "skip overwrite", description = "specifies if the existing files should be " + "overwritten during the generation.") - private boolean skipOverwrite; + private Boolean skipOverwrite; @Option(name = {"--api-package"}, title = "api package", description = CodegenConstants.API_PACKAGE_DESC) private String apiPackage; @@ -110,116 +104,146 @@ public class Generate implements Runnable { @Option(name = {"--artifact-version"}, title = "artifact version", description = CodegenConstants.ARTIFACT_VERSION_DESC) private String artifactVersion; + @Option(name = {"--library"}, title = "library", description = CodegenConstants.LIBRARY_DESC) + private String library; + @Override public void run() { - verbosed(verbose); - setSystemProperties(); + //attempt to read from config file + CodegenConfigurator configurator = CodegenConfigurator.fromFile(configFile); - CodegenConfig config = CodegenConfigLoader.forName(lang); + //if a config file wasn't specified or we were unable to read it + if(configurator == null) { + //createa a fresh configurator + configurator = new CodegenConfigurator(); + } - config.setOutputDir(new File(output).getAbsolutePath()); - config.setSkipOverwrite(skipOverwrite); + //now override with any specified parameters + if (verbose != null) { + configurator.setVerbose(verbose); + } - putKeyValuePairsInMap(config.instantiationTypes(), instantiationTypes); - putKeyValuePairsInMap(config.typeMapping(), typeMappings); - putKeyValuePairsInMap(config.additionalProperties(), additionalProperties); - putKeyValuePairsInMap(config.importMapping(), importMappings); + if(skipOverwrite != null) { + configurator.setSkipOverwrite(skipOverwrite); + } - addValuesToSet(config.languageSpecificPrimitives(), languageSpecificPrimitives); + if(isNotEmpty(spec)) { + configurator.setInputSpec(spec); + } - checkAndSetAdditionalProperty(config, apiPackage, CodegenConstants.API_PACKAGE); - checkAndSetAdditionalProperty(config, modelPackage, CodegenConstants.MODEL_PACKAGE); + if(isNotEmpty(lang)) { + configurator.setLang(lang); + } + + if(isNotEmpty(output)) { + configurator.setOutputDir(output); + } + + if(isNotEmpty(auth)) { + configurator.setAuth(auth); + } if(isNotEmpty(templateDir)) { - config.additionalProperties().put(CodegenConstants.TEMPLATE_DIR, new File(templateDir).getAbsolutePath()); + configurator.setTemplateDir(templateDir); } - checkAndSetAdditionalProperty(config, invokerPackage, CodegenConstants.INVOKER_PACKAGE); - checkAndSetAdditionalProperty(config, groupId, CodegenConstants.GROUP_ID); - checkAndSetAdditionalProperty(config, artifactId, CodegenConstants.ARTIFACT_ID); - checkAndSetAdditionalProperty(config, artifactVersion, CodegenConstants.ARTIFACT_VERSION); + if(isNotEmpty(apiPackage)) { + configurator.setApiPackage(apiPackage); + } - if (null != configFile) { - Config genConfig = ConfigParser.read(configFile); - if (null != genConfig) { - for (CliOption langCliOption : config.cliOptions()) { - String opt = langCliOption.getOpt(); - if (genConfig.hasOption(opt)) { - config.additionalProperties().put(opt, genConfig.getOption(opt)); - // the "library" config option is for library template (sub-template) - if ("library".equals(opt)) { - config.setLibrary(genConfig.getOption(opt)); - } - } - } - } + if(isNotEmpty(modelPackage)) { + configurator.setModelPackage(modelPackage); } - ClientOptInput input = new ClientOptInput().config(config); + if(isNotEmpty(invokerPackage)) { + configurator.setInvokerPackage(invokerPackage); + } - if (isNotEmpty(auth)) { - input.setAuth(auth); + if(isNotEmpty(groupId)) { + configurator.setGroupId(groupId); } - Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true); - new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); - } + if(isNotEmpty(artifactId)) { + configurator.setArtifactId(artifactId); + } - private void addValuesToSet(Set set, String csvProperty) { - final List values = OptionUtils.splitCommaSeparatedList(csvProperty); + if(isNotEmpty(artifactVersion)) { + configurator.setArtifactVersion(artifactVersion); + } - for (String value : values) { - set.add(value); + if(isNotEmpty(library)) { + configurator.setLibrary(library); + } + + setSystemProperties(configurator); + setInstantiationTypes(configurator); + setImportMappings(configurator); + setTypeMappings(configurator); + setAdditionalProperties(configurator); + setLanguageSpecificPrimitives(configurator); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + + new DefaultGenerator().opts(clientOptInput).generate(); + } + + private void setSystemProperties(CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(systemProperties); + for (Map.Entry entry : map.entrySet()) { + configurator.addSystemProperty(entry.getKey(), entry.getValue()); } } - private void checkAndSetAdditionalProperty(CodegenConfig config, String property, String propertyKey) { - checkAndSetAdditionalProperty(config, property, property, propertyKey); + private void setInstantiationTypes(CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(instantiationTypes); + for (Map.Entry entry : map.entrySet()) { + configurator.addInstantiationType(entry.getKey(), entry.getValue()); + } } - private void checkAndSetAdditionalProperty(CodegenConfig config, String property, String valueToSet, String propertyKey) { - if(isNotEmpty(property)) { - config.additionalProperties().put(propertyKey, valueToSet); + private void setImportMappings(CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(importMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addImportMapping(entry.getKey(), entry.getValue()); } } - private void setSystemProperties() { + private void setTypeMappings(CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(typeMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addTypeMapping(entry.getKey(), entry.getValue()); + } + } - final List> systemPropertyPairs = OptionUtils.parseCommaSeparatedTuples(systemProperties); + private void setAdditionalProperties(CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(additionalProperties); + for (Map.Entry entry : map.entrySet()) { + configurator.addAdditionalProperty(entry.getKey(), entry.getValue()); + } + } - for (Pair pair : systemPropertyPairs) { - System.setProperty(pair.getLeft(), pair.getRight()); + private void setLanguageSpecificPrimitives(CodegenConfigurator configurator) { + final Set set = createSetFromCsvList(languageSpecificPrimitives); + for (String item : set) { + configurator.addLanguageSpecificPrimitive(item); } } - private void putKeyValuePairsInMap(Map map, String commaSeparatedKVPairs) { + private Set createSetFromCsvList(String csvProperty) { + final List values = OptionUtils.splitCommaSeparatedList(csvProperty); + return new HashSet(values); + } + + private Map createMapFromKeyValuePairs(String commaSeparatedKVPairs) { final List> pairs = OptionUtils.parseCommaSeparatedTuples(commaSeparatedKVPairs); + Map result = new HashMap(); + for (Pair pair : pairs) { - map.put(pair.getLeft(), pair.getRight()); + result.put(pair.getLeft(), pair.getRight()); } - } - - /** - * If true parameter, adds system properties which enables debug mode in generator - * - * @param verbose - if true, enables debug mode - */ - private void verbosed(boolean verbose) { - if (!verbose) { - return; - } - LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" + - "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + - "\n - [debugModels] prints models passed to the template engine" + - "\n - [debugOperations] prints operations passed to the template engine" + - "\n - [debugSupportingFiles] prints additional data passed to the template engine"); - - System.setProperty("debugSwagger", ""); - System.setProperty("debugModels", ""); - System.setProperty("debugOperations", ""); - System.setProperty("debugSupportingFiles", ""); + return result; } } diff --git a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java index 94a397df700d..e07d0be4610d 100644 --- a/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java +++ b/modules/swagger-codegen-cli/src/test/java/io/swagger/codegen/cmd/GenerateTest.java @@ -1,84 +1,77 @@ package io.swagger.codegen.cmd; -import config.Config; -import config.ConfigParser; import io.swagger.codegen.ClientOptInput; -import io.swagger.codegen.ClientOpts; -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.DefaultGenerator; import io.swagger.codegen.SwaggerCodegen; -import io.swagger.codegen.CodegenConfigLoader; -import io.swagger.codegen.languages.JavaClientCodegen; -import io.swagger.models.Swagger; -import io.swagger.models.auth.AuthorizationValue; -import io.swagger.parser.SwaggerParser; +import io.swagger.codegen.config.CodegenConfigurator; import mockit.Expectations; import mockit.FullVerifications; import mockit.Injectable; import mockit.Mocked; -import mockit.StrictExpectations; +import mockit.Verifications; import org.apache.commons.lang3.ArrayUtils; import org.testng.annotations.Test; -import java.io.File; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertTrue; - public class GenerateTest { @Mocked - SwaggerParser parser; + CodegenConfigurator configurator; @Injectable - Swagger swagger; - - @Mocked - DefaultGenerator defaultGenerator; + ClientOptInput clientOptInput; @Mocked - CodegenConfigLoader codegenConfigLoader; + DefaultGenerator generator; - @Mocked - ClientOptInput clientOptInput; + @Test + public void testVerbose() throws Exception { + setupAndRunGenericTest("-v"); - @Injectable - List authorizationValues; + new FullVerifications() {{ + configurator.setVerbose(true); + times = 1; + }}; - @Test - public void testVerbose_ShortArg() throws Exception { - doVerboseTest("-v"); - } + setupAndRunGenericTest("--verbose"); - @Test - public void testVerbose_LongArg() throws Exception { - doVerboseTest("--verbose"); + new FullVerifications() {{ + configurator.setVerbose(true); + times = 1; + }}; } @Test public void testRequiredArgs_ShortArgs() throws Exception { - doRequiredArgsTest("-l", "-o", "-i"); + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null); + new FullVerifications() {{ + }}; } @Test public void testRequiredArgs_LongArgs() throws Exception { - doRequiredArgsTest("--lang", "--output", "--input-spec"); + setupAndRunTest("--input-spec", "swagger.yaml", "--lang", "java", "--output", "src/main/java", false, null); + new FullVerifications() {{ + }}; } @Test public void testTemplateDir() throws Exception { - final String absolutePath = new File("src").getAbsolutePath(); - doSingleAdditionalPropertyTest("--template-dir", CodegenConstants.TEMPLATE_DIR, "src", absolutePath); - doSingleAdditionalPropertyTest("--template-dir", CodegenConstants.TEMPLATE_DIR, absolutePath, absolutePath); - doSingleAdditionalPropertyTest("-t", CodegenConstants.TEMPLATE_DIR, "src", absolutePath); - doSingleAdditionalPropertyTest("-t", CodegenConstants.TEMPLATE_DIR, absolutePath, absolutePath); + final String templateDir = "src/main/resources/customTemplates"; + + setupAndRunGenericTest("--template-dir", templateDir); + + new FullVerifications() {{ + configurator.setTemplateDir(templateDir); + times = 1; + }}; + + setupAndRunGenericTest("-t", templateDir); + + new FullVerifications() {{ + configurator.setTemplateDir(templateDir); + times = 1; + }}; } @Test @@ -86,267 +79,279 @@ public void testAuth() throws Exception { final String auth = "hello:world"; - new StrictExpectations() {{ - clientOptInput.setAuth(auth); + setupAndRunGenericTest("--auth", auth); + + new FullVerifications() {{ + configurator.setAuth(auth); times = 1; }}; setupAndRunGenericTest("-a", auth); - new StrictExpectations() {{ - clientOptInput.setAuth(auth); + new FullVerifications() {{ + configurator.setAuth(auth); times = 1; }}; - setupAndRunGenericTest("--auth", auth); + setupAndRunGenericTest(); + + new FullVerifications() {{ + configurator.setAuth(anyString); + times = 0; + }}; } @Test public void testSystemProperties() throws Exception { - new StrictExpectations(System.class) {{ - System.setProperty("hello", "world"); + setupAndRunGenericTest("-D", "hello=world,foo=bar"); + + new FullVerifications() {{ + configurator.addSystemProperty("hello", "world"); times = 1; - System.setProperty("foo", "bar"); + configurator.addSystemProperty("foo", "bar"); times = 1; }}; - setupAndRunGenericTest("-D", "hello=world,foo=bar"); - } + setupAndRunGenericTest("-D", "hello=world,key=,foo=bar"); - @Test - public void testConfig(@Mocked final ConfigParser parser) throws Exception { + new FullVerifications() {{ + configurator.addSystemProperty("hello", "world"); + times = 1; + configurator.addSystemProperty("foo", "bar"); + times = 1; + configurator.addSystemProperty("key", anyString); + times = 0; + }}; + } - final String configFilePath = "config.json"; - final String invokerPackage = "com.foo.bar.invoker"; - final String groupId = "com.foo.bar"; - Map configMap = new HashMap(); - configMap.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); - configMap.put(CodegenConstants.GROUP_ID, groupId); - final Config config = new Config(configMap); - final String[] configArgs = {"-c", "--config"}; + @Test + public void testConfig() throws Exception { - for (String configArg : configArgs) { - new StrictExpectations() {{ - parser.read(configFilePath); - times = 1; - result = config; + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, "config.json", "-c", "config.json"); - }}; + new FullVerifications(){{}}; - final CodegenConfig codegenConfig = setupAndRunGenericTest(configArg, configFilePath); + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", true, "config.json", "--config", "config.json"); - assertValueInMap(codegenConfig.additionalProperties(), CodegenConstants.INVOKER_PACKAGE, invokerPackage); - assertValueInMap(codegenConfig.additionalProperties(), CodegenConstants.GROUP_ID, groupId); - } + new FullVerifications(){{}}; } @Test public void testSkipOverwrite() throws Exception { - CodegenConfig codegenConfig1 = setupAndRunGenericTest(); - assertFalse(codegenConfig1.isSkipOverwrite()); - - CodegenConfig codegenConfig2 = setupAndRunGenericTest("-s"); - assertTrue(codegenConfig2.isSkipOverwrite()); + setupAndRunGenericTest("-s"); + new FullVerifications(){{ + configurator.setSkipOverwrite(true); times=1; + }}; - CodegenConfig codegenConfig3 = setupAndRunGenericTest("--skip-overwrite"); - assertTrue(codegenConfig3.isSkipOverwrite()); + setupAndRunGenericTest("--skip-overwrite"); + new FullVerifications(){{ + configurator.setSkipOverwrite(true); times=1; + }}; } @Test public void testApiPackage() throws Exception { - doSingleAdditionalPropertyTest("--api-package", CodegenConstants.API_PACKAGE, "io.foo.bar.api"); + final String value = "io.foo.bar.api"; + setupAndRunGenericTest("--api-package", value); + + new FullVerifications(){{ + configurator.setApiPackage(value); times=1; + }}; } @Test public void testModelPackage() throws Exception { - doSingleAdditionalPropertyTest("--model-package", CodegenConstants.MODEL_PACKAGE, "io.foo.bar.models"); + final String value = "io.foo.bar.api"; + setupAndRunGenericTest("--model-package", value); + + new FullVerifications(){{ + configurator.setModelPackage(value); times=1; + }}; } @Test public void testInstantiationTypes() throws Exception { - final CodegenConfig codegenConfig = setupAndRunGenericTest("--instantiation-types", "foo=bar,hello=world"); + setupAndRunGenericTest("--instantiation-types", "hello=world,key=,foo=bar"); - assertValueInMap(codegenConfig.instantiationTypes(), "foo", "bar"); - assertValueInMap(codegenConfig.instantiationTypes(), "hello", "world"); + new FullVerifications() {{ + configurator.addInstantiationType("hello", "world"); + times = 1; + configurator.addInstantiationType("foo", "bar"); + times = 1; + configurator.addInstantiationType("key", anyString); + times = 0; + }}; } @Test public void testTypeMappings() throws Exception { - final CodegenConfig codegenConfig = setupAndRunGenericTest("--type-mappings", "foo=bar,hello=world"); + setupAndRunGenericTest("--type-mappings", "hello=world,key=,foo=bar"); - assertValueInMap(codegenConfig.typeMapping(), "foo", "bar"); - assertValueInMap(codegenConfig.typeMapping(), "hello", "world"); + new FullVerifications() {{ + configurator.addTypeMapping("hello", "world"); + times = 1; + configurator.addTypeMapping("foo", "bar"); + times = 1; + configurator.addTypeMapping("key", anyString); + times = 0; + }}; } @Test public void testAdditionalProperties() throws Exception { - final CodegenConfig codegenConfig = setupAndRunGenericTest("--additional-properties", "foo=bar,hello=world"); + setupAndRunGenericTest("--additional-properties", "hello=world,key=,foo=bar"); - assertValueInMap(codegenConfig.additionalProperties(), "foo", "bar"); - assertValueInMap(codegenConfig.additionalProperties(), "hello", "world"); + new FullVerifications() {{ + configurator.addAdditionalProperty("hello", "world"); + times = 1; + configurator.addAdditionalProperty("foo", "bar"); + times = 1; + configurator.addAdditionalProperty("key", anyString); + times = 0; + }}; } @Test public void testLanguageSpecificPrimitives() throws Exception { - final CodegenConfig codegenConfig = setupAndRunGenericTest("--language-specific-primitives", "foo,bar,hello,world"); + setupAndRunGenericTest("--language-specific-primitives", "foo,bar,,hello,world"); - final Set languageSpecificPrimitives = codegenConfig.languageSpecificPrimitives(); - - assertTrue(languageSpecificPrimitives.contains("foo")); - assertTrue(languageSpecificPrimitives.contains("bar")); - assertTrue(languageSpecificPrimitives.contains("hello")); - assertTrue(languageSpecificPrimitives.contains("world")); + new FullVerifications() {{ + configurator.addLanguageSpecificPrimitive("foo"); + times = 1; + configurator.addLanguageSpecificPrimitive("bar"); + times = 1; + configurator.addLanguageSpecificPrimitive("hello"); + times = 1; + configurator.addLanguageSpecificPrimitive("world"); + times = 1; + }}; } @Test public void testImportMappings() throws Exception { - final CodegenConfig codegenConfig = setupAndRunGenericTest("--import-mappings", "foo=bar,hello=world"); + setupAndRunGenericTest("--import-mappings", "hello=world,key=,foo=bar"); - assertValueInMap(codegenConfig.importMapping(), "foo", "bar"); - assertValueInMap(codegenConfig.importMapping(), "hello", "world"); + new FullVerifications() {{ + configurator.addImportMapping("hello", "world"); + times = 1; + configurator.addImportMapping("foo", "bar"); + times = 1; + configurator.addImportMapping("key", anyString); + times = 0; + }}; } @Test public void testInvokerPackage() throws Exception { - doSingleAdditionalPropertyTest("--invoker-package", CodegenConstants.INVOKER_PACKAGE, "io.foo.bar.invoker"); + final String value = "io.foo.bar.api"; + setupAndRunGenericTest("--invoker-package", value); + + new FullVerifications(){{ + configurator.setInvokerPackage(value); times=1; + }}; } @Test public void testGroupId() throws Exception { - doSingleAdditionalPropertyTest("--group-id", CodegenConstants.GROUP_ID, "io.foo.bar"); + final String value = "io.foo.bar.api"; + setupAndRunGenericTest("--group-id", value); + + new FullVerifications(){{ + configurator.setGroupId(value); times=1; + }}; } @Test public void testArtifactId() throws Exception { - doSingleAdditionalPropertyTest("--artifact-id", CodegenConstants.ARTIFACT_ID, "awesome-api"); + final String value = "awesome-api"; + setupAndRunGenericTest("--artifact-id", value); + + new FullVerifications(){{ + configurator.setArtifactId(value); times=1; + }}; } @Test public void testArtifactVersion() throws Exception { - doSingleAdditionalPropertyTest("--artifact-version", CodegenConstants.ARTIFACT_VERSION, "1.2.3"); - } + final String value = "1.2.3"; + setupAndRunGenericTest("--artifact-version", value); - private void doVerboseTest(String verboseFlag) { - new StrictExpectations(System.class) {{ - System.setProperty("debugSwagger", ""); - times = 1; - System.setProperty("debugModels", ""); - times = 1; - System.setProperty("debugOperations", ""); - times = 1; - System.setProperty("debugSupportingFiles", ""); - times = 1; + new FullVerifications(){{ + configurator.setArtifactVersion(value); times=1; }}; - - setupAndRunGenericTest(verboseFlag); } - private void doRequiredArgsTest(String langFlag, String outputDirFlag, String inputSpecFlag) { - final String spec = "swagger.yaml"; - final String lang = "java"; - final String outputDir = "src/main/java"; - - final String[] args = {"generate", langFlag, lang, outputDirFlag, outputDir, inputSpecFlag, spec}; - - final CodegenConfig config = new JavaClientCodegen(); - - setupStandardExpectations(spec, lang, config); - - SwaggerCodegen.main(args); + @Test + public void testLibrary() throws Exception { + final String value = "library1"; + setupAndRunGenericTest("--library", value); - new FullVerifications() {{ + new FullVerifications(){{ + configurator.setLibrary(value); times=1; }}; - - assertEquals(config.getOutputDir(), new File(outputDir).getAbsolutePath()); - } - - private void doSingleAdditionalPropertyTest(String cliArg, String additionalPropertyKey, String expectedValue) { - doSingleAdditionalPropertyTest(cliArg, additionalPropertyKey, expectedValue, expectedValue); } - private void doSingleAdditionalPropertyTest(String cliArg, String additionalPropertyKey, String cliValue, String additionalPropertyValue) { - - final CodegenConfig config = setupAndRunGenericTest(cliArg, cliValue); - - assertValueInMap(config.additionalProperties(), additionalPropertyKey, additionalPropertyValue); - } - - private CodegenConfig setupAndRunGenericTest(String... additionalParameters) { - - final String spec = "swagger.yaml"; - final String lang = "java"; - - final String[] commonArgs = {"generate", "-l", lang, "-o", "path/to/some/directory", "-i", spec}; + private void setupAndRunTest(String specFlag, final String spec, String langFlag, final String lang, + String outputDirFlag, final String outputDir, boolean configuratorFromFile, + final String configFile, String... additionalParameters) { + final String[] commonArgs = {"generate", langFlag, lang, outputDirFlag, outputDir, specFlag, spec}; String[] argsToUse = ArrayUtils.addAll(commonArgs, additionalParameters); - final CodegenConfig config = new JavaClientCodegen(); - - setupStandardExpectations(spec, lang, config); - - SwaggerCodegen.main(argsToUse); - - new FullVerifications() {{ - }}; + if (configuratorFromFile) { - return config; - } + new Expectations(){{ + CodegenConfigurator.fromFile(configFile); + times = 1; + result = configurator; + }}; - private void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) { - assertTrue(map.containsKey(propertyKey)); - assertEquals(map.get(propertyKey), expectedPropertyValue); - } + } else { + new Expectations() {{ + CodegenConfigurator.fromFile(anyString); + result = null; - private void setupStandardExpectations(final String spec, final String languageName, final CodegenConfig config) { + new CodegenConfigurator(); + times = 1; + result = configurator; + }}; + } new Expectations() {{ - CodegenConfigLoader.forName(languageName); - times = 1; - result = config; - - new ClientOptInput(); - times = 1; - result = clientOptInput; - clientOptInput.config(config); + configurator.toClientOptInput(); times = 1; result = clientOptInput; - new SwaggerParser(); - times = 1; - result = parser; - - clientOptInput.getAuthorizationValues(); + new DefaultGenerator(); times = 1; - result = authorizationValues; + result = generator; - parser.read(spec, authorizationValues, true); + generator.opts(clientOptInput); times = 1; - result = swagger; + result = generator; - new DefaultGenerator(); + generator.generate(); times = 1; - result = defaultGenerator; - clientOptInput.opts((ClientOpts) any); - times = 1; - result = clientOptInput; + }}; - clientOptInput.swagger(swagger); - times = 1; - result = clientOptInput; + SwaggerCodegen.main(argsToUse); - defaultGenerator.opts(clientOptInput); + new Verifications() {{ + configurator.setLang(lang); times = 1; - result = defaultGenerator; - - defaultGenerator.generate(); + configurator.setInputSpec(spec); times = 1; + configurator.setOutputDir(outputDir); }}; } + private void setupAndRunGenericTest(String... additionalParameters) { + setupAndRunTest("-i", "swagger.yaml", "-l", "java", "-o", "src/main/java", false, null, additionalParameters); + } } diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index b6caa0a684ae..b1318a343e23 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -346,6 +346,12 @@ ${reflections-version} test + + org.jmockit + jmockit + ${jmockit-version} + test + diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java index 456c7799065d..571498c3121f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/ClientOptInput.java @@ -1,6 +1,7 @@ package io.swagger.codegen; import io.swagger.annotations.ApiModelProperty; +import io.swagger.codegen.auth.AuthParser; import io.swagger.models.Swagger; import io.swagger.models.auth.AuthorizationValue; @@ -32,47 +33,23 @@ public ClientOptInput config(CodegenConfig codegenConfig) { return this; } + @Deprecated public ClientOptInput auth(String urlEncodedAuthString) { this.setAuth(urlEncodedAuthString); return this; } + @Deprecated public String getAuth() { - if (auths != null) { - StringBuilder b = new StringBuilder(); - for (AuthorizationValue v : auths) { - try { - if (b.toString().length() > 0) { - b.append(","); - } - b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")) - .append(":") - .append(URLEncoder.encode(v.getValue(), "UTF-8")); - } catch (Exception e) { - // continue - e.printStackTrace(); - } - } - return b.toString(); - } else { - return null; - } + return AuthParser.reconstruct(auths); } + @Deprecated public void setAuth(String urlEncodedAuthString) { - List auths = new ArrayList(); - if (isNotEmpty(urlEncodedAuthString)) { - String[] parts = urlEncodedAuthString.split(","); - for (String part : parts) { - String[] kvPair = part.split(":"); - if (kvPair.length == 2) { - auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); - } - } - } - this.auths = auths; + this.auths = AuthParser.parse(urlEncodedAuthString); } + @Deprecated public List getAuthorizationValues() { return auths; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 569e445b07da..9978160b557e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -33,5 +33,8 @@ public class CodegenConstants { public static final String SERIALIZABLE_MODEL = "serializableModel"; public static final String SERIALIZABLE_MODEL_DESC = "boolean - toggle \"implements Serializable\" for generated models"; + public static final String LIBRARY = "library"; + public static final String LIBRARY_DESC = "library template (sub-template)"; + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java new file mode 100644 index 000000000000..5fb41755184d --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/auth/AuthParser.java @@ -0,0 +1,50 @@ +package io.swagger.codegen.auth; + +import io.swagger.models.auth.AuthorizationValue; + +import java.net.URLDecoder; +import java.net.URLEncoder; +import java.util.ArrayList; +import java.util.List; + +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + +public class AuthParser { + + public static List parse(String urlEncodedAuthStr) { + List auths = new ArrayList(); + if (isNotEmpty(urlEncodedAuthStr)) { + String[] parts = urlEncodedAuthStr.split(","); + for (String part : parts) { + String[] kvPair = part.split(":"); + if (kvPair.length == 2) { + auths.add(new AuthorizationValue(URLDecoder.decode(kvPair[0]), URLDecoder.decode(kvPair[1]), "header")); + } + } + } + return auths; + } + + public static String reconstruct(List authorizationValueList) { + if (authorizationValueList != null) { + StringBuilder b = new StringBuilder(); + for (AuthorizationValue v : authorizationValueList) { + try { + if (b.toString().length() > 0) { + b.append(","); + } + b.append(URLEncoder.encode(v.getKeyName(), "UTF-8")) + .append(":") + .append(URLEncoder.encode(v.getValue(), "UTF-8")); + } catch (Exception e) { + // continue + e.printStackTrace(); + } + } + return b.toString(); + } else { + return null; + } + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index acc55f3c3144..1b281753e8b1 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -1,20 +1,28 @@ package io.swagger.codegen.config; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import io.swagger.codegen.CliOption; import io.swagger.codegen.ClientOptInput; import io.swagger.codegen.ClientOpts; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConfigLoader; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.auth.AuthParser; import io.swagger.models.Swagger; +import io.swagger.models.auth.AuthorizationValue; import io.swagger.parser.SwaggerParser; +import io.swagger.util.Json; import org.apache.commons.lang3.Validate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; +import java.io.IOException; import java.nio.file.Paths; import java.util.HashMap; import java.util.HashSet; +import java.util.List; import java.util.Map; import java.util.Set; @@ -34,7 +42,7 @@ public class CodegenConfigurator { private String inputSpec; private String outputDir; private boolean verbose = false; - private boolean skipOverwrite; + private boolean skipOverwrite = false; private String templateDir; private String auth; private String apiPackage; @@ -43,6 +51,7 @@ public class CodegenConfigurator { private String groupId; private String artifactId; private String artifactVersion; + private String library; private Map systemProperties = new HashMap(); private Map instantiationTypes = new HashMap(); private Map typeMappings = new HashMap(); @@ -50,6 +59,8 @@ public class CodegenConfigurator { private Map importMappings = new HashMap(); private Set languageSpecificPrimitives = new HashSet(); + private final Map dynamicProperties = new HashMap(); //the map that holds the JsonAnySetter/JsonAnyGetter values + public CodegenConfigurator() { this.setOutputDir("."); } @@ -255,6 +266,15 @@ public CodegenConfigurator addLanguageSpecificPrimitive(String value) { return this; } + public String getLibrary() { + return library; + } + + public CodegenConfigurator setLibrary(String library) { + this.library = library; + return this; + } + public ClientOptInput toClientOptInput() { Validate.notEmpty(lang, "language must be specified"); @@ -281,7 +301,8 @@ public ClientOptInput toClientOptInput() { checkAndSetAdditionalProperty(artifactVersion, CodegenConstants.ARTIFACT_VERSION); checkAndSetAdditionalProperty(templateDir, toAbsolutePathStr(templateDir), CodegenConstants.TEMPLATE_DIR); - final String library = additionalProperties.remove(CodegenConstants.LIBRARY); + handleDynamicProperties(config); + if (isNotEmpty(library)) { config.setLibrary(library); } @@ -289,16 +310,37 @@ public ClientOptInput toClientOptInput() { config.additionalProperties().putAll(additionalProperties); ClientOptInput input = new ClientOptInput() - .config(config) - .auth(auth); + .config(config); + + final List authorizationValues = AuthParser.parse(auth); - Swagger swagger = new SwaggerParser().read(inputSpec, input.getAuthorizationValues(), true); + Swagger swagger = new SwaggerParser().read(inputSpec, authorizationValues, true); input.opts(new ClientOpts()) .swagger(swagger); return input; + } + @JsonAnySetter + public void addDynamicProperty(String name, Object value) { + if (value instanceof String) { + dynamicProperties.put(name, (String) value); + } + } + + @JsonAnyGetter + public Map getDynamicProperties() { + return dynamicProperties; + } + + private void handleDynamicProperties(CodegenConfig codegenConfig) { + for (CliOption langCliOption : codegenConfig.cliOptions()) { + String opt = langCliOption.getOpt(); + if (dynamicProperties.containsKey(opt)) { + codegenConfig.additionalProperties().put(opt, dynamicProperties.get(opt)); + } + } } private void setVerboseFlags() { @@ -342,4 +384,17 @@ private void checkAndSetAdditionalProperty(String property, String valueToSet, S } } + public static CodegenConfigurator fromFile(String configFile) { + + if(isNotEmpty(configFile)) { + try { + CodegenConfigurator result = Json.mapper().readValue(new File(configFile), CodegenConfigurator.class); + return result; + } catch (IOException e) { + LOG.error("Unable to deserialize config file: " + configFile, e); + } + } + return null; + } + } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java new file mode 100644 index 000000000000..2245f2f58771 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/config/CodegenConfiguratorTest.java @@ -0,0 +1,347 @@ +package io.swagger.codegen.config; + +import io.swagger.codegen.ClientOptInput; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConfigLoader; +import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.auth.AuthParser; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.models.Swagger; +import io.swagger.models.auth.AuthorizationValue; +import io.swagger.parser.SwaggerParser; +import mockit.Expectations; +import mockit.FullVerifications; +import mockit.Injectable; +import mockit.Mocked; +import mockit.StrictExpectations; +import mockit.Tested; +import org.testng.annotations.Test; + +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; + +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; + +public class CodegenConfiguratorTest { + + @Mocked + SwaggerParser parser; + + @Mocked + AuthParser authParser; + + @Injectable + Swagger swagger; + + @Mocked + CodegenConfigLoader codegenConfigLoader; + + @Injectable + List authorizationValues; + + @Tested + CodegenConfigurator configurator; + + @Test + public void testVerbose() throws Exception { + + configurator.setVerbose(true); + + new StrictExpectations(System.class) {{ + System.setProperty("debugSwagger", ""); + times = 1; + System.setProperty("debugModels", ""); + times = 1; + System.setProperty("debugOperations", ""); + times = 1; + System.setProperty("debugSupportingFiles", ""); + times = 1; + }}; + + setupAndRunGenericTest(configurator); + } + + @Test + public void testTemplateDir() throws Exception { + + final String templateDir = "src/test/resources"; + configurator.setTemplateDir(templateDir); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.TEMPLATE_DIR, toAbsolutePathDir(templateDir)); + } + + @Test + public void testSystemProperties() throws Exception { + + configurator.addSystemProperty("hello", "world") + .addSystemProperty("foo", "bar"); + + new Expectations(System.class) {{ + System.setProperty("hello", "world"); + times = 1; + System.setProperty("foo", "bar"); + times = 1; + }}; + + setupAndRunGenericTest(configurator); + } + + @Test + public void testSkipOverwrite() throws Exception { + CodegenConfigurator configurator1 = new CodegenConfigurator(); + configurator1.setSkipOverwrite(true); + + ClientOptInput clientOptInput = setupAndRunGenericTest(configurator1); + assertTrue(clientOptInput.getConfig().isSkipOverwrite()); + + CodegenConfigurator configurator2 = new CodegenConfigurator(); + configurator1.setSkipOverwrite(true); + + clientOptInput = setupAndRunGenericTest(configurator2); + assertFalse(clientOptInput.getConfig().isSkipOverwrite()); + } + + @Test + public void testApiPackage() throws Exception { + final String apiPackage = "io.foo.bar.api"; + configurator.setApiPackage(apiPackage); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.API_PACKAGE, apiPackage); + } + + + @Test + public void testModelPackage() throws Exception { + final String modelPackage = "io.foo.bar.models"; + configurator.setModelPackage(modelPackage); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.MODEL_PACKAGE, modelPackage); + } + + @Test + public void testInstantiationTypes() throws Exception { + + configurator.addInstantiationType("foo", "bar") + .addInstantiationType("hello", "world"); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertValueInMap(clientOptInput.getConfig().instantiationTypes(), "foo", "bar"); + assertValueInMap(clientOptInput.getConfig().instantiationTypes(), "hello", "world"); + } + + @Test + public void testTypeMappings() throws Exception { + + configurator.addTypeMapping("foo", "bar") + .addTypeMapping("hello", "world"); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertValueInMap(clientOptInput.getConfig().typeMapping(), "foo", "bar"); + assertValueInMap(clientOptInput.getConfig().typeMapping(), "hello", "world"); + } + + @Test + public void testAdditionalProperties() throws Exception { + + configurator.addAdditionalProperty("foo", "bar") + .addAdditionalProperty("hello", "world"); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertValueInMap(clientOptInput.getConfig().additionalProperties(), "foo", "bar"); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), "hello", "world"); + } + + @Test + public void testLanguageSpecificPrimitives() throws Exception { + + configurator.addLanguageSpecificPrimitive("foo") + .addLanguageSpecificPrimitive("bar") + .addLanguageSpecificPrimitive("hello") + .addLanguageSpecificPrimitive("world"); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("foo")); + assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("bar")); + assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("hello")); + assertTrue(clientOptInput.getConfig().languageSpecificPrimitives().contains("world")); + } + + @Test + public void testImportMappings() throws Exception { + + configurator.addImportMapping("foo", "bar") + .addImportMapping("hello", "world"); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertValueInMap(clientOptInput.getConfig().importMapping(), "foo", "bar"); + assertValueInMap(clientOptInput.getConfig().importMapping(), "hello", "world"); + } + + @Test + public void testInvokerPackage() throws Exception { + final String invokerPackage = "io.foo.bar.models"; + configurator.setInvokerPackage(invokerPackage); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.INVOKER_PACKAGE, invokerPackage); + } + + @Test + public void testGroupId() throws Exception { + final String expectedValue = "io.foo.bar.models"; + configurator.setGroupId(expectedValue); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.GROUP_ID, expectedValue); + } + + @Test + public void testArtifactId() throws Exception { + final String expectedValue = "io.foo.bar.models"; + configurator.setArtifactId(expectedValue); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.ARTIFACT_ID, expectedValue); + } + + @Test + public void testArtifactVersion() throws Exception { + final String expectedValue = "1.2.3"; + configurator.setArtifactVersion(expectedValue); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.ARTIFACT_VERSION, expectedValue); + } + + @Test + public void testLibrary() throws Exception { + final String expectedValue = "jersey2"; + + configurator.setLibrary(expectedValue); + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertEquals(clientOptInput.getConfig().getLibrary(), expectedValue); + } + + @Test + public void testDynamicProperties() throws Exception { + configurator.addDynamicProperty(CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + + final ClientOptInput clientOptInput = setupAndRunGenericTest(configurator); + + assertValueInMap(clientOptInput.getConfig().additionalProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + } + + @Test + public void testFromFile() throws Exception { + final CodegenConfigurator configurator = CodegenConfigurator.fromFile("src/test/resources/sampleConfig.json"); + + assertEquals(configurator.getLang(), "java"); + assertEquals(configurator.getInputSpec(), "swagger.yaml"); + assertEquals(configurator.getOutputDir(), toAbsolutePathDir("src/gen/java")); + assertEquals(configurator.isVerbose(), true); + assertEquals(configurator.isSkipOverwrite(), true); + assertEquals(configurator.getTemplateDir(), toAbsolutePathDir("src/main/resources")); + assertEquals(configurator.getAuth(), "hello:world"); + assertEquals(configurator.getApiPackage(), "io.something.api"); + assertEquals(configurator.getModelPackage(), "io.something.models"); + assertEquals(configurator.getInvokerPackage(), "io.something.invoker"); + assertEquals(configurator.getGroupId(), "io.something"); + assertEquals(configurator.getArtifactId(), "awesome-api"); + assertEquals(configurator.getArtifactVersion(), "1.2.3"); + assertEquals(configurator.getLibrary(), "jersey2"); + + assertEquals(configurator.getSystemProperties().size(), 1); + assertValueInMap(configurator.getSystemProperties(), "systemProp1", "value1"); + + assertEquals(configurator.getInstantiationTypes().size(), 1); + assertValueInMap(configurator.getInstantiationTypes(), "hello", "world"); + + assertEquals(configurator.getTypeMappings().size(), 1); + assertValueInMap(configurator.getTypeMappings(), "foo", "bar"); + + assertEquals(configurator.getAdditionalProperties().size(), 1); + assertValueInMap(configurator.getAdditionalProperties(), "addtProp1", "value2"); + + assertEquals(configurator.getImportMappings().size(), 1); + assertValueInMap(configurator.getImportMappings(), "type1", "import1"); + + + assertEquals(configurator.getLanguageSpecificPrimitives().size(), 1); + assertTrue(configurator.getLanguageSpecificPrimitives().contains("rolex")); + + assertEquals(configurator.getDynamicProperties().size(), 1); + assertValueInMap(configurator.getDynamicProperties(), CodegenConstants.LOCAL_VARIABLE_PREFIX, "_"); + } + + private ClientOptInput setupAndRunGenericTest(CodegenConfigurator configurator) { + + final String spec = "swagger.yaml"; + final String lang = "java"; + final String outputDir = "src/test/java"; + final String expectedAuth = "hello:world"; + + + configurator.setLang(lang) + .setOutputDir(outputDir) + .setInputSpec(spec) + .setAuth(expectedAuth); + + final CodegenConfig config = new JavaClientCodegen(); + + setupStandardExpectations(spec, lang, configurator.getAuth(), config); + + ClientOptInput result = configurator.toClientOptInput(); + + new FullVerifications() {{ + }}; + + final String expectedOutputDir = toAbsolutePathDir(outputDir); + + assertEquals(result.getConfig().getOutputDir(), expectedOutputDir); + + return result; + } + + private String toAbsolutePathDir(String outputDir) { + return Paths.get(outputDir).toAbsolutePath().toAbsolutePath().toString(); + } + + private void setupStandardExpectations(final String spec, final String languageName, final String auth, final CodegenConfig config) { + + new StrictExpectations() {{ + CodegenConfigLoader.forName(languageName); + times = 1; + result = config; + + AuthParser.parse(auth); times=1; result = authorizationValues; + + new SwaggerParser(); + times = 1; + result = parser; + + parser.read(spec, authorizationValues, true); + times = 1; + result = swagger; + + }}; + } + + private void assertValueInMap(Map map, String propertyKey, String expectedPropertyValue) { + assertTrue(map.containsKey(propertyKey)); + assertEquals(map.get(propertyKey), expectedPropertyValue); + } + +} diff --git a/modules/swagger-codegen/src/test/resources/sampleConfig.json b/modules/swagger-codegen/src/test/resources/sampleConfig.json new file mode 100644 index 000000000000..373665877c4b --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/sampleConfig.json @@ -0,0 +1,33 @@ +{ + "lang" : "java", + "inputSpec" : "swagger.yaml", + "outputDir" : "src/gen/java", + "verbose" : true, + "skipOverwrite" : true, + "templateDir" : "src/main/resources", + "auth" : "hello:world", + "apiPackage" : "io.something.api", + "modelPackage" : "io.something.models", + "invokerPackage" : "io.something.invoker", + "groupId" : "io.something", + "artifactId" : "awesome-api", + "artifactVersion" : "1.2.3", + "library" : "jersey2", + "systemProperties" : { + "systemProp1" : "value1" + }, + "instantiationTypes" : { + "hello" : "world" + }, + "typeMappings" : { + "foo" : "bar" + }, + "additionalProperties" : { + "addtProp1" : "value2" + }, + "importMappings" : { + "type1" : "import1" + }, + "languageSpecificPrimitives" : [ "rolex" ], + "localVariablePrefix" : "_" +} \ No newline at end of file From 8ce06fc898456b784ebb418a78842fe4f33ba7f8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 3 Sep 2015 22:38:19 +0800 Subject: [PATCH 048/219] fix HTML-escaped description on nodejs json files --- .../main/resources/nodejs/package.mustache | 2 +- .../main/resources/nodejs/swagger.mustache | 2 +- .../server/petstore/nodejs/api/swagger.json | 483 +++++++++--------- .../server/petstore/nodejs/controllers/Pet.js | 4 +- .../petstore/nodejs/controllers/PetService.js | 2 +- .../nodejs/controllers/StoreService.js | 4 +- samples/server/petstore/nodejs/package.json | 2 +- 7 files changed, 260 insertions(+), 239 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache index 7add6e813fed..89db4c0b91eb 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/package.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/package.mustache @@ -1,7 +1,7 @@ { "name": "{{projectName}}", "version": "{{appVersion}}", - "description": "{{appDescription}}", + "description": "{{{appDescription}}}", "main": "index.js", "keywords": [ "swagger" diff --git a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache index 3b975e53b807..1d0f7d781620 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/swagger.mustache @@ -2,7 +2,7 @@ "swagger": "2.0", "info": { "title": "{{appName}}", - "description": "{{appDescription}}", + "description": "{{{appDescription}}}", "version": "{{apiVersion}}" }, {{#apiInfo}} diff --git a/samples/server/petstore/nodejs/api/swagger.json b/samples/server/petstore/nodejs/api/swagger.json index 02c5ca0f97fa..4f091973cf2d 100644 --- a/samples/server/petstore/nodejs/api/swagger.json +++ b/samples/server/petstore/nodejs/api/swagger.json @@ -2,7 +2,7 @@ "swagger": "2.0", "info": { "title": "Swagger Petstore", - "description": "This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "version": "1.0.0" }, "produces": ["application/json"], @@ -10,42 +10,14 @@ "basePath": "/v2", "paths": { - "/user": { - "post": { - "summary": "Create user", - "description":"This can only be done by the logged in user.", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "createUser", - "parameters": [ - { - "in" : "body", - "name" : "body", - "description" : "Created user object", - "required" : false, - "schema" : { - "$ref" : "#/definitions/User" - } -} - - ], - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } - } , - - "/user/createWithArray": { + "/user/createWithList": { + "post": { "summary": "Creates list of users with given input array", "description":"", "x-swagger-router-controller": "User", "tags": ["User"], - "operationId": "createUsersWithArrayInput", + "operationId": "createUsersWithListInput", "parameters": [ { "in" : "body", @@ -68,16 +40,18 @@ } - } + } + } , - "/user/createWithList": { + "/user/createWithArray": { + "post": { "summary": "Creates list of users with given input array", "description":"", "x-swagger-router-controller": "User", "tags": ["User"], - "operationId": "createUsersWithListInput", + "operationId": "createUsersWithArrayInput", "parameters": [ { "in" : "body", @@ -100,68 +74,12 @@ } - } - } , - - "/user/login": { - "get": { - "summary": "Logs user into the system", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "loginUser", - "parameters": [ - { - "name" : "username", - "in" : "query", - "description" : "The user name for login", - "required" : false, - "type" : "string" -}, - { - "name" : "password", - "in" : "query", - "description" : "The password for login in clear text", - "required" : false, - "type" : "string" -} - - ], - "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "type" : "string" - } -} - , - "400": { - "description" : "Invalid username/password supplied" -} - - - } - } - } , - - "/user/logout": { - "get": { - "summary": "Logs out current logged in user session", - "description":"", - "x-swagger-router-controller": "User", - "tags": ["User"], - "operationId": "logoutUser", - "responses": { - "default": { - "description" : "successful operation" -} - - - } - } + } + } , "/user/{username}": { + "get": { "summary": "Get user by user name", "description":"", @@ -208,10 +126,8 @@ } - } - } , - - "/user/{username}": { + } , + "put": { "summary": "Updated user", "description":"This can only be done by the logged in user.", @@ -248,10 +164,8 @@ } - } - } , - - "/user/{username}": { + } , + "delete": { "summary": "Delete user", "description":"This can only be done by the logged in user.", @@ -279,12 +193,106 @@ } - } - } + } + + } , + + "/user": { + + "post": { + "summary": "Create user", + "description":"This can only be done by the logged in user.", + "x-swagger-router-controller": "User", + "tags": ["User"], + "operationId": "createUser", + "parameters": [ + { + "in" : "body", + "name" : "body", + "description" : "Created user object", + "required" : false, + "schema" : { + "$ref" : "#/definitions/User" + } +} + + ], + "responses": { + "default": { + "description" : "successful operation" +} + + + } + } + + } , + + "/user/logout": { + + "get": { + "summary": "Logs out current logged in user session", + "description":"", + "x-swagger-router-controller": "User", + "tags": ["User"], + "operationId": "logoutUser", + "responses": { + "default": { + "description" : "successful operation" +} + + + } + } + + } , + + "/user/login": { + + "get": { + "summary": "Logs user into the system", + "description":"", + "x-swagger-router-controller": "User", + "tags": ["User"], + "operationId": "loginUser", + "parameters": [ + { + "name" : "username", + "in" : "query", + "description" : "The user name for login", + "required" : false, + "type" : "string" +}, + { + "name" : "password", + "in" : "query", + "description" : "The password for login in clear text", + "required" : false, + "type" : "string" +} + + ], + "responses": { + "200": { + "description" : "successful operation", + "schema" : { + "type" : "string" + } +} + , + "400": { + "description" : "Invalid username/password supplied" +} + + + } + } + + } , - , "/pet": { + "put": { "summary": "Update an existing pet", "description":"", @@ -318,10 +326,8 @@ } - } - } , - - "/pet": { + } , + "post": { "summary": "Add a new pet to the store", "description":"", @@ -347,10 +353,56 @@ } - } + } + + } , + + "/pet/{petId}/uploadImage": { + + "post": { + "summary": "uploads an image", + "description":"", + "x-swagger-router-controller": "Pet", + "tags": ["Pet"], + "operationId": "uploadFile", + "parameters": [ + { + "name" : "petId", + "in" : "path", + "description" : "ID of pet to update", + "required" : true, + "type" : "integer", + "format" : "int64" +}, + { + "name" : "additionalMetadata", + "in" : "formData", + "description" : "Additional data to pass to server", + "required" : false, + "type" : "string" +}, + { + "name" : "file", + "in" : "formData", + "description" : "file to upload", + "required" : false, + "type" : "file" +} + + ], + "responses": { + "default": { + "description" : "successful operation" +} + + + } + } + } , "/pet/findByStatus": { + "get": { "summary": "Finds Pets by status", "description":"Multiple status values can be provided with comma seperated strings", @@ -389,10 +441,12 @@ } - } + } + } , "/pet/findByTags": { + "get": { "summary": "Finds Pets by tags", "description":"Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", @@ -430,10 +484,12 @@ } - } + } + } , "/pet/{petId}": { + "get": { "summary": "Find pet by ID", "description":"Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", @@ -469,10 +525,8 @@ } - } - } , - - "/pet/{petId}": { + } , + "post": { "summary": "Updates a pet in the store with form data", "description":"", @@ -510,10 +564,8 @@ } - } - } , - - "/pet/{petId}": { + } , + "delete": { "summary": "Deletes a pet", "description":"", @@ -522,19 +574,19 @@ "operationId": "deletePet", "parameters": [ { - "name" : "api_key", - "in" : "header", - "description" : "", - "required" : false, - "type" : "string" -}, - { "name" : "petId", "in" : "path", "description" : "Pet id to delete", "required" : true, "type" : "integer", "format" : "int64" +}, + { + "name" : "api_key", + "in" : "header", + "description" : "", + "required" : false, + "type" : "string" } ], @@ -545,78 +597,82 @@ } - } + } + } , - "/pet/{petId}/uploadImage": { - "post": { - "summary": "uploads an image", - "description":"", - "x-swagger-router-controller": "Pet", - "tags": ["Pet"], - "operationId": "uploadFile", + + "/store/order/{orderId}": { + + "get": { + "summary": "Find purchase order by ID", + "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "x-swagger-router-controller": "Store", + "tags": ["Store"], + "operationId": "getOrderById", "parameters": [ { - "name" : "petId", + "name" : "orderId", "in" : "path", - "description" : "ID of pet to update", + "description" : "ID of pet that needs to be fetched", "required" : true, - "type" : "integer", - "format" : "int64" -}, - { - "name" : "additionalMetadata", - "in" : "formData", - "description" : "Additional data to pass to server", - "required" : false, "type" : "string" -}, - { - "name" : "file", - "in" : "formData", - "description" : "file to upload", - "required" : false, - "type" : "file" } ], "responses": { - "default": { - "description" : "successful operation" + "404": { + "description" : "Order not found" +} + , + "200": { + "description" : "successful operation", + "schema" : { + "$ref" : "#/definitions/Order" + } +} + , + "400": { + "description" : "Invalid ID supplied" } } - } - } - - , - - "/store/inventory": { - "get": { - "summary": "Returns pet inventories by status", - "description":"Returns a map of status codes to quantities", + } , + + "delete": { + "summary": "Delete purchase order by ID", + "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", "x-swagger-router-controller": "Store", "tags": ["Store"], - "operationId": "getInventory", + "operationId": "deleteOrder", + "parameters": [ + { + "name" : "orderId", + "in" : "path", + "description" : "ID of the order that needs to be deleted", + "required" : true, + "type" : "string" +} + + ], "responses": { - "200": { - "description" : "successful operation", - "schema" : { - "type" : "object", - "additionalProperties" : { - "type" : "integer", - "format" : "int32" - } - } + "404": { + "description" : "Order not found" +} + , + "400": { + "description" : "Invalid ID supplied" } } - } + } + } , "/store/order": { + "post": { "summary": "Place an order for a pet", "description":"", @@ -649,79 +705,36 @@ } - } + } + } , - "/store/order/{orderId}": { + "/store/inventory": { + "get": { - "summary": "Find purchase order by ID", - "description":"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "summary": "Returns pet inventories by status", + "description":"Returns a map of status codes to quantities", "x-swagger-router-controller": "Store", "tags": ["Store"], - "operationId": "getOrderById", - "parameters": [ - { - "name" : "orderId", - "in" : "path", - "description" : "ID of pet that needs to be fetched", - "required" : true, - "type" : "string" -} - - ], + "operationId": "getInventory", "responses": { - "404": { - "description" : "Order not found" -} - , "200": { "description" : "successful operation", "schema" : { - "$ref" : "#/definitions/Order" - } -} - , - "400": { - "description" : "Invalid ID supplied" -} - - - } + "type" : "object", + "additionalProperties" : { + "type" : "integer", + "format" : "int32" } - } , - - "/store/order/{orderId}": { - "delete": { - "summary": "Delete purchase order by ID", - "description":"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", - "x-swagger-router-controller": "Store", - "tags": ["Store"], - "operationId": "deleteOrder", - "parameters": [ - { - "name" : "orderId", - "in" : "path", - "description" : "ID of the order that needs to be deleted", - "required" : true, - "type" : "string" -} - - ], - "responses": { - "404": { - "description" : "Order not found" -} - , - "400": { - "description" : "Invalid ID supplied" + } } } - } + } + } - }, "definitions": { "User": { "properties" : { @@ -785,12 +798,20 @@ }, "photoUrls" : { "type" : "array", + "xml" : { + "name" : "photoUrl", + "wrapped" : true + }, "items" : { "type" : "string" } }, "tags" : { "type" : "array", + "xml" : { + "name" : "tag", + "wrapped" : true + }, "items" : { "$ref" : "#/definitions/Tag" } diff --git a/samples/server/petstore/nodejs/controllers/Pet.js b/samples/server/petstore/nodejs/controllers/Pet.js index f23f593f4145..a268c8fa700e 100644 --- a/samples/server/petstore/nodejs/controllers/Pet.js +++ b/samples/server/petstore/nodejs/controllers/Pet.js @@ -93,11 +93,11 @@ module.exports.updatePetWithForm = function updatePetWithForm (req, res, next) { }; module.exports.deletePet = function deletePet (req, res, next) { - var apiKey = req.swagger.params['api_key'].value; var petId = req.swagger.params['petId'].value; + var apiKey = req.swagger.params['api_key'].value; - var result = Pet.deletePet(apiKey, petId); + var result = Pet.deletePet(petId, apiKey); if(typeof result !== 'undefined') { res.setHeader('Content-Type', 'application/json'); diff --git a/samples/server/petstore/nodejs/controllers/PetService.js b/samples/server/petstore/nodejs/controllers/PetService.js index cdfac3466ae4..f238fa410ac9 100644 --- a/samples/server/petstore/nodejs/controllers/PetService.js +++ b/samples/server/petstore/nodejs/controllers/PetService.js @@ -96,7 +96,7 @@ exports.updatePetWithForm = function(petId, name, status) { } -exports.deletePet = function(apiKey, petId) { +exports.deletePet = function(petId, apiKey) { var examples = {}; diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index ba9ffd4fc441..947774aad2ec 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -24,7 +24,7 @@ exports.placeOrder = function(body) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-07-09T06:03:19.571+0000" + "shipDate" : "2015-09-03T14:34:08.343+0000" }; @@ -43,7 +43,7 @@ exports.getOrderById = function(orderId) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-07-09T06:03:19.576+0000" + "shipDate" : "2015-09-03T14:34:08.347+0000" }; diff --git a/samples/server/petstore/nodejs/package.json b/samples/server/petstore/nodejs/package.json index 7bb6df08fb5b..35390feefda6 100644 --- a/samples/server/petstore/nodejs/package.json +++ b/samples/server/petstore/nodejs/package.json @@ -1,7 +1,7 @@ { "name": "", "version": "1.0.0", - "description": "This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", "main": "index.js", "keywords": [ "swagger" From ab6118afe429a9a4d4ee3d0bd006678e55b077cd Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 3 Sep 2015 08:24:33 -0700 Subject: [PATCH 049/219] update default generator to skip generation of models that have import mappings defined --- .../src/main/java/io/swagger/codegen/CodegenConfig.java | 2 ++ .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 4 ++++ .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 7 +++++++ 3 files changed, 13 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 1b0e349dacaf..10d7363cc35a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -85,6 +85,8 @@ public interface CodegenConfig { Set languageSpecificPrimitives(); + void preprocessSwagger(Swagger swagger); + void processSwagger(Swagger swagger); String toApiFilename(String name); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 8fb6eee2964d..f7d0ce3f45f2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -120,6 +120,10 @@ public Map postProcessSupportingFileData(Map obj return objs; } + //override with any special handling of the entire swagger spec + public void preprocessSwagger(Swagger swagger) { + } + // override with any special handling of the entire swagger spec public void processSwagger(Swagger swagger) { } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index e5a49f4eba46..80a25350d8bf 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -71,6 +71,7 @@ public List generate() { List files = new ArrayList(); try { config.processOpts(); + config.preprocessSwagger(swagger); config.additionalProperties().put("generatedDate", DateTime.now().toString()); config.additionalProperties().put("generatorClass", config.getClass().toString()); @@ -138,6 +139,12 @@ public List generate() { List sortedModelKeys = sortModelsByInheritance(definitions); for (String name : sortedModelKeys) { + + //dont generate models that have an import mapping + if(config.importMapping().containsKey(name)) { + continue; + } + Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); From 435ce7b9d57432b3d284cce4ce5f9134cbdcfb64 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 3 Sep 2015 10:16:44 -0700 Subject: [PATCH 050/219] make JsonAnySetter for dynamic properties "builder" style --- .../java/io/swagger/codegen/config/CodegenConfigurator.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 1b281753e8b1..25e5f1843b81 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -323,10 +323,12 @@ public ClientOptInput toClientOptInput() { } @JsonAnySetter - public void addDynamicProperty(String name, Object value) { + public CodegenConfigurator addDynamicProperty(String name, Object value) { if (value instanceof String) { dynamicProperties.put(name, (String) value); } + + return this; } @JsonAnyGetter From 2822e9ea387ab26be927dec04af6b94e9257791f Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Thu, 3 Sep 2015 12:18:00 -0700 Subject: [PATCH 051/219] added support for retrieving HTTP response headers in obj-c. Also added a +sharedAPI class method for easy initialization of an API class without passing headers --- .../main/resources/objc/ApiClient-body.mustache | 17 ++++++++++++++++- .../resources/objc/ApiClient-header.mustache | 3 +++ .../src/main/resources/objc/api-body.mustache | 11 ++++++++++- .../src/main/resources/objc/api-header.mustache | 1 + 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index b7643de6ddd6..5b2a290ab852 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -9,6 +9,13 @@ static bool cacheEnabled = false; static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; static void (^reachabilityChangeBlock)(int); + +@interface {{classPrefix}}ApiClient () + +@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; + +@end + @implementation {{classPrefix}}ApiClient - (instancetype)init { @@ -385,6 +392,8 @@ static void (^reachabilityChangeBlock)(int); if([[{{classPrefix}}Configuration sharedConfig] debug]) { [self logResponse:operation forRequest:request error:nil]; } + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; + self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { @@ -398,6 +407,10 @@ static void (^reachabilityChangeBlock)(int); if([[{{classPrefix}}Configuration sharedConfig] debug]) [self logResponse:nil forRequest:request error:augmentedError]; + + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; + self.HTTPResponseHeaders = responseHeaders; + completionBlock(nil, augmentedError); } }]; @@ -441,6 +454,7 @@ static void (^reachabilityChangeBlock)(int); NSURL *file = [NSURL fileURLWithPath:filepath]; [operation.responseData writeToURL:file atomically:YES]; + self.HTTPResponseHeaders = headers; completionBlock(file, nil); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { @@ -455,7 +469,8 @@ static void (^reachabilityChangeBlock)(int); if ([[{{classPrefix}}Configuration sharedConfig] debug]) { [self logResponse:nil forRequest:request error:augmentedError]; } - + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; + self.HTTPResponseHeaders = responseHeaders; completionBlock(nil, augmentedError); } }]; diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index eba627058795..fef1a2b79e7b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -31,6 +31,9 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, readonly) NSOperationQueue* queue; +/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one {{classPrefix}}ApiClient instance per thread. +@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; + /** * Clears Cache */ 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 534c887fe7b1..1aa22a0a0c62 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -11,6 +11,8 @@ @implementation {{classname}} +static {{classname}}* singletonAPI = nil; + #pragma mark - Initialize methods - (id) init { @@ -38,7 +40,6 @@ #pragma mark - +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static {{classname}}* singletonAPI = nil; if (singletonAPI == nil) { singletonAPI = [[{{classname}} alloc] init]; @@ -47,6 +48,14 @@ return singletonAPI; } ++({{classname}}*) sharedAPI { + + if (singletonAPI == nil) { + singletonAPI = [[{{classname}} alloc] init]; + } + return singletonAPI; +} + -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } 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 d9f691f72270..29c7d9477f26 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -20,6 +20,7 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++({{classname}}*) sharedAPI; {{#operation}} /// /// From f067b86fa036a67148b89c49086213c59e917812 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Thu, 3 Sep 2015 12:31:30 -0700 Subject: [PATCH 052/219] re-built sample objc-petstore --- samples/client/petstore/objc/README.md | 4 ++++ .../petstore/objc/SwaggerClient/SWGApiClient.h | 3 +++ .../petstore/objc/SwaggerClient/SWGApiClient.m | 17 ++++++++++++++++- .../petstore/objc/SwaggerClient/SWGPetApi.h | 1 + .../petstore/objc/SwaggerClient/SWGPetApi.m | 11 ++++++++++- .../petstore/objc/SwaggerClient/SWGStoreApi.h | 1 + .../petstore/objc/SwaggerClient/SWGStoreApi.m | 11 ++++++++++- .../petstore/objc/SwaggerClient/SWGUserApi.h | 3 ++- .../petstore/objc/SwaggerClient/SWGUserApi.m | 13 +++++++++++-- 9 files changed, 58 insertions(+), 6 deletions(-) diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index 4cce2c882bbf..10e449846838 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -12,6 +12,10 @@ To install it, put the API client library in your project and then simply add th pod "SwaggerClient", :path => "/path/to/lib" ``` +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issue. + ## Author apiteam@swagger.io diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 84f28faa8c6c..580efa739a08 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -35,6 +35,9 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, readonly) NSOperationQueue* queue; +/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one SWGApiClient instance per thread. +@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; + /** * Clears Cache */ diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 906169f4d129..826443453b0e 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -9,6 +9,13 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; static void (^reachabilityChangeBlock)(int); + +@interface SWGApiClient () + +@property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; + +@end + @implementation SWGApiClient - (instancetype)init { @@ -385,6 +392,8 @@ - (void) operationWithCompletionBlock: (NSURLRequest *)request if([[SWGConfiguration sharedConfig] debug]) { [self logResponse:operation forRequest:request error:nil]; } + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; + self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); } } failure:^(AFHTTPRequestOperation *operation, NSError *error) { @@ -398,6 +407,10 @@ - (void) operationWithCompletionBlock: (NSURLRequest *)request if([[SWGConfiguration sharedConfig] debug]) [self logResponse:nil forRequest:request error:augmentedError]; + + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; + self.HTTPResponseHeaders = responseHeaders; + completionBlock(nil, augmentedError); } }]; @@ -441,6 +454,7 @@ - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request NSURL *file = [NSURL fileURLWithPath:filepath]; [operation.responseData writeToURL:file atomically:YES]; + self.HTTPResponseHeaders = headers; completionBlock(file, nil); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { @@ -455,7 +469,8 @@ - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request if ([[SWGConfiguration sharedConfig] debug]) { [self logResponse:nil forRequest:request error:augmentedError]; } - + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; + self.HTTPResponseHeaders = responseHeaders; completionBlock(nil, augmentedError); } }]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h index f7e67d0aa1fc..7ea1821e575a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.h @@ -18,6 +18,7 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(SWGPetApi*) sharedAPI; /// /// /// Update an existing pet diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index d79584f90bfe..4b8eba705627 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -9,6 +9,8 @@ @interface SWGPetApi () @implementation SWGPetApi +static SWGPetApi* singletonAPI = nil; + #pragma mark - Initialize methods - (id) init { @@ -36,7 +38,6 @@ - (id) initWithApiClient:(SWGApiClient *)apiClient { #pragma mark - +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static SWGPetApi* singletonAPI = nil; if (singletonAPI == nil) { singletonAPI = [[SWGPetApi alloc] init]; @@ -45,6 +46,14 @@ +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { return singletonAPI; } ++(SWGPetApi*) sharedAPI { + + if (singletonAPI == nil) { + singletonAPI = [[SWGPetApi alloc] init]; + } + return singletonAPI; +} + -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h index 09e67e38ed02..e1c644ef5f4a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.h @@ -18,6 +18,7 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(SWGStoreApi*) sharedAPI; /// /// /// Returns pet inventories by status diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 792147ebed14..5fdf86b43aff 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -9,6 +9,8 @@ @interface SWGStoreApi () @implementation SWGStoreApi +static SWGStoreApi* singletonAPI = nil; + #pragma mark - Initialize methods - (id) init { @@ -36,7 +38,6 @@ - (id) initWithApiClient:(SWGApiClient *)apiClient { #pragma mark - +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static SWGStoreApi* singletonAPI = nil; if (singletonAPI == nil) { singletonAPI = [[SWGStoreApi alloc] init]; @@ -45,6 +46,14 @@ +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { return singletonAPI; } ++(SWGStoreApi*) sharedAPI { + + if (singletonAPI == nil) { + singletonAPI = [[SWGStoreApi alloc] init]; + } + return singletonAPI; +} + -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index a6e69a8947d9..21f314684fd7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -18,6 +18,7 @@ -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(SWGUserApi*) sharedAPI; /// /// /// Create user @@ -98,7 +99,7 @@ /// Get user by user name /// /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// /// @return SWGUser* diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 92dd00fa28da..75cf8d51b0ea 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -9,6 +9,8 @@ @interface SWGUserApi () @implementation SWGUserApi +static SWGUserApi* singletonAPI = nil; + #pragma mark - Initialize methods - (id) init { @@ -36,7 +38,6 @@ - (id) initWithApiClient:(SWGApiClient *)apiClient { #pragma mark - +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static SWGUserApi* singletonAPI = nil; if (singletonAPI == nil) { singletonAPI = [[SWGUserApi alloc] init]; @@ -45,6 +46,14 @@ +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { return singletonAPI; } ++(SWGUserApi*) sharedAPI { + + if (singletonAPI == nil) { + singletonAPI = [[SWGUserApi alloc] init]; + } + return singletonAPI; +} + -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -461,7 +470,7 @@ -(NSNumber*) logoutUserWithCompletionBlock: /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// @returns SWGUser* /// From 75bb59572aec8a67b04b722473b393dfe8ec213d Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Thu, 3 Sep 2015 12:54:25 -0700 Subject: [PATCH 053/219] added extra CLI options required to generate a valid (lint-able) podspec file. --- .../codegen/languages/ObjcClientCodegen.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) 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 dfb4094f2b65..ef369169827a 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 @@ -23,6 +23,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { protected String podName = "SwaggerClient"; protected String podVersion = "1.0.0"; protected String classPrefix = "SWG"; + protected String authorName = "Swagger"; + protected String authorEmail = "apiteam@swagger.io"; + protected String license = "MIT"; + protected String gitRepoURL = "https://github.com/swagger-api/swagger-codegen"; public ObjcClientCodegen() { super(); @@ -112,6 +116,10 @@ public ObjcClientCodegen() { cliOptions.add(new CliOption("classPrefix", "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`), default: `SWG`")); cliOptions.add(new CliOption("podName", "cocoapods package name (convention: CameCase), default: `SwaggerClient`")); cliOptions.add(new CliOption("podVersion", "cocoapods package version, default: `1.0.0`")); + cliOptions.add(new CliOption("authorName", "Name to use in the podspec file, default: `Swagger`")); + cliOptions.add(new CliOption("authorEmail", "Email to use in the podspec file, default: `apiteam@swagger.io`")); + cliOptions.add(new CliOption("gitRepoURL", "URL for the git repo where this podspec should point to, default: `https://github.com/swagger-api/swagger-codegen`")); + cliOptions.add(new CliOption("license", "License to use in the podspec file, default: `MIT`")); } public CodegenType getTag() { @@ -141,10 +149,30 @@ public void processOpts() { if (additionalProperties.containsKey("classPrefix")) { setClassPrefix((String) additionalProperties.get("classPrefix")); } + + if (additionalProperties.containsKey("authorName")) { + setAuthorName((String) additionalProperties.get("authorName")); + } + + if (additionalProperties.containsKey("authorEmail")) { + setAuthorEmail((String) additionalProperties.get("authorEmail")); + } + + if (additionalProperties.containsKey("gitRepoURL")) { + setGitRepoURL((String) additionalProperties.get("gitRepoURL")); + } + + if (additionalProperties.containsKey("license")) { + setLicense((String) additionalProperties.get("license")); + } additionalProperties.put("podName", podName); additionalProperties.put("podVersion", podVersion); additionalProperties.put("classPrefix", classPrefix); + additionalProperties.put("authorName", authorName); + additionalProperties.put("authorEmail", authorEmail); + additionalProperties.put("gitRepoURL", gitRepoURL); + additionalProperties.put("license", license); String swaggerFolder = podName; @@ -384,4 +412,20 @@ public void setPodName(String podName) { public void setPodVersion(String podVersion) { this.podVersion = podVersion; } + + public void setAuthorEmail(String authorEmail) { + this.authorEmail = authorEmail; + } + + public void setAuthorName(String authorName) { + this.authorName = authorName; + } + + public void setGitRepoURL(String gitRepoURL) { + this.gitRepoURL = gitRepoURL; + } + + public void setLicense(String license) { + this.license = license; + } } From f705e03fc4b04f7c2f8ab4d7be59c855b3181057 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Thu, 3 Sep 2015 13:02:24 -0700 Subject: [PATCH 054/219] changes to podspec.mustache to accept new params --- .../swagger-codegen/src/main/resources/objc/podspec.mustache | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index 9ce03695bcf1..338ded84e89c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -20,6 +20,11 @@ Pod::Spec.new do |s| s.requires_arc = true s.framework = 'SystemConfiguration' + + s.homepage = "{{gitRepoURL}}" + s.license = "{{license}}" + s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } + s.author = { "{{authorName}}" => "{{authorEmail}}" } s.source_files = '{{podName}}/**/*' s.public_header_files = '{{podName}}/**/*.h' From ba701be2f25c712d6560f927c245468152d2cf74 Mon Sep 17 00:00:00 2001 From: "sparrow.jang" Date: Fri, 4 Sep 2015 15:20:34 +0800 Subject: [PATCH 055/219] fixed a empty object for response --- .../src/main/resources/python/api_client.mustache | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 1becd5547dd5..84a1dca45ffc 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -270,7 +270,7 @@ class ApiClient(object): if klass in [int, float, str, bool]: return self.__deserialize_primitive(data, klass) elif klass == object: - return self.__deserialize_object() + return self.__deserialize_object(data) elif klass == date: return self.__deserialize_date(data) elif klass == datetime: @@ -495,13 +495,13 @@ class ApiClient(object): value = data return value - def __deserialize_object(self): + def __deserialize_object(self, value): """ - Deserializes empty object. + Return a original value. :return: object. """ - return object() + return value def __deserialize_date(self, string): """ From d22398eb7310547f8a8193310c35e0aab9dd9fd8 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Fri, 4 Sep 2015 15:24:36 -0700 Subject: [PATCH 056/219] put all values into dynamic properties map --- .../io/swagger/codegen/config/CodegenConfigurator.java | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java index 25e5f1843b81..27a6716eceb8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/config/CodegenConfigurator.java @@ -324,10 +324,7 @@ public ClientOptInput toClientOptInput() { @JsonAnySetter public CodegenConfigurator addDynamicProperty(String name, Object value) { - if (value instanceof String) { - dynamicProperties.put(name, (String) value); - } - + dynamicProperties.put(name, value.toString()); return this; } @@ -388,7 +385,7 @@ private void checkAndSetAdditionalProperty(String property, String valueToSet, S public static CodegenConfigurator fromFile(String configFile) { - if(isNotEmpty(configFile)) { + if (isNotEmpty(configFile)) { try { CodegenConfigurator result = Json.mapper().readValue(new File(configFile), CodegenConfigurator.class); return result; From 90b89c618994fa4ebd25d5044e80ecf46e846618 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 5 Sep 2015 16:48:00 +0800 Subject: [PATCH 057/219] fix typescript basepath --- .../main/resources/TypeScript-Angular/api.mustache | 2 +- .../src/main/resources/TypeScript-node/api.mustache | 2 +- samples/client/petstore/swift/PetstoreClient.podspec | 11 +++++++++++ .../petstore/typescript-angular/API/Client/PetApi.ts | 2 +- .../typescript-angular/API/Client/StoreApi.ts | 2 +- .../petstore/typescript-angular/API/Client/UserApi.ts | 2 +- samples/client/petstore/typescript-node/api.ts | 6 +++--- 7 files changed, 19 insertions(+), 8 deletions(-) create mode 100644 samples/client/petstore/swift/PetstoreClient.podspec diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 427d847663b8..23b5fe2ea50b 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -12,7 +12,7 @@ module {{package}} { */ {{/description}} export class {{classname}} { - private basePath = '{{contextPath}}'; + private basePath = '{{basePath}}'; static $inject: string[] = ['$http']; diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index f8d4577ee7ae..5f6428ce7e2a 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -95,7 +95,7 @@ class VoidAuth implements Authentication { */ {{/description}} export class {{classname}} { - private basePath = '{{contextPath}}'; + private basePath = '{{basePath}}'; public authentications = { 'default': new VoidAuth(), {{#authMethods}} diff --git a/samples/client/petstore/swift/PetstoreClient.podspec b/samples/client/petstore/swift/PetstoreClient.podspec new file mode 100644 index 000000000000..00c0ef33e12b --- /dev/null +++ b/samples/client/petstore/swift/PetstoreClient.podspec @@ -0,0 +1,11 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '8.0' + s.osx.deployment_target = '10.9' + s.version = '0.0.1' + s.source = { :git => 'git@github.com:swagger-api/swagger-mustache.git', :tag => 'v1.0.0' } + s.license = 'Apache License, Version 2.0' + s.source_files = 'PetstoreClient/Classes/Swaggers/**/*.swift' + s.dependency 'PromiseKit', '~> 2.1' + s.dependency 'Alamofire', '~> 1.3' +end diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 6bb4e10d3871..3189f6166e42 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -6,7 +6,7 @@ module API.Client { 'use strict'; export class PetApi { - private basePath = '/v2'; + private basePath = 'http://petstore.swagger.io/v2'; static $inject: string[] = ['$http']; diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 948b68593817..443ea5d0c589 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -6,7 +6,7 @@ module API.Client { 'use strict'; export class StoreApi { - private basePath = '/v2'; + private basePath = 'http://petstore.swagger.io/v2'; static $inject: string[] = ['$http']; diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index eb04f4b31f06..aaf2ef81bb15 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -6,7 +6,7 @@ module API.Client { 'use strict'; export class UserApi { - private basePath = '/v2'; + private basePath = 'http://petstore.swagger.io/v2'; static $inject: string[] = ['$http']; diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 0b7089fdaae0..52a3d7f97064 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -118,7 +118,7 @@ class VoidAuth implements Authentication { } export class UserApi { - private basePath = '/v2'; + private basePath = 'http://petstore.swagger.io/v2'; public authentications = { 'default': new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), @@ -528,7 +528,7 @@ export class UserApi { } } export class PetApi { - private basePath = '/v2'; + private basePath = 'http://petstore.swagger.io/v2'; public authentications = { 'default': new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), @@ -980,7 +980,7 @@ export class PetApi { } } export class StoreApi { - private basePath = '/v2'; + private basePath = 'http://petstore.swagger.io/v2'; public authentications = { 'default': new VoidAuth(), 'api_key': new ApiKeyAuth('header', 'api_key'), From e72a53448e7d1ae454c9008becd80a78323361cc Mon Sep 17 00:00:00 2001 From: Yissachar Radcliffe Date: Sun, 6 Sep 2015 18:35:29 -0400 Subject: [PATCH 058/219] Add Dart support --- .gitignore | 3 + bin/dart-petstore.sh | 31 ++ .../codegen/languages/DartClientCodegen.java | 282 ++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/dart/api.mustache | 83 ++++ .../main/resources/dart/apiException.mustache | 9 + .../main/resources/dart/api_client.mustache | 160 +++++++ .../src/main/resources/dart/apilib.mustache | 22 + .../resources/dart/auth/api_key_auth.mustache | 28 ++ .../dart/auth/authentication.mustache | 7 + .../dart/auth/http_basic_auth.mustache | 14 + .../main/resources/dart/auth/oauth.mustache | 9 + .../src/main/resources/dart/model.mustache | 18 + .../src/main/resources/dart/pubspec.mustache | 15 + .../petstore/dart/auth/api_key_auth.dart | 28 ++ .../petstore/dart/auth/authentication.dart | 7 + .../petstore/dart/auth/http_basic_auth.dart | 14 + samples/client/petstore/dart/auth/oauth.dart | 9 + samples/client/petstore/dart/lib/api.dart | 27 ++ .../client/petstore/dart/lib/api/pet_api.dart | 418 ++++++++++++++++++ .../petstore/dart/lib/api/store_api.dart | 201 +++++++++ .../petstore/dart/lib/api/user_api.dart | 389 ++++++++++++++++ .../client/petstore/dart/lib/api_client.dart | 179 ++++++++ .../petstore/dart/lib/api_exception.dart | 9 + .../petstore/dart/lib/auth/api_key_auth.dart | 28 ++ .../dart/lib/auth/authentication.dart | 6 + .../dart/lib/auth/http_basic_auth.dart | 14 + .../client/petstore/dart/lib/auth/oauth.dart | 9 + .../petstore/dart/lib/model/category.dart | 21 + .../client/petstore/dart/lib/model/order.dart | 33 ++ .../client/petstore/dart/lib/model/pet.dart | 33 ++ .../client/petstore/dart/lib/model/tag.dart | 21 + .../client/petstore/dart/lib/model/user.dart | 39 ++ samples/client/petstore/dart/pubspec.lock | 87 ++++ samples/client/petstore/dart/pubspec.yaml | 15 + .../client/petstore/dart/test/pet_test.dart | 85 ++++ .../client/petstore/dart/test/store_test.dart | 30 ++ samples/client/petstore/dart/test/tests.dart | 16 + samples/client/petstore/dart/test/tests.html | 14 + .../client/petstore/dart/test/user_test.dart | 63 +++ 40 files changed, 2477 insertions(+) create mode 100644 bin/dart-petstore.sh create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/dart/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/apiException.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/api_client.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/apilib.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/dart/pubspec.mustache create mode 100644 samples/client/petstore/dart/auth/api_key_auth.dart create mode 100644 samples/client/petstore/dart/auth/authentication.dart create mode 100644 samples/client/petstore/dart/auth/http_basic_auth.dart create mode 100644 samples/client/petstore/dart/auth/oauth.dart create mode 100644 samples/client/petstore/dart/lib/api.dart create mode 100644 samples/client/petstore/dart/lib/api/pet_api.dart create mode 100644 samples/client/petstore/dart/lib/api/store_api.dart create mode 100644 samples/client/petstore/dart/lib/api/user_api.dart create mode 100644 samples/client/petstore/dart/lib/api_client.dart create mode 100644 samples/client/petstore/dart/lib/api_exception.dart create mode 100644 samples/client/petstore/dart/lib/auth/api_key_auth.dart create mode 100644 samples/client/petstore/dart/lib/auth/authentication.dart create mode 100644 samples/client/petstore/dart/lib/auth/http_basic_auth.dart create mode 100644 samples/client/petstore/dart/lib/auth/oauth.dart create mode 100644 samples/client/petstore/dart/lib/model/category.dart create mode 100644 samples/client/petstore/dart/lib/model/order.dart create mode 100644 samples/client/petstore/dart/lib/model/pet.dart create mode 100644 samples/client/petstore/dart/lib/model/tag.dart create mode 100644 samples/client/petstore/dart/lib/model/user.dart create mode 100644 samples/client/petstore/dart/pubspec.lock create mode 100644 samples/client/petstore/dart/pubspec.yaml create mode 100644 samples/client/petstore/dart/test/pet_test.dart create mode 100644 samples/client/petstore/dart/test/store_test.dart create mode 100644 samples/client/petstore/dart/test/tests.dart create mode 100644 samples/client/petstore/dart/test/tests.html create mode 100644 samples/client/petstore/dart/test/user_test.dart diff --git a/.gitignore b/.gitignore index b4d421e3c554..cd7e1d286fa0 100644 --- a/.gitignore +++ b/.gitignore @@ -41,6 +41,9 @@ target .lib atlassian-ide-plugin.xml .DS_Store +packages/ +.pub +.packages samples/client/petstore/php/SwaggerClient-php/composer.lock samples/client/petstore/php/SwaggerClient-php/vendor/ diff --git a/bin/dart-petstore.sh b/bin/dart-petstore.sh new file mode 100644 index 000000000000..387d005132b2 --- /dev/null +++ b/bin/dart-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l dart -o samples/client/petstore/dart" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java new file mode 100644 index 000000000000..c22e7969e28c --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -0,0 +1,282 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.CliOption; +import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenType; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.SupportingFile; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.HashMap; + +public class DartClientCodegen extends DefaultCodegen implements CodegenConfig { + protected boolean browserClient = true; + protected String pubName = "swagger"; + protected String pubVersion = "1.0.0"; + protected String pubDescription = "Swagger API client"; + protected String sourceFolder = ""; + + public DartClientCodegen() { + super(); + outputFolder = "generated-code/dart"; + modelTemplateFiles.put("model.mustache", ".dart"); + apiTemplateFiles.put("api.mustache", ".dart"); + templateDir = "dart"; + apiPackage = "lib.api"; + modelPackage = "lib.model"; + + reservedWords = new HashSet( + Arrays.asList( + "abstract", "as", "assert", "async", "async*", "await", + "break", "case", "catch", "class", "const", "continue", + "default", "deferred", "do", "dynamic", "else", "enum", + "export", "external", "extends", "factory", "false", "final", + "finally", "for", "get", "if", "implements", "import", "in", + "is", "library", "new", "null", "operator", "part", "rethrow", + "return", "set", "static", "super", "switch", "sync*", "this", + "throw", "true", "try", "typedef", "var", "void", "while", + "with", "yield", "yield*" ) + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "bool", + "num", + "int", + "float") + ); + instantiationTypes.put("array", "List"); + instantiationTypes.put("map", "Map"); + + typeMapping = new HashMap(); + typeMapping.put("Array", "List"); + typeMapping.put("array", "List"); + typeMapping.put("List", "List"); + typeMapping.put("boolean", "bool"); + typeMapping.put("string", "String"); + typeMapping.put("int", "int"); + typeMapping.put("float", "num"); + typeMapping.put("long", "int"); + typeMapping.put("short", "int"); + typeMapping.put("char", "String"); + typeMapping.put("double", "num"); + typeMapping.put("object", "Object"); + typeMapping.put("integer", "int"); + typeMapping.put("Date", "DateTime"); + typeMapping.put("date", "DateTime"); + typeMapping.put("File", "MultipartFile"); + + cliOptions.add(new CliOption("browserClient", "Is the client browser based")); + cliOptions.add(new CliOption("pubName", "Name in generated pubspec")); + cliOptions.add(new CliOption("pubVersion", "Version in generated pubspec")); + cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + } + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "dart"; + } + + public String getHelp() { + return "Generates a Dart client library."; + } + + @Override + public void processOpts() { + super.processOpts(); + + if (additionalProperties.containsKey("browserClient")) { + this.setBrowserClient(Boolean.parseBoolean((String) additionalProperties.get("browserClient"))); + additionalProperties.put("browserClient", browserClient); + } else { + //not set, use to be passed to template + additionalProperties.put("browserClient", browserClient); + } + + if (additionalProperties.containsKey("pubName")) { + this.setPubName((String) additionalProperties.get("pubName")); + } else { + //not set, use to be passed to template + additionalProperties.put("pubName", pubName); + } + + if (additionalProperties.containsKey("pubVersion")) { + this.setPubVersion((String) additionalProperties.get("pubVersion")); + } else { + //not set, use to be passed to template + additionalProperties.put("pubVersion", pubVersion); + } + + if (additionalProperties.containsKey("pubDescription")) { + this.setPubDescription((String) additionalProperties.get("pubDescription")); + } else { + //not set, use to be passed to template + additionalProperties.put("pubDescription", pubDescription); + } + + if (additionalProperties.containsKey("sourceFolder")) { + this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + } + + final String libFolder = sourceFolder + File.separator + "lib"; + supportingFiles.add(new SupportingFile("pubspec.mustache", "", "pubspec.yaml")); + supportingFiles.add(new SupportingFile("api_client.mustache", libFolder, "api_client.dart")); + supportingFiles.add(new SupportingFile("apiException.mustache", libFolder, "api_exception.dart")); + supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart")); + + final String authFolder = sourceFolder + File.separator + "auth"; + supportingFiles.add(new SupportingFile("auth/authentication.mustache", authFolder, "authentication.dart")); + supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart")); + supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); + supportingFiles.add(new SupportingFile("auth/oauth.mustache", authFolder, "oauth.dart")); + } + + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + // camelize (lower first character) the variable name + // pet_id => petId + name = camelize(name, true); + + // for reserved word or word starting with number, append _ + if (reservedWords.contains(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if (reservedWords.contains(name)) { + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + } + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + return underscore(toModelName(name)); + } + + @Override + public String toApiFilename(String name) { + return underscore(toApiName(name)); + } + + @Override + public String toDefaultValue(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "{}"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "[]"; + } + + return super.toDefaultValue(p); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + ""; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return type; + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String toOperationId(String operationId) { + // method name cannot use reserved keyword, e.g. return + if (reservedWords.contains(operationId)) { + throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); + } + + return camelize(operationId, true); + } + + public void setBrowserClient(boolean browserClient) { + this.browserClient = browserClient; + } + + public void setPubName(String pubName) { + this.pubName = pubName; + } + + public void setPubVersion(String pubVersion) { + this.pubVersion = pubVersion; + } + + public void setPubDescription(String pubDescription) { + this.pubDescription = pubDescription; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index e98ac4622301..a73fe5f43880 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -1,6 +1,7 @@ io.swagger.codegen.languages.AndroidClientCodegen io.swagger.codegen.languages.AsyncScalaClientCodegen io.swagger.codegen.languages.CSharpClientCodegen +io.swagger.codegen.languages.DartClientCodegen io.swagger.codegen.languages.FlashClientCodegen io.swagger.codegen.languages.JavaClientCodegen io.swagger.codegen.languages.JaxRSServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/dart/api.mustache b/modules/swagger-codegen/src/main/resources/dart/api.mustache new file mode 100644 index 000000000000..51216a11c958 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api.mustache @@ -0,0 +1,83 @@ +part of api; + +{{#operations}} + +class {{classname}} { + String basePath = "{{basePath}}"; + ApiClient apiClient = ApiClient.defaultApiClient; + + {{classname}}([ApiClient apiClient]) { + if (apiClient != null) { + this.apiClient = apiClient; + } + } + + {{#operation}} + /// {{summary}} + /// + /// {{notes}} + {{#returnType}}Future<{{{returnType}}}> {{/returnType}}{{^returnType}}Future {{/returnType}}{{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#requiredParamCount}} + // verify required params are set + if({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { + throw new ApiException(400, "missing required params"); + }{{/requiredParamCount}} + + // create path and map variables + String path = "{{path}}".replaceAll("{format}","json"){{#pathParams}}.replaceAll("{" + "{{paramName}}" + "}", {{{paramName}}}.toString()){{/pathParams}}; + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + {{#queryParams}}if("null" != {{paramName}}) + queryParams["{{baseName}}"] = {{paramName}} is List ? {{paramName}}.join(',') : {{paramName}}; + {{/queryParams}} + {{#headerParams}}headerParams["{{baseName}}"] = {{paramName}}; + {{/headerParams}} + + List contentTypes = [{{#consumes}}"{{mediaType}}"{{#hasMore}},{{/hasMore}}{{/consumes}}]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = [{{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + {{#formParams}}{{#notFile}} + if ({{paramName}} != null) { + hasFields = true; + mp.fields['{{baseName}}'] = apiClient.parameterToString({{paramName}}); + } + {{/notFile}}{{#isFile}} + if ({{paramName}} != null) { + hasFields = true; + mp.fields['{{baseName}}'] = {{paramName}}.field; + mp.files.add({{paramName}}); + } + {{/isFile}}{{/formParams}} + if(hasFields) + postBody = mp; + } + else { + {{#formParams}}{{#notFile}}if ({{paramName}} != null) + formParams['{{baseName}}'] = apiClient.parameterToString({{paramName}});{{/notFile}} + {{/formParams}} + } + + return apiClient.invokeAPI(basePath, path, '{{httpMethod}}', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return {{#returnType}}ApiClient.deserialize(response.body, {{returnBaseType}}){{/returnType}}; + } + else { + return {{#returnType}}null{{/returnType}}; + } + }); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/dart/apiException.mustache b/modules/swagger-codegen/src/main/resources/dart/apiException.mustache new file mode 100644 index 000000000000..c168fb512da4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/apiException.mustache @@ -0,0 +1,9 @@ +part of api; + +class ApiException implements Exception { + int code = 0; + String message = null; + + ApiException(this.code, this.message); + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/api_client.mustache b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache new file mode 100644 index 000000000000..92fa90d62612 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/api_client.mustache @@ -0,0 +1,160 @@ +part of api; + +class ApiClient { + static ApiClient defaultApiClient = new ApiClient(); + + Map _defaultHeaderMap = {}; + Map _authentications = {}; + static final dson = new Dartson.JSON(); + final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + ApiClient() { + // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}} + _authentications['{{name}}'] = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} + _authentications['{{name}}'] = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} + _authentications['{{name}}'] = new OAuth();{{/isOAuth}}{{/authMethods}} + } + + void addDefaultHeader(String key, String value) { + _defaultHeaderMap[key] = value; + } + + /// Format the given Date object into string. + String formatDate(DateTime date) { + return _dateFormatter.format(date); + } + + /// Format the given parameter object into string. + String parameterToString(Object param) { + if (param == null) { + return ''; + } else if (param is DateTime) { + return formatDate(param); + } else if (param is List) { + return (param).join(','); + } else { + return param.toString(); + } + } + + static dynamic deserialize(String json, dynamic clazz) { + var result = json; + + try { + var decodedJson = JSON.decode(json); + + if(decodedJson is List) { + result = []; + for(var obj in decodedJson) { + result.add(_createEntity(obj, clazz)); + } + } else { + result = _createEntity(json, clazz); + } + } on FormatException { + // Just return the passed in value + } + + return result; + } + + static dynamic _createEntity(dynamic json, dynamic clazz) { + bool isMap = json is Map; + + switch(clazz) { + {{#models}} + {{#model}} + case {{classname}}: + return isMap ? dson.map(json, new {{classname}}()) : dson.decode(json, new {{classname}}()); + {{/model}} + {{/models}} + default: + throw new ApiException(500, 'Could not find a suitable class for deserialization'); + } + } + + static String serialize(Object obj) { + String serialized = ''; + if (obj == null) { + serialized = ''; + } else if (obj is String) { + serialized = obj; + } else { + serialized = dson.encode(obj); + } + return serialized; + } + + Future invokeAPI( String host, + String path, + String method, + Map queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) { + + updateParamsForAuth(authNames, queryParams, headerParams); + + var client = new {{#browserClient}}Browser{{/browserClient}}Client(); + + StringBuffer sb = new StringBuffer(); + + for(String key in queryParams.keys) { + String value = queryParams[key]; + if (value != null){ + if(sb.toString().length == 0) { + sb.write("?"); + } else { + sb.write("&"); + } + sb.write(key); + sb.write("="); + sb.write(value); + } + } + String querystring = sb.toString(); + + String url = host + path + querystring; + + headerParams.addAll(_defaultHeaderMap); + headerParams['Content-Type'] = contentType; + + var completer = new Completer(); + + if(body is MultipartRequest) { + var request = new MultipartRequest(method, Uri.parse(url)); + request.fields.addAll(body.fields); + request.files.addAll(body.files); + request.headers.addAll(body.headers); + request.headers.addAll(headerParams); + client.send(request).then((response) => completer.complete(Response.fromStream(response))); + } else { + var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); + switch(method) { + case "GET": + return client.get(url, headers: headerParams); + case "POST": + return client.post(url, headers: headerParams, body: msgBody); + case "PUT": + return client.put(url, headers: headerParams, body: msgBody); + case "DELETE": + return client.delete(url, headers: headerParams); + } + } + + return completer.future; + } + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { + authNames.forEach((authName) { + Authentication auth = _authentications[authName]; + if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + }); + } + +} diff --git a/modules/swagger-codegen/src/main/resources/dart/apilib.mustache b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache new file mode 100644 index 000000000000..f96993155660 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/apilib.mustache @@ -0,0 +1,22 @@ +library api; + +import 'dart:async'; +import 'dart:convert';{{#browserClient}} +import 'dart:html'; +import 'package:http/browser_client.dart';{{/browserClient}} +import 'package:http/http.dart'; +import 'package:dartson/dartson.dart'; +import 'package:crypto/crypto.dart'; +import 'package:intl/intl.dart'; + +part 'api_client.dart'; +part 'api_exception.dart'; +part 'auth/authentication.dart'; +part 'auth/api_key_auth.dart'; +part 'auth/oauth.dart'; +part 'auth/http_basic_auth.dart'; + +{{#apiInfo}}{{#apis}}part 'api/{{classVarName}}_api.dart'; +{{/apis}}{{/apiInfo}} +{{#models}}{{#model}}part 'model/{{classVarName}}.dart'; +{{/model}}{{/models}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache new file mode 100644 index 000000000000..6e728ae916ba --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/auth/api_key_auth.mustache @@ -0,0 +1,28 @@ +part of api; + +class ApiKeyAuth implements Authentication { + + final String location; + final String paramName; + String apiKey; + String apiKeyPrefix; + + ApiKeyAuth(this.location, this.paramName); + + @override + void applyToParams(Map queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = '$apiKeyPrefix $apiKey'; + } else { + value = apiKey; + } + + if (location == 'query' && value != null) { + queryParams[paramName] = value; + } else if (location == 'header' && value != null) { + headerParams[paramName] = value; + } + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache new file mode 100644 index 000000000000..4833af90ec0d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/auth/authentication.mustache @@ -0,0 +1,7 @@ +part of api; + +abstract class Authentication { + + /// Apply authentication settings to header and query params. + void applyToParams(Map queryParams, Map headerParams); +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache new file mode 100644 index 000000000000..e681c25653db --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/auth/http_basic_auth.mustache @@ -0,0 +1,14 @@ +part of api; + +class HttpBasicAuth implements Authentication { + + String username; + String password; + + @override + void applyToParams(Map queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache new file mode 100644 index 000000000000..5e3e2c8b260d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/auth/oauth.mustache @@ -0,0 +1,9 @@ +part of api; + +class OAuth implements Authentication { + + @override + void applyToParams(Map queryParams, Map headerParams) { + // TODO: support oauth + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/dart/model.mustache b/modules/swagger-codegen/src/main/resources/dart/model.mustache new file mode 100644 index 000000000000..c0c4789c00b3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/model.mustache @@ -0,0 +1,18 @@ +part of api; + +{{#models}}{{#model}} +@Entity() +class {{classname}} { + {{#vars}}{{#description}}/* {{{description}}} */{{/description}} + {{{datatype}}} {{name}} = {{{defaultValue}}}; + {{#allowableValues}}{{#min}} // range from {{min}} to {{max}}{{/min}}//{{^min}}enum {{name}}Enum { {{#values}} {{.}}, {{/values}} };{{/min}}{{/allowableValues}} + {{/vars}} + {{classname}}(); + + @override + String toString() { + return '{{classname}}[{{#vars}}{{name}}=${{name}}, {{/vars}}]'; + } + +} +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache new file mode 100644 index 000000000000..97bf9c1defd8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/dart/pubspec.mustache @@ -0,0 +1,15 @@ +name: {{pubName}} +version: {{pubVersion}} +description: {{pubDescription}} +dependencies: + http: '>=0.11.1 <0.12.0' + dartson: "^0.2.4" + crypto: "^0.9.0" + intl: "^0.12.4+2" + +dev_dependencies: + guinness: '^0.1.17' + browser: any + +transformers: + - dartson diff --git a/samples/client/petstore/dart/auth/api_key_auth.dart b/samples/client/petstore/dart/auth/api_key_auth.dart new file mode 100644 index 000000000000..6e728ae916ba --- /dev/null +++ b/samples/client/petstore/dart/auth/api_key_auth.dart @@ -0,0 +1,28 @@ +part of api; + +class ApiKeyAuth implements Authentication { + + final String location; + final String paramName; + String apiKey; + String apiKeyPrefix; + + ApiKeyAuth(this.location, this.paramName); + + @override + void applyToParams(Map queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = '$apiKeyPrefix $apiKey'; + } else { + value = apiKey; + } + + if (location == 'query' && value != null) { + queryParams[paramName] = value; + } else if (location == 'header' && value != null) { + headerParams[paramName] = value; + } + } + +} \ No newline at end of file diff --git a/samples/client/petstore/dart/auth/authentication.dart b/samples/client/petstore/dart/auth/authentication.dart new file mode 100644 index 000000000000..4833af90ec0d --- /dev/null +++ b/samples/client/petstore/dart/auth/authentication.dart @@ -0,0 +1,7 @@ +part of api; + +abstract class Authentication { + + /// Apply authentication settings to header and query params. + void applyToParams(Map queryParams, Map headerParams); +} \ No newline at end of file diff --git a/samples/client/petstore/dart/auth/http_basic_auth.dart b/samples/client/petstore/dart/auth/http_basic_auth.dart new file mode 100644 index 000000000000..e681c25653db --- /dev/null +++ b/samples/client/petstore/dart/auth/http_basic_auth.dart @@ -0,0 +1,14 @@ +part of api; + +class HttpBasicAuth implements Authentication { + + String username; + String password; + + @override + void applyToParams(Map queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + } + +} \ No newline at end of file diff --git a/samples/client/petstore/dart/auth/oauth.dart b/samples/client/petstore/dart/auth/oauth.dart new file mode 100644 index 000000000000..5e3e2c8b260d --- /dev/null +++ b/samples/client/petstore/dart/auth/oauth.dart @@ -0,0 +1,9 @@ +part of api; + +class OAuth implements Authentication { + + @override + void applyToParams(Map queryParams, Map headerParams) { + // TODO: support oauth + } +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/api.dart b/samples/client/petstore/dart/lib/api.dart new file mode 100644 index 000000000000..3dba4e66eef1 --- /dev/null +++ b/samples/client/petstore/dart/lib/api.dart @@ -0,0 +1,27 @@ +library api; + +import 'dart:async'; +import 'dart:convert'; +import 'dart:html'; +import 'package:http/browser_client.dart'; +import 'package:http/http.dart'; +import 'package:dartson/dartson.dart'; +import 'package:crypto/crypto.dart'; +import 'package:intl/intl.dart'; + +part 'api_client.dart'; +part 'api_exception.dart'; +part 'auth/authentication.dart'; +part 'auth/api_key_auth.dart'; +part 'auth/oauth.dart'; +part 'auth/http_basic_auth.dart'; + +part 'api/user_api.dart'; +part 'api/store_api.dart'; +part 'api/pet_api.dart'; + +part 'model/user.dart'; +part 'model/category.dart'; +part 'model/pet.dart'; +part 'model/tag.dart'; +part 'model/order.dart'; diff --git a/samples/client/petstore/dart/lib/api/pet_api.dart b/samples/client/petstore/dart/lib/api/pet_api.dart new file mode 100644 index 000000000000..b800b535d84c --- /dev/null +++ b/samples/client/petstore/dart/lib/api/pet_api.dart @@ -0,0 +1,418 @@ +part of api; + + + +class PetApi { + String basePath = "http://petstore.swagger.io/v2"; + ApiClient apiClient = ApiClient.defaultApiClient; + + PetApi([ApiClient apiClient]) { + if (apiClient != null) { + this.apiClient = apiClient; + } + } + + + /// Update an existing pet + /// + /// + Future updatePet(Pet body) { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = ["application/json","application/xml"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Add a new pet to the store + /// + /// + Future addPet(Pet body) { + Object postBody = body; + + + // create path and map variables + String path = "/pet".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = ["application/json","application/xml"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Finds Pets by status + /// + /// Multiple status values can be provided with comma seperated strings + Future> findPetsByStatus(List status) { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByStatus".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + if("null" != status) + queryParams["status"] = status is List ? status.join(',') : status; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, Pet); + } + else { + return null; + } + }); + } + + /// Finds Pets by tags + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + Future> findPetsByTags(List tags) { + Object postBody = null; + + + // create path and map variables + String path = "/pet/findByTags".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + if("null" != tags) + queryParams["tags"] = tags is List ? tags.join(',') : tags; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, Pet); + } + else { + return null; + } + }); + } + + /// Find pet by ID + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + Future getPetById(int petId) { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth", "api_key"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, Pet); + } + else { + return null; + } + }); + } + + /// Updates a pet in the store with form data + /// + /// + Future updatePetWithForm(String petId, String name, String status) { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = ["application/x-www-form-urlencoded"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if (name != null) { + hasFields = true; + mp.fields['name'] = apiClient.parameterToString(name); + } + + if (status != null) { + hasFields = true; + mp.fields['status'] = apiClient.parameterToString(status); + } + + if(hasFields) + postBody = mp; + } + else { + if (name != null) + formParams['name'] = apiClient.parameterToString(name); + if (status != null) + formParams['status'] = apiClient.parameterToString(status); + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Deletes a pet + /// + /// + Future deletePet(int petId, String apiKey) { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + headerParams["api_key"] = apiKey; + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// uploads an image + /// + /// + Future uploadFile(int petId, String additionalMetadata, MultipartFile file) { + Object postBody = null; + + + // create path and map variables + String path = "/pet/{petId}/uploadImage".replaceAll("{format}","json").replaceAll("{" + "petId" + "}", petId.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = ["multipart/form-data"]; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["petstore_auth"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if (additionalMetadata != null) { + hasFields = true; + mp.fields['additionalMetadata'] = apiClient.parameterToString(additionalMetadata); + } + + if (file != null) { + hasFields = true; + mp.fields['file'] = file.field; + mp.files.add(file); + } + + if(hasFields) + postBody = mp; + } + else { + if (additionalMetadata != null) + formParams['additionalMetadata'] = apiClient.parameterToString(additionalMetadata); + + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + +} + diff --git a/samples/client/petstore/dart/lib/api/store_api.dart b/samples/client/petstore/dart/lib/api/store_api.dart new file mode 100644 index 000000000000..fb346e317ee7 --- /dev/null +++ b/samples/client/petstore/dart/lib/api/store_api.dart @@ -0,0 +1,201 @@ +part of api; + + + +class StoreApi { + String basePath = "http://petstore.swagger.io/v2"; + ApiClient apiClient = ApiClient.defaultApiClient; + + StoreApi([ApiClient apiClient]) { + if (apiClient != null) { + this.apiClient = apiClient; + } + } + + + /// Returns pet inventories by status + /// + /// Returns a map of status codes to quantities + Future> getInventory() { + Object postBody = null; + + + // create path and map variables + String path = "/store/inventory".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = ["api_key"]; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, Map); + } + else { + return null; + } + }); + } + + /// Place an order for a pet + /// + /// + Future placeOrder(Order body) { + Object postBody = body; + + + // create path and map variables + String path = "/store/order".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, Order); + } + else { + return null; + } + }); + } + + /// Find purchase order by ID + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + Future getOrderById(String orderId) { + Object postBody = null; + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, Order); + } + else { + return null; + } + }); + } + + /// Delete purchase order by ID + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + Future deleteOrder(String orderId) { + Object postBody = null; + + + // create path and map variables + String path = "/store/order/{orderId}".replaceAll("{format}","json").replaceAll("{" + "orderId" + "}", orderId.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + +} + diff --git a/samples/client/petstore/dart/lib/api/user_api.dart b/samples/client/petstore/dart/lib/api/user_api.dart new file mode 100644 index 000000000000..b8e7bc0f1498 --- /dev/null +++ b/samples/client/petstore/dart/lib/api/user_api.dart @@ -0,0 +1,389 @@ +part of api; + + + +class UserApi { + String basePath = "http://petstore.swagger.io/v2"; + ApiClient apiClient = ApiClient.defaultApiClient; + + UserApi([ApiClient apiClient]) { + if (apiClient != null) { + this.apiClient = apiClient; + } + } + + + /// Create user + /// + /// This can only be done by the logged in user. + Future createUser(User body) { + Object postBody = body; + + + // create path and map variables + String path = "/user".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Creates list of users with given input array + /// + /// + Future createUsersWithArrayInput(List body) { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithArray".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Creates list of users with given input array + /// + /// + Future createUsersWithListInput(List body) { + Object postBody = body; + + + // create path and map variables + String path = "/user/createWithList".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'POST', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Logs user into the system + /// + /// + Future loginUser(String username, String password) { + Object postBody = null; + + + // create path and map variables + String path = "/user/login".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + if("null" != username) + queryParams["username"] = username is List ? username.join(',') : username; + if("null" != password) + queryParams["password"] = password is List ? password.join(',') : password; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, String); + } + else { + return null; + } + }); + } + + /// Logs out current logged in user session + /// + /// + Future logoutUser() { + Object postBody = null; + + + // create path and map variables + String path = "/user/logout".replaceAll("{format}","json"); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Get user by user name + /// + /// + Future getUserByName(String username) { + Object postBody = null; + + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'GET', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ApiClient.deserialize(response.body, User); + } + else { + return null; + } + }); + } + + /// Updated user + /// + /// This can only be done by the logged in user. + Future updateUser(String username, User body) { + Object postBody = body; + + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'PUT', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + + /// Delete user + /// + /// This can only be done by the logged in user. + Future deleteUser(String username) { + Object postBody = null; + + + // create path and map variables + String path = "/user/{username}".replaceAll("{format}","json").replaceAll("{" + "username" + "}", username.toString()); + + // query params + Map queryParams = {}; + Map headerParams = {}; + Map formParams = {}; + + + + List contentTypes = []; + + String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; + List authNames = []; + + if(contentType.startsWith("multipart/form-data")) { + bool hasFields = false; + MultipartRequest mp = new MultipartRequest(null, null); + + if(hasFields) + postBody = mp; + } + else { + + } + + return apiClient.invokeAPI(basePath, path, 'DELETE', queryParams, postBody, headerParams, formParams, contentType, authNames).then((response) { + if(response.statusCode >= 400) { + throw new ApiException(response.statusCode, response.body); + } + else if(response.body != null){ + return ; + } + else { + return ; + } + }); + } + +} + diff --git a/samples/client/petstore/dart/lib/api_client.dart b/samples/client/petstore/dart/lib/api_client.dart new file mode 100644 index 000000000000..82cecd7db495 --- /dev/null +++ b/samples/client/petstore/dart/lib/api_client.dart @@ -0,0 +1,179 @@ +part of api; + +class ApiClient { + static ApiClient defaultApiClient = new ApiClient(); + + Map _defaultHeaderMap = {}; + Map _authentications = {}; + static final dson = new Dartson.JSON(); + final DateFormat _dateFormatter = new DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); + + ApiClient() { + // Setup authentications (key: authentication name, value: authentication). + _authentications['api_key'] = new ApiKeyAuth("header", "api_key"); + _authentications['petstore_auth'] = new OAuth(); + } + + void addDefaultHeader(String key, String value) { + _defaultHeaderMap[key] = value; + } + + /// Format the given Date object into string. + String formatDate(DateTime date) { + return _dateFormatter.format(date); + } + + /// Format the given parameter object into string. + String parameterToString(Object param) { + if (param == null) { + return ''; + } else if (param is DateTime) { + return formatDate(param); + } else if (param is List) { + return (param).join(','); + } else { + return param.toString(); + } + } + + static dynamic deserialize(String json, dynamic clazz) { + var result = json; + + try { + var decodedJson = JSON.decode(json); + + if(decodedJson is List) { + result = []; + for(var obj in decodedJson) { + result.add(_createEntity(obj, clazz)); + } + } else { + result = _createEntity(json, clazz); + } + } on FormatException { + // Just return the passed in value + } + + return result; + } + + static dynamic _createEntity(dynamic json, dynamic clazz) { + bool isMap = json is Map; + + switch(clazz) { + + + case User: + return isMap ? dson.map(json, new User()) : dson.decode(json, new User()); + + + + case Category: + return isMap ? dson.map(json, new Category()) : dson.decode(json, new Category()); + + + + case Pet: + return isMap ? dson.map(json, new Pet()) : dson.decode(json, new Pet()); + + + + case Tag: + return isMap ? dson.map(json, new Tag()) : dson.decode(json, new Tag()); + + + + case Order: + return isMap ? dson.map(json, new Order()) : dson.decode(json, new Order()); + + + default: + throw new ApiException(500, 'Could not find a suitable class for deserialization'); + } + } + + static String serialize(Object obj) { + String serialized = ''; + if (obj == null) { + serialized = ''; + } else if (obj is String) { + serialized = obj; + } else { + serialized = dson.encode(obj); + } + return serialized; + } + + Future invokeAPI( String host, + String path, + String method, + Map queryParams, + Object body, + Map headerParams, + Map formParams, + String contentType, + List authNames) { + + updateParamsForAuth(authNames, queryParams, headerParams); + + var client = new BrowserClient(); + + StringBuffer sb = new StringBuffer(); + + for(String key in queryParams.keys) { + String value = queryParams[key]; + if (value != null){ + if(sb.toString().length == 0) { + sb.write("?"); + } else { + sb.write("&"); + } + sb.write(key); + sb.write("="); + sb.write(value); + } + } + String querystring = sb.toString(); + + String url = host + path + querystring; + + headerParams.addAll(_defaultHeaderMap); + headerParams['Content-Type'] = contentType; + + var completer = new Completer(); + + if(body is MultipartRequest) { + var request = new MultipartRequest(method, Uri.parse(url)); + request.fields.addAll(body.fields); + request.files.addAll(body.files); + request.headers.addAll(body.headers); + request.headers.addAll(headerParams); + client.send(request).then((response) => completer.complete(Response.fromStream(response))); + } else { + var msgBody = contentType == "application/x-www-form-urlencoded" ? formParams : serialize(body); + switch(method) { + case "GET": + return client.get(url, headers: headerParams); + case "POST": + return client.post(url, headers: headerParams, body: msgBody); + case "PUT": + return client.put(url, headers: headerParams, body: msgBody); + case "DELETE": + return client.delete(url, headers: headerParams); + } + } + + return completer.future; + } + + /// Update query and header parameters based on authentication settings. + /// @param authNames The authentications to apply + void updateParamsForAuth(List authNames, Map queryParams, Map headerParams) { + authNames.forEach((authName) { + Authentication auth = _authentications[authName]; + if (auth == null) throw new ArgumentError("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams); + }); + } + +} diff --git a/samples/client/petstore/dart/lib/api_exception.dart b/samples/client/petstore/dart/lib/api_exception.dart new file mode 100644 index 000000000000..c168fb512da4 --- /dev/null +++ b/samples/client/petstore/dart/lib/api_exception.dart @@ -0,0 +1,9 @@ +part of api; + +class ApiException implements Exception { + int code = 0; + String message = null; + + ApiException(this.code, this.message); + +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/api_key_auth.dart b/samples/client/petstore/dart/lib/auth/api_key_auth.dart new file mode 100644 index 000000000000..6e728ae916ba --- /dev/null +++ b/samples/client/petstore/dart/lib/auth/api_key_auth.dart @@ -0,0 +1,28 @@ +part of api; + +class ApiKeyAuth implements Authentication { + + final String location; + final String paramName; + String apiKey; + String apiKeyPrefix; + + ApiKeyAuth(this.location, this.paramName); + + @override + void applyToParams(Map queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = '$apiKeyPrefix $apiKey'; + } else { + value = apiKey; + } + + if (location == 'query' && value != null) { + queryParams[paramName] = value; + } else if (location == 'header' && value != null) { + headerParams[paramName] = value; + } + } + +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/authentication.dart b/samples/client/petstore/dart/lib/auth/authentication.dart new file mode 100644 index 000000000000..b4aa90651f6b --- /dev/null +++ b/samples/client/petstore/dart/lib/auth/authentication.dart @@ -0,0 +1,6 @@ +part of api; + +abstract class Authentication { + + void applyToParams(Map queryParams, Map headerParams); +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/http_basic_auth.dart b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart new file mode 100644 index 000000000000..e681c25653db --- /dev/null +++ b/samples/client/petstore/dart/lib/auth/http_basic_auth.dart @@ -0,0 +1,14 @@ +part of api; + +class HttpBasicAuth implements Authentication { + + String username; + String password; + + @override + void applyToParams(Map queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); + } + +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/oauth.dart b/samples/client/petstore/dart/lib/auth/oauth.dart new file mode 100644 index 000000000000..5e3e2c8b260d --- /dev/null +++ b/samples/client/petstore/dart/lib/auth/oauth.dart @@ -0,0 +1,9 @@ +part of api; + +class OAuth implements Authentication { + + @override + void applyToParams(Map queryParams, Map headerParams) { + // TODO: support oauth + } +} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/model/category.dart b/samples/client/petstore/dart/lib/model/category.dart new file mode 100644 index 000000000000..d036a2b186ac --- /dev/null +++ b/samples/client/petstore/dart/lib/model/category.dart @@ -0,0 +1,21 @@ +part of api; + + +@Entity() +class Category { + + int id = null; + + + String name = null; + + + Category(); + + @override + String toString() { + return 'Category[id=$id, name=$name, ]'; + } + +} + diff --git a/samples/client/petstore/dart/lib/model/order.dart b/samples/client/petstore/dart/lib/model/order.dart new file mode 100644 index 000000000000..487f5fad6447 --- /dev/null +++ b/samples/client/petstore/dart/lib/model/order.dart @@ -0,0 +1,33 @@ +part of api; + + +@Entity() +class Order { + + int id = null; + + + int petId = null; + + + int quantity = null; + + + DateTime shipDate = null; + + /* Order Status */ + String status = null; + //enum statusEnum { placed, approved, delivered, }; + + bool complete = null; + + + Order(); + + @override + String toString() { + return 'Order[id=$id, petId=$petId, quantity=$quantity, shipDate=$shipDate, status=$status, complete=$complete, ]'; + } + +} + diff --git a/samples/client/petstore/dart/lib/model/pet.dart b/samples/client/petstore/dart/lib/model/pet.dart new file mode 100644 index 000000000000..133cc2eb4ad2 --- /dev/null +++ b/samples/client/petstore/dart/lib/model/pet.dart @@ -0,0 +1,33 @@ +part of api; + + +@Entity() +class Pet { + + int id = null; + + + Category category = null; + + + String name = null; + + + List photoUrls = []; + + + List tags = []; + + /* pet status in the store */ + String status = null; + //enum statusEnum { available, pending, sold, }; + + Pet(); + + @override + String toString() { + return 'Pet[id=$id, category=$category, name=$name, photoUrls=$photoUrls, tags=$tags, status=$status, ]'; + } + +} + diff --git a/samples/client/petstore/dart/lib/model/tag.dart b/samples/client/petstore/dart/lib/model/tag.dart new file mode 100644 index 000000000000..36cbb19a7965 --- /dev/null +++ b/samples/client/petstore/dart/lib/model/tag.dart @@ -0,0 +1,21 @@ +part of api; + + +@Entity() +class Tag { + + int id = null; + + + String name = null; + + + Tag(); + + @override + String toString() { + return 'Tag[id=$id, name=$name, ]'; + } + +} + diff --git a/samples/client/petstore/dart/lib/model/user.dart b/samples/client/petstore/dart/lib/model/user.dart new file mode 100644 index 000000000000..4e09c4559417 --- /dev/null +++ b/samples/client/petstore/dart/lib/model/user.dart @@ -0,0 +1,39 @@ +part of api; + + +@Entity() +class User { + + int id = null; + + + String username = null; + + + String firstName = null; + + + String lastName = null; + + + String email = null; + + + String password = null; + + + String phone = null; + + /* User Status */ + int userStatus = null; + + + User(); + + @override + String toString() { + return 'User[id=$id, username=$username, firstName=$firstName, lastName=$lastName, email=$email, password=$password, phone=$phone, userStatus=$userStatus, ]'; + } + +} + diff --git a/samples/client/petstore/dart/pubspec.lock b/samples/client/petstore/dart/pubspec.lock new file mode 100644 index 000000000000..1e4ba01779c3 --- /dev/null +++ b/samples/client/petstore/dart/pubspec.lock @@ -0,0 +1,87 @@ +# Generated by pub +# See http://pub.dartlang.org/doc/glossary.html#lockfile +packages: + analyzer: + description: analyzer + source: hosted + version: "0.25.0+1" + args: + description: args + source: hosted + version: "0.13.2" + barback: + description: barback + source: hosted + version: "0.15.2+4" + browser: + description: browser + source: hosted + version: "0.10.0+2" + collection: + description: collection + source: hosted + version: "1.1.1" + crypto: + description: crypto + source: hosted + version: "0.9.0" + dartson: + description: dartson + source: hosted + version: "0.2.4" + guinness: + description: guinness + source: hosted + version: "0.1.17" + http: + description: http + source: hosted + version: "0.11.2" + http_parser: + description: http_parser + source: hosted + version: "0.0.2+7" + intl: + description: intl + source: hosted + version: "0.12.4+2" + logging: + description: logging + source: hosted + version: "0.9.3" + path: + description: path + source: hosted + version: "1.3.6" + petitparser: + description: petitparser + source: hosted + version: "1.4.3" + pool: + description: pool + source: hosted + version: "1.1.0" + source_maps: + description: source_maps + source: hosted + version: "0.10.1" + source_span: + description: source_span + source: hosted + version: "1.1.2" + stack_trace: + description: stack_trace + source: hosted + version: "1.3.4" + string_scanner: + description: string_scanner + source: hosted + version: "0.1.3+1" + unittest: + description: unittest + source: hosted + version: "0.11.6+1" + watcher: + description: watcher + source: hosted + version: "0.9.6" diff --git a/samples/client/petstore/dart/pubspec.yaml b/samples/client/petstore/dart/pubspec.yaml new file mode 100644 index 000000000000..cbc62b63ca1d --- /dev/null +++ b/samples/client/petstore/dart/pubspec.yaml @@ -0,0 +1,15 @@ +name: swagger +version: 1.0.0 +description: Swagger API client +dependencies: + http: '>=0.11.1 <0.12.0' + dartson: "^0.2.4" + crypto: "^0.9.0" + intl: "^0.12.4+2" + +dev_dependencies: + guinness: '^0.1.17' + browser: any + +transformers: + - dartson diff --git a/samples/client/petstore/dart/test/pet_test.dart b/samples/client/petstore/dart/test/pet_test.dart new file mode 100644 index 000000000000..f93c3ea3e373 --- /dev/null +++ b/samples/client/petstore/dart/test/pet_test.dart @@ -0,0 +1,85 @@ +part of tests; + +testPetApi() { + var petApi = new PetApi(); + + describe('Pet API ', () { + it('adds a new pet and gets it by id', () async { + var id = 137; + + await petApi.addPet(new Pet()..id = id); + var pet = await petApi.getPetById(id); + expect(pet.id).toEqual(id); + }); + + it('doesn\'t get non-existing pet by id', () { + expect(petApi.getPetById(6789099)).toThrowWith(anInstanceOf: ApiException); + }); + + it('deletes existing pet by id', () async { + var id = 7689; + await petApi.addPet(new Pet()..id = id); + await petApi.deletePet(id, 'special-key'); + expect(petApi.getPetById(id)).toThrowWith(anInstanceOf: ApiException); + }); + + it('updates pet with form', () async { + var id = 52341; + await petApi.addPet(new Pet()..id = id..name='Snowy'); + await petApi.updatePetWithForm('$id', 'Doge', ''); + var pet = await petApi.getPetById(id); + expect(pet.name).toEqual('Doge'); + }); + + it('updates existing pet', () async { + var id = 900001; + var name = 'Snowy'; + + await petApi.addPet(new Pet()..id = id); + await petApi.updatePet(new Pet()..id = id..name = name); + var pet = await petApi.getPetById(id); + expect(pet.name).toEqual(name); + }); + + it('finds pets by status', () async { + var id1 = 754111; + var id2 = 1231341; + var id3 = 6776251; + var status = 'available'; + + return Future.wait([petApi.addPet(new Pet()..id = id1..status = status), + petApi.addPet(new Pet()..id = id2..status = status), + petApi.addPet(new Pet()..id = id3..status = 'sold')]) + .then((_) async { + + var pets = await petApi.findPetsByStatus([status]); + var petIds = pets.map((pet) => pet.id).toList(); + expect(petIds).toContain(id1); + expect(petIds).toContain(id2); + expect(petIds).not.toContain(id3); + }); + }); + + it('finds pets by tag', () async { + var snowyId = 253156; + var grumpyId = 734215; + var snowyTags = [new Tag()..id=12211..name='terrier']; + var grumpyTags = [new Tag()..id=455803..name='grumpy']; + await petApi.addPet(new Pet()..id = snowyId..name = 'Snowy'..tags = snowyTags); + await petApi.addPet(new Pet()..id = grumpyId..name = 'Grumpy Cat'..tags = grumpyTags); + + var pets = await petApi.findPetsByTags(['grumpy']); + var petIds = pets.map((pet) => pet.id).toList(); + expect(petIds).toContain(grumpyId); + expect(petIds).not.toContain(snowyId); + }); + + it('uploads a pet image', () async { + var id = 672322; + await petApi.addPet(new Pet()..id = id); + var file = new MultipartFile.fromBytes('file', [104, 101, 108, 108, 111]); + await petApi.uploadFile(id, '', file); + }); + + }); +} \ No newline at end of file diff --git a/samples/client/petstore/dart/test/store_test.dart b/samples/client/petstore/dart/test/store_test.dart new file mode 100644 index 000000000000..692760f1be10 --- /dev/null +++ b/samples/client/petstore/dart/test/store_test.dart @@ -0,0 +1,30 @@ +part of tests; + +testStoreApi() { + var storeApi = new StoreApi(); + + describe('Store API ', () async { + + it('places an order and gets it by id', () async { + var id = 4356; + + await storeApi.placeOrder(new Order()..id = id); + var order = await storeApi.getOrderById(id.toString()); + expect(order.id).toEqual(id); + }); + + it('deletes an order', () async { + var id = 637211; + + await storeApi.placeOrder(new Order()..id = id); + await storeApi.deleteOrder(id.toString()); + expect(storeApi.getOrderById(id.toString())).toThrowWith(anInstanceOf: ApiException); + }); + + it('gets the store inventory', () async { + Map inventory = await storeApi.getInventory(); + expect(inventory.length).not.toBe(0); + }); + + }); +} \ No newline at end of file diff --git a/samples/client/petstore/dart/test/tests.dart b/samples/client/petstore/dart/test/tests.dart new file mode 100644 index 000000000000..173a5587a4d8 --- /dev/null +++ b/samples/client/petstore/dart/test/tests.dart @@ -0,0 +1,16 @@ +library tests; + +import 'dart:async'; +import 'package:http/http.dart'; +import 'package:guinness/guinness.dart'; +import 'package:swagger/api.dart'; + +part 'pet_test.dart'; +part 'store_test.dart'; +part 'user_test.dart'; + +main() { + testPetApi(); + testStoreApi(); + testUserApi(); +} \ No newline at end of file diff --git a/samples/client/petstore/dart/test/tests.html b/samples/client/petstore/dart/test/tests.html new file mode 100644 index 000000000000..e3796c5fcfe2 --- /dev/null +++ b/samples/client/petstore/dart/test/tests.html @@ -0,0 +1,14 @@ + + + + + + + Unit Test Results + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/dart/test/user_test.dart b/samples/client/petstore/dart/test/user_test.dart new file mode 100644 index 000000000000..886a6bc3c5d2 --- /dev/null +++ b/samples/client/petstore/dart/test/user_test.dart @@ -0,0 +1,63 @@ +part of tests; + +testUserApi() { + var userApi = new UserApi(); + + describe('User API ', () { + + it('creates a user', () async { + var id = 67567; + var username = 'Mally45'; + await userApi.createUser(new User()..id = id..username = username); + var user = await userApi.getUserByName(username); + expect(user.id).toEqual(id); + }); + + it('creates users with list input', () async { + var firstId = 46226; + var joe ='Joe'; + + var sally = 'Sally'; + var secondId = 95239; + + var users = [ new User()..id = firstId..username = joe, + new User()..id = secondId..username = sally]; + + await userApi.createUsersWithListInput(users); + var firstUser = await userApi.getUserByName(joe); + var secondUser = await userApi.getUserByName(sally); + expect(firstUser.id).toEqual(firstId); + expect(secondUser.id).toEqual(secondId); + }); + + it('updates a user', () async { + var username ='Arkjam89'; + var email = 'test@example.com'; + var user = new User()..id = 733356..username = username; + + await userApi.createUser(user); + user.email = email; + await userApi.updateUser(username,user); + var foundUser = await userApi.getUserByName(username); + expect(foundUser.email).toEqual(email); + }); + + it('deletes a user', () async { + var username ='Riddlem325'; + await userApi.createUser(new User()..id = 1231114..username = username); + await userApi.deleteUser(username); + expect(userApi.getUserByName(username)).toThrowWith(anInstanceOf: ApiException); + }); + + it('logs a user in', () async { + var username ='sgarad625'; + var password = 'lokimoki1'; + var user = new User()..id = 733356..username = username..password = password; + + await userApi.createUser(user); + var result = await userApi.loginUser(username, password); + expect(result).toContain('logged in user session:'); + }); + + }); +} \ No newline at end of file From 58c5ecf13ce93ea706ad0eb5349e0f7aeb08a20b Mon Sep 17 00:00:00 2001 From: Yissachar Radcliffe Date: Sun, 6 Sep 2015 19:58:28 -0400 Subject: [PATCH 059/219] Generate auth files to correct location --- .../codegen/languages/DartClientCodegen.java | 2 +- .../petstore/dart/auth/api_key_auth.dart | 28 ------------------- .../petstore/dart/auth/authentication.dart | 7 ----- .../petstore/dart/auth/http_basic_auth.dart | 14 ---------- samples/client/petstore/dart/auth/oauth.dart | 9 ------ .../dart/lib/auth/authentication.dart | 5 ++-- 6 files changed, 4 insertions(+), 61 deletions(-) delete mode 100644 samples/client/petstore/dart/auth/api_key_auth.dart delete mode 100644 samples/client/petstore/dart/auth/authentication.dart delete mode 100644 samples/client/petstore/dart/auth/http_basic_auth.dart delete mode 100644 samples/client/petstore/dart/auth/oauth.dart diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java index c22e7969e28c..ede4505d4ddc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/DartClientCodegen.java @@ -133,7 +133,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("apiException.mustache", libFolder, "api_exception.dart")); supportingFiles.add(new SupportingFile("apilib.mustache", libFolder, "api.dart")); - final String authFolder = sourceFolder + File.separator + "auth"; + final String authFolder = sourceFolder + File.separator + "lib" + File.separator + "auth"; supportingFiles.add(new SupportingFile("auth/authentication.mustache", authFolder, "authentication.dart")); supportingFiles.add(new SupportingFile("auth/http_basic_auth.mustache", authFolder, "http_basic_auth.dart")); supportingFiles.add(new SupportingFile("auth/api_key_auth.mustache", authFolder, "api_key_auth.dart")); diff --git a/samples/client/petstore/dart/auth/api_key_auth.dart b/samples/client/petstore/dart/auth/api_key_auth.dart deleted file mode 100644 index 6e728ae916ba..000000000000 --- a/samples/client/petstore/dart/auth/api_key_auth.dart +++ /dev/null @@ -1,28 +0,0 @@ -part of api; - -class ApiKeyAuth implements Authentication { - - final String location; - final String paramName; - String apiKey; - String apiKeyPrefix; - - ApiKeyAuth(this.location, this.paramName); - - @override - void applyToParams(Map queryParams, Map headerParams) { - String value; - if (apiKeyPrefix != null) { - value = '$apiKeyPrefix $apiKey'; - } else { - value = apiKey; - } - - if (location == 'query' && value != null) { - queryParams[paramName] = value; - } else if (location == 'header' && value != null) { - headerParams[paramName] = value; - } - } - -} \ No newline at end of file diff --git a/samples/client/petstore/dart/auth/authentication.dart b/samples/client/petstore/dart/auth/authentication.dart deleted file mode 100644 index 4833af90ec0d..000000000000 --- a/samples/client/petstore/dart/auth/authentication.dart +++ /dev/null @@ -1,7 +0,0 @@ -part of api; - -abstract class Authentication { - - /// Apply authentication settings to header and query params. - void applyToParams(Map queryParams, Map headerParams); -} \ No newline at end of file diff --git a/samples/client/petstore/dart/auth/http_basic_auth.dart b/samples/client/petstore/dart/auth/http_basic_auth.dart deleted file mode 100644 index e681c25653db..000000000000 --- a/samples/client/petstore/dart/auth/http_basic_auth.dart +++ /dev/null @@ -1,14 +0,0 @@ -part of api; - -class HttpBasicAuth implements Authentication { - - String username; - String password; - - @override - void applyToParams(Map queryParams, Map headerParams) { - String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); - headerParams["Authorization"] = "Basic " + CryptoUtils.bytesToBase64(UTF8.encode(str)); - } - -} \ No newline at end of file diff --git a/samples/client/petstore/dart/auth/oauth.dart b/samples/client/petstore/dart/auth/oauth.dart deleted file mode 100644 index 5e3e2c8b260d..000000000000 --- a/samples/client/petstore/dart/auth/oauth.dart +++ /dev/null @@ -1,9 +0,0 @@ -part of api; - -class OAuth implements Authentication { - - @override - void applyToParams(Map queryParams, Map headerParams) { - // TODO: support oauth - } -} \ No newline at end of file diff --git a/samples/client/petstore/dart/lib/auth/authentication.dart b/samples/client/petstore/dart/lib/auth/authentication.dart index b4aa90651f6b..4833af90ec0d 100644 --- a/samples/client/petstore/dart/lib/auth/authentication.dart +++ b/samples/client/petstore/dart/lib/auth/authentication.dart @@ -1,6 +1,7 @@ part of api; abstract class Authentication { - - void applyToParams(Map queryParams, Map headerParams); + + /// Apply authentication settings to header and query params. + void applyToParams(Map queryParams, Map headerParams); } \ No newline at end of file From 8b96cdb7d7a8599c28daeb42125a13d6a3be047b Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 7 Sep 2015 16:35:34 +0800 Subject: [PATCH 060/219] Set source/target compatibility in Android client --- .../Java/libraries/okhttp-gson/build.gradle.mustache | 4 ++-- .../src/main/resources/android-java/build.mustache | 6 +++++- samples/client/petstore/android-java/build.gradle | 4 ++++ samples/client/petstore/java/okhttp-gson/build.gradle | 4 ++-- 4 files changed, 13 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 73ea697ac139..02e1caa673af 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -1,8 +1,8 @@ apply plugin: 'java' apply plugin: 'maven' -sourceCompatibility = 1.7 -targetCompatibility = 1.7 +sourceCompatibility = JavaVersion.VERSION_1_7 +targetCompatibility = JavaVersion.VERSION_1_7 repositories { mavenCentral() diff --git a/modules/swagger-codegen/src/main/resources/android-java/build.mustache b/modules/swagger-codegen/src/main/resources/android-java/build.mustache index 367890f3298c..dff18970462b 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -34,6 +34,10 @@ android { minSdkVersion 14 targetSdkVersion 22 } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } // Rename the aar correctly libraryVariants.all { variant -> @@ -90,4 +94,4 @@ task sourcesJar(type: Jar) { artifacts { archives sourcesJar } -{{/useAndroidMavenGradlePlugin}} \ No newline at end of file +{{/useAndroidMavenGradlePlugin}} diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index 028b56beae61..417503cb51ea 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -30,6 +30,10 @@ android { minSdkVersion 14 targetSdkVersion 22 } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } // Rename the aar correctly libraryVariants.all { variant -> diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 53e92e5fe169..ada6a992573a 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -1,8 +1,8 @@ apply plugin: 'java' apply plugin: 'maven' -sourceCompatibility = 1.7 -targetCompatibility = 1.7 +sourceCompatibility = JavaVersion.VERSION_1_7 +targetCompatibility = JavaVersion.VERSION_1_7 repositories { mavenCentral() From e215a1c87f795295175777864398e8cd9e241367 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 8 Sep 2015 11:38:01 +0800 Subject: [PATCH 061/219] update dart permission --- .gitignore | 2 ++ bin/dart-petstore.sh | 0 2 files changed, 2 insertions(+) mode change 100644 => 100755 bin/dart-petstore.sh diff --git a/.gitignore b/.gitignore index cd7e1d286fa0..c904ba4a5fe5 100644 --- a/.gitignore +++ b/.gitignore @@ -53,3 +53,5 @@ samples/client/petstore/silex/SwaggerServer/venodr/ samples/client/petstore/python/.projectile samples/client/petstore/python/.venv/ + +*/.settings diff --git a/bin/dart-petstore.sh b/bin/dart-petstore.sh old mode 100644 new mode 100755 From 3514bf14b3ff53ec6801620e7c828de0c76f46a8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Tue, 8 Sep 2015 10:00:17 +0200 Subject: [PATCH 062/219] Fix HEAD path item is missing. Fixes #1156. --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 80a25350d8bf..b464c706d31e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -413,6 +413,7 @@ public Map> processPaths(Map paths) for (String resourcePath : paths.keySet()) { Path path = paths.get(resourcePath); processOperation(resourcePath, "get", path.getGet(), ops, path); + processOperation(resourcePath, "head", path.getHead(), ops, path); processOperation(resourcePath, "put", path.getPut(), ops, path); processOperation(resourcePath, "post", path.getPost(), ops, path); processOperation(resourcePath, "delete", path.getDelete(), ops, path); From d37cf6595abe706bb8243a5c0b5bc9ddb5843d9b Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 9 Sep 2015 16:20:17 +0800 Subject: [PATCH 063/219] update pom.xml to get rid of the warning --- modules/swagger-codegen/pom.xml | 5 +++++ pom.xml | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index b1318a343e23..c62bf655b578 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -312,6 +312,11 @@ slf4j-api ${slf4j-version} + + org.slf4j + slf4j-simple + ${slf4j-version} + commons-lang commons-lang diff --git a/pom.xml b/pom.xml index ada6e427badc..883d22257c8b 100644 --- a/pom.xml +++ b/pom.xml @@ -525,7 +525,7 @@ 4.8.1 1.0.0 2.4 - 1.6.3 + 1.7.12 3.2.1 1.9 6.9.6 From 71a3218bb3b3fbaf93065c15d6ee344df6d55034 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 9 Sep 2015 20:27:59 +0800 Subject: [PATCH 064/219] fix sinatra type (tag) --- .../java/io/swagger/codegen/languages/SinatraServerCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index 5bc402fe0c47..c9d8e550b5dd 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -76,7 +76,7 @@ public void processOpts() { } public CodegenType getTag() { - return CodegenType.CLIENT; + return CodegenType.SERVER; } public String getName() { From 0edbfeff157ea80420d31e8a95e199406e8af26a Mon Sep 17 00:00:00 2001 From: Robin Eggenkamp Date: Thu, 10 Sep 2015 14:24:55 +0200 Subject: [PATCH 065/219] Bump Alamofire version to final 2.0.0 --- .../swagger-codegen/src/main/resources/swift/Cartfile.mustache | 2 +- .../swagger-codegen/src/main/resources/swift/Podspec.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache index f870554a505c..e36e0eedabdc 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Cartfile.mustache @@ -1,2 +1,2 @@ -github "Alamofire/Alamofire" >= 1.3{{#usePromiseKit}} +github "Alamofire/Alamofire" >= 2.0.0{{#usePromiseKit}} github "mxcl/PromiseKit" >=1.5.3{{/usePromiseKit}} diff --git a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache index 51858c0f220c..e359edaff671 100644 --- a/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/swift/Podspec.mustache @@ -16,5 +16,5 @@ Pod::Spec.new do |s| s.documentation_url = '{{podDocumentationURL}}'{{/podDocumentationURL}} s.source_files = '{{projectName}}/Classes/Swaggers/**/*.swift'{{#usePromiseKit}} s.dependency 'PromiseKit', '~> 2.1'{{/usePromiseKit}} - s.dependency 'Alamofire', '~> 2.0.0-beta.3' + s.dependency 'Alamofire', '~> 2.0.0' end From 3c3762fd92a7cb7036c2bcfa178c9c7fa0d6fd1d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Thu, 10 Sep 2015 14:55:49 +0200 Subject: [PATCH 066/219] Add HEAD and OPTIONS support in PHP client. The generated PHP client didn't support the HEAD and OPTIONS methods. Followup on #1156 and #1201. --- .../src/main/resources/php/ApiClient.mustache | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 3c6819ab73be..8927cbbecb38 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -48,6 +48,8 @@ class ApiClient public static $PATCH = "PATCH"; public static $POST = "POST"; public static $GET = "GET"; + public static $HEAD = "HEAD"; + public static $OPTIONS = "OPTIONS"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; @@ -170,6 +172,11 @@ class ApiClient if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$HEAD) { + curl_setopt($curl, CURLOPT_NOBODY, true); + } else if ($method == self::$OPTIONS) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method == self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); From 43d71ed10c07a34c407e17ce7b2880653bb181b0 Mon Sep 17 00:00:00 2001 From: Leo Date: Thu, 10 Sep 2015 12:17:23 -0500 Subject: [PATCH 067/219] Remove the parameter in the BasePath getter The parameter in the BasePath getter is not needed. --- modules/swagger-codegen/src/main/resources/csharp/api.mustache | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 24c65f85ba8d..8b958fd0c889 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -68,9 +68,8 @@ namespace {{packageName}}.Api /// /// Gets the base path of the API client. /// - /// The base path /// The base path - public String GetBasePath(String basePath) + public String GetBasePath() { return this.ApiClient.BasePath; } From dbdcf340440922cb8b0e294b02a73563143cc32d Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Thu, 10 Sep 2015 15:14:53 -0700 Subject: [PATCH 068/219] [Obj-C] Fixed an issue with incorrect references in the ApiClient when using a custom prefix. --- .../src/main/resources/objc/ApiClient-body.mustache | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 5b2a290ab852..04c628ee5a32 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -528,7 +528,7 @@ static void (^reachabilityChangeBlock)(int); NSMutableString *resourcePath = [NSMutableString stringWithString:path]; [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] - withString:[SWGApiClient escape:obj]]; + withString:[{{classPrefix}}ApiClient escape:obj]]; }]; NSMutableURLRequest * request = nil; @@ -705,7 +705,7 @@ static void (^reachabilityChangeBlock)(int); if (object == nil) { return nil; } - else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[{{classPrefix}}QueryParamCollection class]]) { return object; } else if ([object isKindOfClass:[NSDate class]]) { @@ -729,7 +729,7 @@ static void (^reachabilityChangeBlock)(int); }]; return sanitizedObjs; } - else if ([object isKindOfClass:[SWGObject class]]) { + else if ([object isKindOfClass:[{{classPrefix}}Object class]]) { return [object toDictionary]; } else { From 60e5a3453442795e371f6b64ee4411759efb39c2 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 11 Sep 2015 10:46:56 +0800 Subject: [PATCH 069/219] Update Java-jersey2 client to skip binary support Binary parameter/response support was added to the default Java client codegen which changed the signature of the `invokeAPI` method in "api.mustache", causing the "jersey2" client fail to compile. Here an separate version of `api.mustache` is added for "jersey2" client which does not handle binary support (for now). --- .../Java/libraries/jersey2/api.mustache | 98 +++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache new file mode 100644 index 000000000000..d525db8a28d0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -0,0 +1,98 @@ +package {{package}}; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.TypeRef; + +import {{modelPackage}}.*; + +import java.util.*; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.io.File; +import java.util.Map; +import java.util.HashMap; + +{{>generatedAnnotation}} +{{#operations}} +public class {{classname}} { + private ApiClient {{localVariablePrefix}}apiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + public ApiClient getApiClient() { + return {{localVariablePrefix}}apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.{{localVariablePrefix}}apiClient = apiClient; + } + + {{#operation}} + /** + * {{summary}} + * {{notes}} +{{#allParams}} * @param {{paramName}} {{description}} +{{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + */ + public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) throws ApiException { + Object {{localVariablePrefix}}postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException(400, "Missing the required parameter '{{paramName}}' when calling {{nickname}}"); + } + {{/required}}{{/allParams}} + // create path and map variables + String {{localVariablePrefix}}path = "{{{path}}}".replaceAll("\\{format\\}","json"){{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; + + // query params + List {{localVariablePrefix}}queryParams = new ArrayList(); + Map {{localVariablePrefix}}headerParams = new HashMap(); + Map {{localVariablePrefix}}formParams = new HashMap(); + + {{#queryParams}} + {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/queryParams}} + + {{#headerParams}}if ({{paramName}} != null) + {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}})); + {{/headerParams}} + + {{#formParams}}if ({{paramName}} != null) + {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}}); + {{/formParams}} + + final String[] {{localVariablePrefix}}accepts = { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + final String {{localVariablePrefix}}accept = {{localVariablePrefix}}apiClient.selectHeaderAccept({{localVariablePrefix}}accepts); + + final String[] {{localVariablePrefix}}contentTypes = { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + final String {{localVariablePrefix}}contentType = {{localVariablePrefix}}apiClient.selectHeaderContentType({{localVariablePrefix}}contentTypes); + + String[] {{localVariablePrefix}}authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + + {{#returnType}} + TypeRef {{localVariablePrefix}}returnType = new TypeRef<{{{returnType}}}>() {}; + return {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, {{localVariablePrefix}}returnType); + {{/returnType}}{{^returnType}} + {{localVariablePrefix}}apiClient.invokeAPI({{localVariablePrefix}}path, "{{httpMethod}}", {{localVariablePrefix}}queryParams, {{localVariablePrefix}}postBody, {{localVariablePrefix}}headerParams, {{localVariablePrefix}}formParams, {{localVariablePrefix}}accept, {{localVariablePrefix}}contentType, {{localVariablePrefix}}authNames, null); + {{/returnType}} + } + {{/operation}} +} +{{/operations}} From def3f5b3fb651affa80da4b6592701335ee12cba Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 11 Sep 2015 11:48:09 +0800 Subject: [PATCH 070/219] Java-jersey2: record status code and response headers of last request --- .../Java/libraries/jersey2/ApiClient.mustache | 44 ++++++++++++++----- 1 file changed, 34 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index fb5f6b0d1075..5033c1986f83 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -53,6 +53,9 @@ public class ApiClient { private Map authentications; + private int statusCode; + private Map> responseHeaders; + private DateFormat dateFormat; public ApiClient() { @@ -84,6 +87,20 @@ public class ApiClient { return this; } + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + /** * Get authentications (key: authentication name, value: authentication). */ @@ -484,6 +501,9 @@ public class ApiClient { throw new ApiException(500, "unknown method type " + method); } + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { return null; } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { @@ -502,23 +522,27 @@ public class ApiClient { // e.printStackTrace(); } } - Map> responseHeaders = new HashMap>(); - for (String key: response.getHeaders().keySet()) { - List values = response.getHeaders().get(key); - List headers = new ArrayList(); - for (Object o : values) { - headers.add(String.valueOf(o)); - } - responseHeaders.put(key, headers); - } throw new ApiException( response.getStatus(), message, - responseHeaders, + buildResponseHeaders(response), respBody); } } + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + /** * Update query and header parameters based on authentication settings. * From 34f196a144a3cb705ead9d5474320c0ee5b32fdd Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 11 Sep 2015 13:15:55 +0800 Subject: [PATCH 071/219] Java-okhttp-gson: allow access to status code and response headers of last (async) request --- .../okhttp-gson/ApiCallback.mustache | 13 +++++++-- .../libraries/okhttp-gson/ApiClient.mustache | 29 +++++++++++++++++-- 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache index 4af16c9faa90..6eee875bdcc2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiCallback.mustache @@ -2,6 +2,9 @@ package {{invokerPackage}}; import java.io.IOException; +import java.util.Map; +import java.util.List; + /** * Callback for asynchronous API call. * @@ -10,13 +13,19 @@ import java.io.IOException; public interface ApiCallback { /** * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null */ - void onFailure(ApiException e); + void onFailure(ApiException e, int statusCode, Map> responseHeaders); /** * This is called when the API call succeeded. * * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response */ - void onSuccess(T result); + void onSuccess(T result, int statusCode, Map> responseHeaders); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 069aa273b142..f8d7fad38490 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -48,6 +48,9 @@ public class ApiClient { private Map authentications; + private int statusCode; + private Map> responseHeaders; + private String dateFormat; private DateFormat dateFormatter; private int dateLength; @@ -107,6 +110,24 @@ public class ApiClient { return this; } + /** + * Gets the status code of the previous request. + * NOTE: Status code of last async response is not recorded here, it is + * passed to the callback methods instead. + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request. + * NOTE: Headers of last async response is not recorded here, it is passed + * to callback methods instead. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + public String getDateFormat() { return dateFormat; } @@ -534,6 +555,8 @@ public class ApiClient { public T execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); + this.statusCode = response.code(); + this.responseHeaders = response.headers().toMultimap(); return handleResponse(response, returnType); } catch (IOException e) { throw new ApiException(e); @@ -557,7 +580,7 @@ public class ApiClient { call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e)); + callback.onFailure(new ApiException(e), 0, null); } @Override @@ -566,10 +589,10 @@ public class ApiClient { try { result = (T) handleResponse(response, returnType); } catch (ApiException e) { - callback.onFailure(e); + callback.onFailure(e, response.code(), response.headers().toMultimap()); return; } - callback.onSuccess(result); + callback.onSuccess(result, response.code(), response.headers().toMultimap()); } }); } From 2e402bba977a664efcb5a725567e0c25b02be5c3 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 11 Sep 2015 13:19:23 +0800 Subject: [PATCH 072/219] Rebuild Java clients for the petstore sample --- .../java/io/swagger/client/ApiClient.java | 135 +++++++++++++++--- .../java/io/swagger/client/ApiException.java | 39 +++-- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 11 +- .../main/java/io/swagger/client/TypeRef.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 132 ++++++++++++----- .../java/io/swagger/client/api/StoreApi.java | 66 ++++++--- .../java/io/swagger/client/api/UserApi.java | 122 +++++++++++----- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/model/Category.java | 9 +- .../java/io/swagger/client/model/Order.java | 17 +-- .../java/io/swagger/client/model/Pet.java | 17 +-- .../java/io/swagger/client/model/Tag.java | 9 +- .../java/io/swagger/client/model/User.java | 21 +-- .../client/petstore/java/jersey2/hello.txt | 1 + .../java/io/swagger/client/ApiClient.java | 46 ++++-- .../java/io/swagger/client/ApiException.java | 39 +++-- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 11 +- .../main/java/io/swagger/client/TypeRef.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 26 ++-- .../java/io/swagger/client/api/StoreApi.java | 14 +- .../java/io/swagger/client/api/UserApi.java | 26 ++-- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/model/Category.java | 13 +- .../java/io/swagger/client/model/Order.java | 17 +-- .../java/io/swagger/client/model/Pet.java | 17 +-- .../java/io/swagger/client/model/Tag.java | 13 +- .../java/io/swagger/client/model/User.java | 25 ++-- .../java/io/swagger/client/ApiCallback.java | 13 +- .../java/io/swagger/client/ApiClient.java | 29 +++- .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 4 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/petstore/test/PetApiTest.java | 78 ++++++++++ 50 files changed, 720 insertions(+), 276 deletions(-) create mode 100644 samples/client/petstore/java/jersey2/hello.txt diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index bc2dab2e8a8d..0d531986afa3 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -28,6 +28,7 @@ import java.io.IOException; import java.io.File; import java.io.UnsupportedEncodingException; +import java.io.DataInputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; @@ -38,7 +39,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -48,6 +49,9 @@ public class ApiClient { private Map authentications; + private int statusCode; + private Map> responseHeaders; + private DateFormat dateFormat; public ApiClient() { @@ -78,6 +82,20 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + /** * Get authentications (key: authentication name, value: authentication). */ @@ -371,22 +389,12 @@ public T deserialize(ClientResponse response, TypeRef returnType) throws Api } } - /** - * Invoke API by sending HTTP request with the given options. - * - * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" - * @param queryParams The query parameters - * @param body The request body object - * @param headerParams The header parameters - * @param formParams The form parameters - * @param accept The request's Accept header - * @param contentType The request's Content-Type header - * @param authNames The authentications to apply - * @param returnType The return type into which to deserialize the response - * @return The response body in type of string - */ - public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + private ClientResponse getAPIResponse(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames) throws ApiException { + + if (body != null && binaryBody != null){ + throw new ApiException(500, "either body or binaryBody must be null"); + } + updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(); @@ -446,7 +454,10 @@ public T invokeAPI(String path, String method, List queryParams, Objec if (encodedFormParams != null) { response = builder.type(contentType).post(ClientResponse.class, encodedFormParams); } else if (body == null) { - response = builder.post(ClientResponse.class, null); + if(binaryBody == null) + response = builder.post(ClientResponse.class, null); + else + response = builder.type(contentType).post(ClientResponse.class, binaryBody); } else if (body instanceof FormDataMultiPart) { response = builder.type(contentType).post(ClientResponse.class, body); } else { @@ -456,7 +467,10 @@ public T invokeAPI(String path, String method, List queryParams, Objec if (encodedFormParams != null) { response = builder.type(contentType).put(ClientResponse.class, encodedFormParams); } else if(body == null) { - response = builder.put(ClientResponse.class, serialize(body, contentType)); + if(binaryBody == null) + response = builder.put(ClientResponse.class, null); + else + response = builder.type(contentType).put(ClientResponse.class, binaryBody); } else { response = builder.type(contentType).put(ClientResponse.class, serialize(body, contentType)); } @@ -464,15 +478,42 @@ public T invokeAPI(String path, String method, List queryParams, Objec if (encodedFormParams != null) { response = builder.type(contentType).delete(ClientResponse.class, encodedFormParams); } else if(body == null) { - response = builder.delete(ClientResponse.class); + if(binaryBody == null) + response = builder.delete(ClientResponse.class); + else + response = builder.type(contentType).delete(ClientResponse.class, binaryBody); } else { response = builder.type(contentType).delete(ClientResponse.class, serialize(body, contentType)); } } else { throw new ApiException(500, "unknown method type " + method); } + return response; + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object - if it is not binary, otherwise null + * @param binaryBody The request body object - if it is binary, otherwise null + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @return The response body in type of string + */ + public T invokeAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, TypeRef returnType) throws ApiException { + + ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); - if (response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = response.getHeaders(); + + if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { return null; } else if (response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { if (returnType == null) @@ -497,6 +538,58 @@ public T invokeAPI(String path, String method, List queryParams, Objec respBody); } } + /** + * Invoke API by sending HTTP request with the given options - return binary result + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", and "DELETE" + * @param queryParams The query parameters + * @param body The request body object - if it is not binary, otherwise null + * @param binaryBody The request body object - if it is binary, otherwise null + * @param headerParams The header parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @return The response body in type of string + */ + public byte[] invokeBinaryAPI(String path, String method, List queryParams, Object body, byte[] binaryBody, Map headerParams, Map formParams, String accept, String contentType, String[]authNames) throws ApiException { + + ClientResponse response = getAPIResponse(path, method, queryParams, body, binaryBody, headerParams, formParams, accept, contentType, authNames); + + if(response.getStatusInfo() == ClientResponse.Status.NO_CONTENT) { + return null; + } + else if(response.getStatusInfo().getFamily() == Family.SUCCESSFUL) { + if(response.hasEntity()) { + DataInputStream stream = new DataInputStream(response.getEntityInputStream()); + byte[] data = new byte[response.getLength()]; + try { + stream.readFully(data); + } catch (IOException ex) { + throw new ApiException(500, "Error obtaining binary response data"); + } + return data; + } + else { + return new byte[0]; + } + } + else { + String message = "error"; + if(response.hasEntity()) { + try{ + message = String.valueOf(response.getEntity(String.class)); + } + catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatusInfo().getStatusCode(), + message); + } + } /** * Update query and header parameters based on authentication settings. diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index 679786deb107..88761f16e9cb 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,23 +3,48 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class ApiException extends Exception { private int code = 0; - private String message = null; private Map> responseHeaders = null; private String responseBody = null; public ApiException() {} + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + public ApiException(int code, String message) { + super(message); this.code = code; - this.message = message; } public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this.code = code; - this.message = message; + this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } @@ -28,10 +53,6 @@ public int getCode() { return code; } - public String getMessage() { - return message; - } - /** * Get the HTTP response headers. */ diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 0a674b8d52ae..47acca1b8ea0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java index 5523b921e45c..dd716e6fd90a 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java @@ -6,7 +6,7 @@ import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T18:19:30.060+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class JSON { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 9f9e2c96b4cc..0bff951077c6 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index de5e940ba55d..df5670a8b0d3 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). @@ -39,4 +39,13 @@ public static String join(String[] array, String separator) { } return out.toString(); } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java index cd69bd71e7c6..12a842d84048 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 75dfc35beb1c..3a14b07dc259 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class PetApi { private ApiClient apiClient; @@ -46,8 +46,8 @@ public void setApiClient(ApiClient apiClient) { */ public void updatePet (Pet body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -73,9 +73,16 @@ public void updatePet (Pet body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + + - apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -86,8 +93,8 @@ public void updatePet (Pet body) throws ApiException { */ public void addPet (Pet body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -113,9 +120,16 @@ public void addPet (Pet body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + + - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -126,8 +140,8 @@ public void addPet (Pet body) throws ApiException { */ public List findPetsByStatus (List status) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); @@ -155,10 +169,17 @@ public List findPetsByStatus (List status) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + + TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -169,8 +190,8 @@ public List findPetsByStatus (List status) throws ApiException { */ public List findPetsByTags (List tags) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); @@ -198,10 +219,17 @@ public List findPetsByTags (List tags) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + + TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -212,13 +240,13 @@ public List findPetsByTags (List tags) throws ApiException { */ public Pet getPetById (Long petId) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); - } - - + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + } + // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -244,11 +272,18 @@ public Pet getPetById (Long petId) throws ApiException { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - String[] authNames = new String[] { "api_key", "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth", "api_key" }; + + + + TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -261,13 +296,13 @@ public Pet getPetById (Long petId) throws ApiException { */ public void updatePetWithForm (String petId, String name, String status) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); - } - - + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + } + // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -298,9 +333,16 @@ public void updatePetWithForm (String petId, String name, String status) throws final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + + - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -312,13 +354,13 @@ public void updatePetWithForm (String petId, String name, String status) throws */ public void deletePet (Long petId, String apiKey) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); - } - - + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + } + // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -347,9 +389,16 @@ public void deletePet (Long petId, String apiKey) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + + - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -362,13 +411,13 @@ public void deletePet (Long petId, String apiKey) throws ApiException { */ public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'petId' is set - if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); - } - - + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + } + // create path and map variables String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -399,9 +448,16 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + + + - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index a488fb374450..a7c73b93fa7b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class StoreApi { private ApiClient apiClient; @@ -45,8 +45,8 @@ public void setApiClient(ApiClient apiClient) { */ public Map getInventory () throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); @@ -72,10 +72,17 @@ public Map getInventory () throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; + + + + TypeRef returnType = new TypeRef>() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -86,8 +93,8 @@ public Map getInventory () throws ApiException { */ public Order placeOrder (Order body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -113,10 +120,17 @@ public Order placeOrder (Order body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -127,13 +141,13 @@ public Order placeOrder (Order body) throws ApiException { */ public Order getOrderById (String orderId) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); - } - - + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + } + // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); @@ -160,10 +174,17 @@ public Order getOrderById (String orderId) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -174,13 +195,13 @@ public Order getOrderById (String orderId) throws ApiException { */ public void deleteOrder (String orderId) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'orderId' is set - if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); - } - - + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + } + // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); @@ -207,9 +228,16 @@ public void deleteOrder (String orderId) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index 3dee565a271b..dd798e3e7974 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class UserApi { private ApiClient apiClient; @@ -46,8 +46,8 @@ public void setApiClient(ApiClient apiClient) { */ public void createUser (User body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); @@ -73,9 +73,16 @@ public void createUser (User body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -86,8 +93,8 @@ public void createUser (User body) throws ApiException { */ public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); @@ -113,9 +120,16 @@ public void createUsersWithArrayInput (List body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -126,8 +140,8 @@ public void createUsersWithArrayInput (List body) throws ApiException { */ public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); @@ -153,9 +167,16 @@ public void createUsersWithListInput (List body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + + + apiClient.invokeAPI(path, "POST", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); - apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + } /** @@ -167,8 +188,8 @@ public void createUsersWithListInput (List body) throws ApiException { */ public String loginUser (String username, String password) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); @@ -198,10 +219,17 @@ public String loginUser (String username, String password) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -211,8 +239,8 @@ public String loginUser (String username, String password) throws ApiException { */ public void logoutUser () throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // create path and map variables String path = "/user/logout".replaceAll("\\{format\\}","json"); @@ -238,26 +266,33 @@ public void logoutUser () throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + - apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + + + + apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ public User getUserByName (String username) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); - } - - + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -284,10 +319,17 @@ public User getUserByName (String username) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + TypeRef returnType = new TypeRef() {}; - return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); + return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); + + + } /** @@ -299,13 +341,13 @@ public User getUserByName (String username) throws ApiException { */ public void updateUser (String username, User body) throws ApiException { Object postBody = body; + byte[] postBinaryBody = null; - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); - } - - + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -332,9 +374,16 @@ public void updateUser (String username, User body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + + - apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "PUT", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + } /** @@ -345,13 +394,13 @@ public void updateUser (String username, User body) throws ApiException { */ public void deleteUser (String username) throws ApiException { Object postBody = null; + byte[] postBinaryBody = null; - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); - } - - + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -378,9 +427,16 @@ public void deleteUser (String username) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + + + - apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, null); + + + + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index dccddad00886..84461023650e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 7efcc795425a..efb1fc172ea8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 41d7988af0d6..1c3b905baeda 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index 20520b968133..a5d6fa740404 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java index b7ccc46204c0..f3ba53b985dc 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; @@ -8,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class Category { private Long id = null; @@ -45,9 +46,9 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index e89c1f3fb408..16855721cd0d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; import java.util.Date; @@ -9,7 +10,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T18:19:30.060+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class Order { private Long id = null; @@ -115,13 +116,13 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" petId: ").append(petId).append("\n"); - sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" shipDate: ").append(shipDate).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append(" complete: ").append(complete).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index b3b0e1b5347f..9f06fc171aad 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; import io.swagger.client.model.Category; import java.util.*; import io.swagger.client.model.Tag; @@ -11,7 +12,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T18:19:30.060+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class Pet { private Long id = null; @@ -117,13 +118,13 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" category: ").append(category).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append(" photoUrls: ").append(photoUrls).append("\n"); - sb.append(" tags: ").append(tags).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java index 2550d7c76364..4fd62f39a6be 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; @@ -8,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class Tag { private Long id = null; @@ -45,9 +46,9 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java index d27f1c2658d8..df035a093e14 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; @@ -8,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T11:46:58.447+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") public class User { private Long id = null; @@ -124,15 +125,15 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" username: ").append(username).append("\n"); - sb.append(" firstName: ").append(firstName).append("\n"); - sb.append(" lastName: ").append(lastName).append("\n"); - sb.append(" email: ").append(email).append("\n"); - sb.append(" password: ").append(password).append("\n"); - sb.append(" phone: ").append(phone).append("\n"); - sb.append(" userStatus: ").append(userStatus).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/jersey2/hello.txt b/samples/client/petstore/java/jersey2/hello.txt new file mode 100644 index 000000000000..6769dd60bdf5 --- /dev/null +++ b/samples/client/petstore/java/jersey2/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 3ddf4621ae83..56d7a5453ede 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -43,7 +43,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -53,6 +53,9 @@ public class ApiClient { private Map authentications; + private int statusCode; + private Map> responseHeaders; + private DateFormat dateFormat; public ApiClient() { @@ -83,6 +86,20 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Gets the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + /** * Get authentications (key: authentication name, value: authentication). */ @@ -483,6 +500,9 @@ public T invokeAPI(String path, String method, List queryParams, Objec throw new ApiException(500, "unknown method type " + method); } + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { return null; } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { @@ -501,23 +521,27 @@ public T invokeAPI(String path, String method, List queryParams, Objec // e.printStackTrace(); } } - Map> responseHeaders = new HashMap>(); - for (String key: response.getHeaders().keySet()) { - List values = response.getHeaders().get(key); - List headers = new ArrayList(); - for (Object o : values) { - headers.add(String.valueOf(o)); - } - responseHeaders.put(key, headers); - } throw new ApiException( response.getStatus(), message, - responseHeaders, + buildResponseHeaders(response), respBody); } } + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + /** * Update query and header parameters based on authentication settings. * diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java index 48b196e2af7e..aec34b70511a 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiException.java @@ -3,23 +3,48 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class ApiException extends Exception { private int code = 0; - private String message = null; private Map> responseHeaders = null; private String responseBody = null; public ApiException() {} + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + public ApiException(int code, String message) { + super(message); this.code = code; - this.message = message; } public ApiException(int code, String message, Map> responseHeaders, String responseBody) { - this.code = code; - this.message = message; + this(code, message); this.responseHeaders = responseHeaders; this.responseBody = responseBody; } @@ -28,10 +53,6 @@ public int getCode() { return code; } - public String getMessage() { - return message; - } - /** * Get the HTTP response headers. */ diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java index e94cd5c0aa36..778c303e0ecb 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java index 3095c7bacead..4b14a48b8584 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/JSON.java @@ -6,7 +6,7 @@ import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T16:42:49.539+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class JSON { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java index cb0e034bd638..1695577aff01 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java index 50e37eb367a5..f706fb4f9fa2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). @@ -39,4 +39,13 @@ public static String join(String[] array, String separator) { } return out.toString(); } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java index 1444bca5a064..cbff07c94700 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index ca72d88b1304..26e0f275c8e2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class PetApi { private ApiClient apiClient; @@ -47,7 +47,6 @@ public void setApiClient(ApiClient apiClient) { public void updatePet (Pet body) throws ApiException { Object postBody = body; - // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -73,6 +72,7 @@ public void updatePet (Pet body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -87,7 +87,6 @@ public void updatePet (Pet body) throws ApiException { public void addPet (Pet body) throws ApiException { Object postBody = body; - // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -113,6 +112,7 @@ public void addPet (Pet body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -127,7 +127,6 @@ public void addPet (Pet body) throws ApiException { public List findPetsByStatus (List status) throws ApiException { Object postBody = null; - // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); @@ -155,6 +154,7 @@ public List findPetsByStatus (List status) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -170,7 +170,6 @@ public List findPetsByStatus (List status) throws ApiException { public List findPetsByTags (List tags) throws ApiException { Object postBody = null; - // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); @@ -198,6 +197,7 @@ public List findPetsByTags (List tags) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -215,10 +215,9 @@ public Pet getPetById (Long petId) throws ApiException { // verify the required parameter 'petId' is set if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); + throw new ApiException(400, "Missing the required parameter 'petId' when calling getPetById"); } - // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -245,6 +244,7 @@ public Pet getPetById (Long petId) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth", "api_key" }; + TypeRef returnType = new TypeRef() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -264,10 +264,9 @@ public void updatePetWithForm (String petId, String name, String status) throws // verify the required parameter 'petId' is set if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); + throw new ApiException(400, "Missing the required parameter 'petId' when calling updatePetWithForm"); } - // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -298,6 +297,7 @@ public void updatePetWithForm (String petId, String name, String status) throws final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -315,10 +315,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { // verify the required parameter 'petId' is set if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); + throw new ApiException(400, "Missing the required parameter 'petId' when calling deletePet"); } - // create path and map variables String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -347,6 +346,7 @@ public void deletePet (Long petId, String apiKey) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -365,10 +365,9 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws // verify the required parameter 'petId' is set if (petId == null) { - throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); + throw new ApiException(400, "Missing the required parameter 'petId' when calling uploadFile"); } - // create path and map variables String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); @@ -399,6 +398,7 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "petstore_auth" }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index 2abbae3f714d..c95256c69aae 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class StoreApi { private ApiClient apiClient; @@ -46,7 +46,6 @@ public void setApiClient(ApiClient apiClient) { public Map getInventory () throws ApiException { Object postBody = null; - // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); @@ -72,6 +71,7 @@ public Map getInventory () throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { "api_key" }; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -87,7 +87,6 @@ public Map getInventory () throws ApiException { public Order placeOrder (Order body) throws ApiException { Object postBody = body; - // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -113,6 +112,7 @@ public Order placeOrder (Order body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + TypeRef returnType = new TypeRef() {}; return apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -130,10 +130,9 @@ public Order getOrderById (String orderId) throws ApiException { // verify the required parameter 'orderId' is set if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); + throw new ApiException(400, "Missing the required parameter 'orderId' when calling getOrderById"); } - // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); @@ -160,6 +159,7 @@ public Order getOrderById (String orderId) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + TypeRef returnType = new TypeRef() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -177,10 +177,9 @@ public void deleteOrder (String orderId) throws ApiException { // verify the required parameter 'orderId' is set if (orderId == null) { - throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); + throw new ApiException(400, "Missing the required parameter 'orderId' when calling deleteOrder"); } - // create path and map variables String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); @@ -207,6 +206,7 @@ public void deleteOrder (String orderId) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 7959290acd67..26c8d4b035f6 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class UserApi { private ApiClient apiClient; @@ -47,7 +47,6 @@ public void setApiClient(ApiClient apiClient) { public void createUser (User body) throws ApiException { Object postBody = body; - // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); @@ -73,6 +72,7 @@ public void createUser (User body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -87,7 +87,6 @@ public void createUser (User body) throws ApiException { public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; - // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); @@ -113,6 +112,7 @@ public void createUsersWithArrayInput (List body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -127,7 +127,6 @@ public void createUsersWithArrayInput (List body) throws ApiException { public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; - // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); @@ -153,6 +152,7 @@ public void createUsersWithListInput (List body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "POST", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -168,7 +168,6 @@ public void createUsersWithListInput (List body) throws ApiException { public String loginUser (String username, String password) throws ApiException { Object postBody = null; - // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); @@ -198,6 +197,7 @@ public String loginUser (String username, String password) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + TypeRef returnType = new TypeRef() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -212,7 +212,6 @@ public String loginUser (String username, String password) throws ApiException { public void logoutUser () throws ApiException { Object postBody = null; - // create path and map variables String path = "/user/logout".replaceAll("\\{format\\}","json"); @@ -238,6 +237,7 @@ public void logoutUser () throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -246,7 +246,7 @@ public void logoutUser () throws ApiException { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ public User getUserByName (String username) throws ApiException { @@ -254,10 +254,9 @@ public User getUserByName (String username) throws ApiException { // verify the required parameter 'username' is set if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); + throw new ApiException(400, "Missing the required parameter 'username' when calling getUserByName"); } - // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -284,6 +283,7 @@ public User getUserByName (String username) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + TypeRef returnType = new TypeRef() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -302,10 +302,9 @@ public void updateUser (String username, User body) throws ApiException { // verify the required parameter 'username' is set if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); + throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); } - // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -332,6 +331,7 @@ public void updateUser (String username, User body) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "PUT", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); @@ -348,10 +348,9 @@ public void deleteUser (String username) throws ApiException { // verify the required parameter 'username' is set if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); + throw new ApiException(400, "Missing the required parameter 'username' when calling deleteUser"); } - // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); @@ -378,6 +377,7 @@ public void deleteUser (String username) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); String[] authNames = new String[] { }; + apiClient.invokeAPI(path, "DELETE", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, null); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 87a4a90a49cd..6082e3a6e4ca 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java index b35133a0c94f..6555e457ee56 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 7d224efefbb4..909043e180e7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java index 06debad62e47..d4f548b14125 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java index f0dab47c7f7e..f09bf60128a7 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Category.java @@ -1,13 +1,16 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; + + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") -public class Category { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +public class Category { private Long id = null; private String name = null; @@ -43,9 +46,9 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Category {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 2477288848da..868c59a783d8 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; import java.util.Date; @@ -9,7 +10,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T16:42:49.539+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class Order { private Long id = null; @@ -115,13 +116,13 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Order {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" petId: ").append(petId).append("\n"); - sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" shipDate: ").append(shipDate).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append(" complete: ").append(complete).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index 1ed729475562..2a4a0b6c93d9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -1,5 +1,6 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; import io.swagger.client.model.Category; import java.util.*; import io.swagger.client.model.Tag; @@ -11,7 +12,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-24T16:42:49.539+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") public class Pet { private Long id = null; @@ -117,13 +118,13 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Pet {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" category: ").append(category).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append(" photoUrls: ").append(photoUrls).append("\n"); - sb.append(" tags: ").append(tags).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java index 3bf1b196e1d8..2f7b12a9c2db 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Tag.java @@ -1,13 +1,16 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; + + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") -public class Tag { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +public class Tag { private Long id = null; private String name = null; @@ -43,9 +46,9 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java index 0d454ec95aa4..be1089d751d9 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/User.java @@ -1,13 +1,16 @@ package io.swagger.client.model; +import io.swagger.client.StringUtil; + + import io.swagger.annotations.*; import com.fasterxml.jackson.annotation.JsonProperty; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-22T21:47:05.989+08:00") -public class User { +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +public class User { private Long id = null; private String username = null; @@ -122,15 +125,15 @@ public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); - sb.append(" id: ").append(id).append("\n"); - sb.append(" username: ").append(username).append("\n"); - sb.append(" firstName: ").append(firstName).append("\n"); - sb.append(" lastName: ").append(lastName).append("\n"); - sb.append(" email: ").append(email).append("\n"); - sb.append(" password: ").append(password).append("\n"); - sb.append(" phone: ").append(phone).append("\n"); - sb.append(" userStatus: ").append(userStatus).append("\n"); - sb.append("}\n"); + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); return sb.toString(); } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java index f8254311bce8..d75713c9a015 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiCallback.java @@ -2,6 +2,9 @@ import java.io.IOException; +import java.util.Map; +import java.util.List; + /** * Callback for asynchronous API call. * @@ -10,13 +13,19 @@ public interface ApiCallback { /** * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null */ - void onFailure(ApiException e); + void onFailure(ApiException e, int statusCode, Map> responseHeaders); /** * This is called when the API call succeeded. * * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response */ - void onSuccess(T result); + void onSuccess(T result, int statusCode, Map> responseHeaders); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index f189ea102384..33c009fa0a36 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -48,6 +48,9 @@ public class ApiClient { private Map authentications; + private int statusCode; + private Map> responseHeaders; + private String dateFormat; private DateFormat dateFormatter; private int dateLength; @@ -106,6 +109,24 @@ public ApiClient setJSON(JSON json) { return this; } + /** + * Gets the status code of the previous request. + * NOTE: Status code of last async response is not recorded here, it is + * passed to the callback methods instead. + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request. + * NOTE: Headers of last async response is not recorded here, it is passed + * to callback methods instead. + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + public String getDateFormat() { return dateFormat; } @@ -533,6 +554,8 @@ public T execute(Call call) throws ApiException { public T execute(Call call, Type returnType) throws ApiException { try { Response response = call.execute(); + this.statusCode = response.code(); + this.responseHeaders = response.headers().toMultimap(); return handleResponse(response, returnType); } catch (IOException e) { throw new ApiException(e); @@ -556,7 +579,7 @@ public void executeAsync(Call call, final Type returnType, final ApiCallback call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { - callback.onFailure(new ApiException(e)); + callback.onFailure(new ApiException(e), 0, null); } @Override @@ -565,10 +588,10 @@ public void onResponse(Response response) throws IOException { try { result = (T) handleResponse(response, returnType); } catch (ApiException e) { - callback.onFailure(e); + callback.onFailure(e, response.code(), response.headers().toMultimap()); return; } - callback.onSuccess(result); + callback.onSuccess(result, response.code(), response.headers().toMultimap()); } }); } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java index d19aa8ebb3a4..a76d5872a900 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java index 07c97e116d7e..7a4d947d5e5c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java index bb0cd8237915..5986bdd0db68 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java index 9a58d6d5558f..762f1c611610 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index 274297650694..ce1bae64a46e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -354,7 +354,7 @@ private Call getUserByNameCall(String username) throws ApiException { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ public User getUserByName(String username) throws ApiException { @@ -366,7 +366,7 @@ public User getUserByName(String username) throws ApiException { /** * Get user by user name (asynchronously) * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @param callback The callback to be executed when the API call finishes * @return The request call */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 20ebbf17e742..6bfe672ea939 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java index 9197d04b1b75..3fa136f64c00 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java index 184b9e82ca7c..4e3b5a035bdb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-08-31T19:27:38.337+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T13:13:26.059+08:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java index 0a8f8a1665d2..c9586343025c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -4,6 +4,7 @@ import io.swagger.client.ApiException; import io.swagger.client.Configuration; +import io.swagger.client.ApiCallback; import io.swagger.client.api.*; import io.swagger.client.auth.*; import io.swagger.client.model.*; @@ -13,7 +14,9 @@ import java.io.FileWriter; import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.List; +import java.util.Map; import org.junit.*; import static org.junit.Assert.*; @@ -68,6 +71,81 @@ public void testCreateAndGetPet() throws Exception { assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); } + @Test + public void testCreateAndGetPetAsync() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); + + api.getPetByIdAsync(pet.getId(), new ApiCallback() { + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + result.put("error", e.getMessage()); + } + + @Override + public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + }); + // the API call should be executed asynchronously, so result should be empty at the moment + assertTrue(result.isEmpty()); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("error") != null) fail((String) result.get("error")); + if (result.get("pet") != null) { + fetched = (Pet) result.get("pet"); + break; + } + } while (result.isEmpty()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + + // test getting a nonexistent pet + result.clear(); + api.getPetByIdAsync(new Long(-10000), new ApiCallback() { + @Override + public void onFailure(ApiException e, int statusCode, Map> responseHeaders) { + result.put("exception", e); + } + + @Override + public void onSuccess(Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + }); + // the API call should be executed asynchronously, so result should be empty at the moment + assertTrue(result.isEmpty()); + + // wait for the asynchronous call to finish (at most 10 seconds) + tryCount = 1; + ApiException exception = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("pet") != null) fail("expected an error"); + if (result.get("exception") != null) { + exception = (ApiException) result.get("exception"); + break; + } + } while (result.isEmpty()); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + assertEquals("Not Found", exception.getMessage()); + assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); + } + @Test public void testUpdatePet() throws Exception { Pet pet = createRandomPet(); From 16afd4ee9bb78c0a75b8160269716bed97e1f698 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 11 Sep 2015 18:02:51 +0800 Subject: [PATCH 073/219] update map to use String instead of string --- .../languages/CSharpClientCodegen.java | 2 +- .../src/main/csharp/IO/Swagger/Api/PetApi.cs | 3 +-- .../main/csharp/IO/Swagger/Api/StoreApi.cs | 23 +++++++++--------- .../src/main/csharp/IO/Swagger/Api/UserApi.cs | 11 ++++----- .../csharp/IO/Swagger/Client/ApiClient.cs | 2 +- .../SwaggerClientTest.userprefs | 2 +- .../bin/Debug/SwaggerClientTest.dll | Bin 57344 -> 57344 bytes .../bin/Debug/SwaggerClientTest.dll.mdb | Bin 16975 -> 16974 bytes .../obj/Debug/SwaggerClientTest.dll | Bin 57344 -> 57344 bytes .../obj/Debug/SwaggerClientTest.dll.mdb | Bin 16975 -> 16974 bytes 10 files changed, 20 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index f10d9a0f2990..4b17715e6653 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -218,7 +218,7 @@ public String getTypeDeclaration(Property p) { MapProperty mp = (MapProperty) p; Property inner = mp.getAdditionalProperties(); - return getSwaggerType(p) + ""; + return getSwaggerType(p) + ""; } return super.getTypeDeclaration(p); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 9f3bb5501b59..15dc644e4136 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -175,9 +175,8 @@ public void SetBasePath(String basePath) /// /// Gets the base path of the API client. /// - /// The base path /// The base path - public String GetBasePath(String basePath) + public String GetBasePath() { return this.ApiClient.BasePath; } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index 6dfd81bd99d1..1d927a28cd24 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -14,14 +14,14 @@ public interface IStoreApi /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary - Dictionary GetInventory (); + /// Dictionary + Dictionary GetInventory (); /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary - System.Threading.Tasks.Task> GetInventoryAsync (); + /// Dictionary + System.Threading.Tasks.Task> GetInventoryAsync (); /// /// Place an order for a pet @@ -107,9 +107,8 @@ public void SetBasePath(String basePath) /// /// Gets the base path of the API client. /// - /// The base path /// The base path - public String GetBasePath(String basePath) + public String GetBasePath() { return this.ApiClient.BasePath; } @@ -124,8 +123,8 @@ public String GetBasePath(String basePath) /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary - public Dictionary GetInventory () + /// Dictionary + public Dictionary GetInventory () { @@ -156,14 +155,14 @@ public String GetBasePath(String basePath) else if (((int)response.StatusCode) == 0) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.ErrorMessage, response.ErrorMessage); - return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); } /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary - public async System.Threading.Tasks.Task> GetInventoryAsync () + /// Dictionary + public async System.Threading.Tasks.Task> GetInventoryAsync () { @@ -191,7 +190,7 @@ public String GetBasePath(String basePath) if (((int)response.StatusCode) >= 400) throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content, response.Content); - return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); + return (Dictionary) ApiClient.Deserialize(response.Content, typeof(Dictionary), response.Headers); } /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 1ca200137a2d..719e6f2351bc 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -84,14 +84,14 @@ public interface IUserApi /// /// Get user by user name /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. /// User User GetUserByName (string username); /// /// Get user by user name /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. /// User System.Threading.Tasks.Task GetUserByNameAsync (string username); @@ -167,9 +167,8 @@ public void SetBasePath(String basePath) /// /// Gets the base path of the API client. /// - /// The base path /// The base path - public String GetBasePath(String basePath) + public String GetBasePath() { return this.ApiClient.BasePath; } @@ -573,7 +572,7 @@ public async System.Threading.Tasks.Task LogoutUserAsync () /// /// Get user by user name /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. /// User public User GetUserByName (string username) { @@ -616,7 +615,7 @@ public User GetUserByName (string username) /// /// Get user by user name /// - /// The name that needs to be fetched. Use user1 for testing. + /// The name that needs to be fetched. Use user1 for testing. /// User public async System.Threading.Tasks.Task GetUserByNameAsync (string username) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 4d87e7bd9c6e..09bc236a56f0 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -170,7 +170,7 @@ public void AddDefaultHeader(string key, string value) /// Escaped string. public string EscapeString(string str) { - return RestSharp.Extensions.StringExtensions.UrlDecode(str); + return RestSharp.Extensions.StringExtensions.UrlEncode(str); } /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index 3839afecb770..10c2758ea5e4 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -2,7 +2,7 @@ - + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 8f38016c832bf50d0ba402544b302681b7ea5fd7..4f62f5e8567c180ea3d6a5587dcb6a74425c14db 100755 GIT binary patch delta 3651 zcmYkhX$KLMULD2+>M8q)>N2(L8c%oLMl@fx2O?*MYmy{?1dYIBI zMr2HD6YvPNi5-cR2{kIjg9=Cm5=1eH5?>G%Uux}*lflGJI)-Vr)92+kckUl>pZz}1 zKF{yB$Lvzx6!;NRrF`k`8rDd*`Ykd|2q$OH5(;Xq7@{;XJcntbu`ADBK-*zK>Jk;l;GFirg z2~x{h_8eTKeB0gd2`Gq@**4q5@HiYH?Xlf8!k@?B^D_L9g%c4qQL51vWQ|8@yi~g_ z%sL6Jq;s}tYXZU&WHw}rwNAlnr0;DB)~Pr&S!Pdc)2-7mObXMIt<#Y+MP`v&n$?)W zKeMAZBww2z@sb2nk>+|z723;B={+qcVwQj80c~x>Y`>0Z8zX+=*D0;VJjbtdT5&`& zdgt;Jl~G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Q9H6WuCL4Xo*(Y!Job3rl8$s3P&~8d@@g3tmI@hTxn-sCYJ*4dH;0 zAs4)k%8kMBIu4Tfq&HBtDVW_rEs1A0fvv&pCfG*}+vJ?XxU(&o4P%1D$K68Kc99w4 z`QE~2Nm2a>nhJvhN6=2<13$-r_`s0We~u3EZj=j-BBv}kZWQ@Kby&^bn_r-cl*Kg0 zE>mzX6mU0I+uTR?SGmjgJKQz<{9 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 290bbd5f2e08039b04927f563bc5bd98f7715aa6..5eb1f662e8505257e0b19ead5f8b10fa2c268c47 100644 GIT binary patch delta 6321 zcmY+I2Urx>8ixO2mSvZ5c1*CU0DvAPDikcg5qDk&*q}U5bAyJ8f zqDDcQf`}#dE?|jhf+dPZMbyMz?>9T_#N~NjzW4m+pEGA?X7^dB%izvuaHG3yQNOpf z|I6Qv#GiNh)fbZWIt^R@;8+pe+?yUgjA$mN3_Xe3AzMEunt&91d7EE>&&7NfLrB|C z_^Q$SjUFzTadcegD@_jPD@Xf1T9HDzt7a`_ySN^m`ldD)oqqZxaR)cy+aD+0{gtiM zU(Cul8B5bMGkUqKBDA_GF30b7lV?)E#td4!YSuz_oi}7oe0L*)RF}A$ z><`sly%L@^sl3?xcE#Kqw!QsB?mWxw@QmBWmUO(&&117W-Q#Akah-dbe63kj@0krf zw|QZsSyZOSf6Z2P&g9h0)M&gxYcG1->q#%R(r~surcQCJgQ-d9Oxr;7dp}=$IZ;OtEIZakt!W`If`56`8fU|c}wzn`+ z@>d+G(ebL(P{?t{M&81_vb~YHl7Hn$uN~h=(>sJ|wJ3$Px|2b(Nk#B$18lG-*!v;c3U=xJ`DOe zNb0=pMR&ZK*;Dgg>VLfGnb&hK%@nRnFX6egk>z{S&)yrnb*jB(mEN?=d$&||6nY(G zr@ZO3_Zi)4KiLg$y6JsOs`l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q&HBtDVW_rEs1A0fvv&pCfG*}+vJ?XxU(&o4P%1D$K68Kc99w4 z`QE~2Nm2a>nhJvhN6=2<13$-r_`s0We~u3EZj=j-BBv}kZWQ@Kby&^bn_r-cl*Kg0 zE>mzX6mU0I+uTR?SGmjgJKQz<{9 diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 290bbd5f2e08039b04927f563bc5bd98f7715aa6..5eb1f662e8505257e0b19ead5f8b10fa2c268c47 100644 GIT binary patch delta 6321 zcmY+I2Urx>8ixO2mSvZ5c1*CU0DvAPDikcg5qDk&*q}U5bAyJ8f zqDDcQf`}#dE?|jhf+dPZMbyMz?>9T_#N~NjzW4m+pEGA?X7^dB%izvuaHG3yQNOpf z|I6Qv#GiNh)fbZWIt^R@;8+pe+?yUgjA$mN3_Xe3AzMEunt&91d7EE>&&7NfLrB|C z_^Q$SjUFzTadcegD@_jPD@Xf1T9HDzt7a`_ySN^m`ldD)oqqZxaR)cy+aD+0{gtiM zU(Cul8B5bMGkUqKBDA_GF30b7lV?)E#td4!YSuz_oi}7oe0L*)RF}A$ z><`sly%L@^sl3?xcE#Kqw!QsB?mWxw@QmBWmUO(&&117W-Q#Akah-dbe63kj@0krf zw|QZsSyZOSf6Z2P&g9h0)M&gxYcG1->q#%R(r~surcQCJgQ-d9Oxr;7dp}=$IZ;OtEIZakt!W`If`56`8fU|c}wzn`+ z@>d+G(ebL(P{?t{M&81_vb~YHl7Hn$uN~h=(>sJ|wJ3$Px|2b(Nk#B$18lG-*!v;c3U=xJ`DOe zNb0=pMR&ZK*;Dgg>VLfGnb&hK%@nRnFX6egk>z{S&)yrnb*jB(mEN?=d$&||6nY(G zr@ZO3_Zi)4KiLg$y6JsOs`lrMrlY&FaX;B}Z+hYVvTY_x#(N6OSj$%U&`O_GKH5`i zs?M?^AKK!xRjLjadWXnreQ2N0e%)%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8O+4>WkC=>Fbflj$XGBNJ`P8{1fsem1u^D}roz zF>(u70e^x#3K(2rNAv-{5^e@J1*_n$NPCb24@C9?x$t;o49J5|Lrwsz;TgzZfMyK_ z>me(_T6igP2UrI`g**z@!*3xkgAMT4$j4wKTxm}v2Akk&WCySrz7XjF^5KQZRiFS~ zhTI1V;iv6!7k|ZI3kJ85S3nW`4e|-t3UAc~|B(aR;MPbpupRD=bOk%$5y(KW6FvqR z4|c(4BBz1f@a4!1Pz*0Zt_OQ?eOVQx6zs)>jRVm+_&&Hl+zph#Bas6^DSRw40hGaK zA-@Ov;n~QA-~fCpasw!bHzE&$3OM&yd6I8+DkYS)2 zJ_$J*9EPVMe*{P1Imo5pD0~;P0Q?HCK^_D(@Tl*=OI17-|%h7E#MxmFEen*1B5{Xygl3)G{S#CT7&!W zdB`;I0N#XL4*r2RBR_$M@MI6{1b77h0XY>shMz*FfhX{5$jjg<+^q-R|BV Date: Fri, 11 Sep 2015 22:48:38 +0800 Subject: [PATCH 074/219] update C# ParamterToString to support array of object, add test case --- .../main/resources/csharp/ApiClient.mustache | 13 +++++++-- .../csharp/IO/Swagger/Client/ApiClient.cs | 13 +++++++-- .../SwaggerClientTest.csproj | 1 + .../csharp/SwaggerClientTest/TestApiClient.cs | 26 ++++++++++++++++++ .../bin/Debug/SwaggerClientTest.dll | Bin 57344 -> 57856 bytes .../bin/Debug/SwaggerClientTest.dll.mdb | Bin 16974 -> 17345 bytes ...ClientTest.csproj.FilesWrittenAbsolute.txt | 6 ++-- .../obj/Debug/SwaggerClientTest.dll | Bin 57344 -> 57856 bytes .../obj/Debug/SwaggerClientTest.dll.mdb | Bin 16974 -> 17345 bytes 9 files changed, 50 insertions(+), 9 deletions(-) create mode 100644 samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 3399d84297da..f29e7cf6bf59 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; @@ -189,7 +190,7 @@ namespace {{packageName}}.Client /// /// If parameter is DateTime, output in ISO8601 format. - /// If parameter is a list of string, join the list with ",". + /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// /// The parameter (header, path, query, form). @@ -198,8 +199,14 @@ namespace {{packageName}}.Client { if (obj is DateTime) return ((DateTime)obj).ToString ("u"); - else if (obj is List) - return String.Join(",", obj as List); + else if (obj is IList) { + string flattenString = ""; + string separator = ","; + foreach (var param in (IList)obj) { + flattenString += param.ToString() + separator; + } + return flattenString.Remove(flattenString.Length - 1);; + } else return Convert.ToString (obj); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 09bc236a56f0..76841f428d4d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -1,4 +1,5 @@ using System; +using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; @@ -189,7 +190,7 @@ public FileParameter ParameterToFile(string name, Stream stream) /// /// If parameter is DateTime, output in ISO8601 format. - /// If parameter is a list of string, join the list with ",". + /// If parameter is a list, join the list with ",". /// Otherwise just return the string. /// /// The parameter (header, path, query, form). @@ -198,8 +199,14 @@ public string ParameterToString(object obj) { if (obj is DateTime) return ((DateTime)obj).ToString ("u"); - else if (obj is List) - return String.Join(",", obj as List); + else if (obj is IList) { + string flattenString = ""; + string separator = ","; + foreach (var param in (IList)obj) { + flattenString += param.ToString() + separator; + } + return flattenString.Remove(flattenString.Length - 1);; + } else return Convert.ToString (obj); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj index 982ecc7a3158..00467e845ea9 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.csproj @@ -55,6 +55,7 @@ + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs new file mode 100644 index 000000000000..42cea3120fed --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs @@ -0,0 +1,26 @@ +using NUnit.Framework; +using System; +using System.Collections.Generic; +using IO.Swagger.Client; + +namespace SwaggerClient.TestApiClient +{ + public class TestApiClient + { + [Test ()] + public void TestParameterToString () + { + ApiClient api = new ApiClient (); + + // test array of string + List statusList = new List(new String[] {"available", "sold"}); + Assert.AreEqual("available,sold", api.ParameterToString (statusList)); + + // test array of int + List numList = new List(new int[] {1, 37}); + Assert.AreEqual("1,37", api.ParameterToString (numList)); + } + + } +} + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 4f62f5e8567c180ea3d6a5587dcb6a74425c14db..7a68ae28dc29a620984dcc8ccb843a8166253a95 100755 GIT binary patch delta 15176 zcmb_j349b)(y!Mu({uOC^c+b@fP`~61p!UCB%li@B1pIqIT9ffn2>}^fld@zz<^*Q zq5=yDu6Tij6;M_|A%X{oh=2So0cJXaT8R=%q0&P#y1M>V_3C=Br(gGk z(w&yl-Im2Gy&nRAj0b+Y{KS5`^EgV<@%T_*AX-mRet7ZX#gj>F zI;8=QZXA@e>;&alU(}y)IAR5OP8u4Uh$qdR=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iZYH6}U$v-9`CpoJ*{oB1sp=7sTh{m}5uyu`b_2BsCddepw z1F2qWUTJEgojMsPy{>%WClN`%yl=3ZR;oQFP&!hmY5Ms6?>YNg?IO^>on6s0560^m z2jZNANHVlljl>hHrjaO%$Y>(th)mRi;ri+*^DbGICR&-q|CrQHVwI@kxvRBPUhiWpm&YLLP zC0rKnBnvHw7dqjKsJ9Q5Rn{l#+fdZ+PrmtLRc5IPtA0>uCR9bBgHu diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 5eb1f662e8505257e0b19ead5f8b10fa2c268c47..4588e46813afab29b3ec36ea15970beac8d0cbcf 100644 GIT binary patch literal 17345 zcmd5^349aP_CAwIo1|&fBrQuQ-CLj(3Mo)Xij|KFWShJ+TLzW4k83iZqP&AB&o?wNDu&Kf-y zzj-ep_@({+(`#_6}hkOLD`KELKqS%(8)ti=w{CDvw|Ld-TB(rAub~R#CkDCG8K# z8-Kl~cc)7e@@e|hH0)k%Gt@lr(1Np7d$0bUv78(D+IyCBU(&RvY2YmLHIMt|_|@_2 zj;BuUbozKiW|#RRY39>1Zn3^txrnNUYT0n;qso-#iOb$zJG1VJaX0JJoTqQ_onOtg zlvs0%i)tAE$_=X~$qHYMF5vFHSm82cKFxi~#vfB$G$=QFNNM_G0%+*gFXz3Tms{^k zeBjY$jI0s8_p}6%fVr$7EGFG*$u2G(TEn(qx@YXRi@Vmow>Mzs&9An-yZ!0eVa1^* zmS$N>YZ$kpG z>;Lc2&yN2!r@T08(~?ag*V5~RtUk56;nY2p_y0SJCmkq4EWbtG8Fp&XiswwBt9rhn zCyq!)#1qMhT!>tW6ht^(!r2nerPM_3;+YouOyM}Q-fZe;2q%tvPNmV-(biFMReD;i zU!rGgA$}g~Vldh|cNTwb< z#8Nucw#2*VSkf_}*cRn(gNjQFZ3`}LgK`Tjwgp#ZNpYDqx;Sen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q=Nof{RdzZ~s>?nxdOvzWqC3zWsY(G(iu+eEW=2Y@Y+eL~=0xlM6oh_SIm% M{YGHEeI5A!0B!-}?f?J) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt index dded8c015ee5..286fb333c482 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt +++ b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.csproj.FilesWrittenAbsolute.txt @@ -1,8 +1,8 @@ /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/.NETFramework,Version=v4.5.AssemblyAttribute.cs +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll +/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll /Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/Newtonsoft.Json.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/RestSharp.dll -/Users/williamcheng/Code/swagger-codegen/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/nunit.framework.dll diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 4f62f5e8567c180ea3d6a5587dcb6a74425c14db..7a68ae28dc29a620984dcc8ccb843a8166253a95 100755 GIT binary patch delta 15176 zcmb_j349b)(y!Mu({uOC^c+b@fP`~61p!UCB%li@B1pIqIT9ffn2>}^fld@zz<^*Q zq5=yDu6Tij6;M_|A%X{oh=2So0cJXaT8R=%q0&P#y1M>V_3C=Br(gGk z(w&yl-Im2Gy&nRAj0b+Y{KS5`^EgV<@%T_*AX-mRet7ZX#gj>F zI;8=QZXA@e>;&alU(}y)IAR5OP8u4Uh$qdR=|QC>IthV06Irk~7k*0o7HD%XkRwQK zV};=YpcQ%n>p^Udi2Bez8bgxhAQOu#vlCia4@NFkt|Dc09`-X@NX9OLlab4`u|h+Q z+aAU4xXRnm&|>5~wyXg(uIM;+p|}JkUZ;(VjZHxiv|{PlELRqG2kZ!@At>tMfkN(H zY&yZ7m%u1yiA{1?qBD?jq!izSCs*b?j1Sh>y)@t!91xp{Tvjp#w}jG5@f4kfl5#7i z=E@w7*m}@;NrfH5Bs4rMiF;5`2o@^^lUXm8>Ige`xUU*Vwyf@z_oQs zQJ0Al2)RxM@#HoP?5I9Cpm}>*6|UI<3}sOvR))q+xK{UUm1TluSqQ*h^djaVNAK2K z=kyKSho+pPT!d*9M(@)X=F}JW>(A%3Rpy{hiamhTB}eD#XLGK*ts55CI8r|&M04g^ z+c+sw%_S$9Ty#Eaq6?6e77DP=CUWnC2$?&0O?7)DORQXTIl)%gR&&NRCW$Zm4whw4(gn;6fLF%H?r2#I^aR4$E0A<^CkD|ZODrw# zNewC1zZ}wj_)4@|+c>4Dp%)6*M)BIf#uqh35d9PKvDHXshcITVK15~L;_mL?YSdQk!h;JE8yJF{Bau) zWA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6cHGzx7#sFWa$|@6ZF+PnuyW*)*YGhxHJJBczmOsO~pji&g|URnuJepIY|gL zpXm&zBE48p>L+)G_28~Q$a(1k()5+P8tA#Z(!>;f`L65bf*RR( zyOQPU_#b^bu|?`f%|)I*_@l-ii%q>A&qPYKSdUaD>Q8>uQl5Q-fDHYP-SK++-9CNM ztG-8fyY;=htn%Ex0(zN>?xIAWy1ToW&%@r^-9cW!;b@q*GDR$6`H;#aJ+-ot{%~b8 zQLH~-d86p2uiMs5@AB~}u~bjoljV<5V+8&XEP1^#YRM|$)fetb@NAG#keFyo5^Bji z`s;f_TBS8fNcan}B@pncB?kf}M{FP^deuxvl7z1Xe-QsT)Z)bhN1`to|BScfBzCKj zjJ)tRl0!E1e?}lVC#xlYS2GjwpA#gt$fpg2TI%tl&VjXA z9FomKS(i58d=r^(WJ`iZYH6}U$v-9`CpoJ*{oB1sp=7sTh{m}5uyu`b_2BsCddepw z1F2qWUTJEgojMsPy{>%WClN`%yl=3ZR;oQFP&!hmY5Ms6?>YNg?IO^>on6s0560^m z2jZNANHVlljl>hHrjaO%$Y>(th)mRi;ri+*^DbGICR&-q|CrQHVwI@kxvRBPUhiWpm&YLLP zC0rKnBnvHw7dqjKsJ9Q5Rn{l#+fdZ+PrmtLRc5IPtA0>uCR9bBgHu diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 5eb1f662e8505257e0b19ead5f8b10fa2c268c47..4588e46813afab29b3ec36ea15970beac8d0cbcf 100644 GIT binary patch literal 17345 zcmd5^349aP_CAwIo1|&fBrQuQ-CLj(3Mo)Xij|KFWShJ+TLzW4k83iZqP&AB&o?wNDu&Kf-y zzj-ep_@({+(`#_6}hkOLD`KELKqS%(8)ti=w{CDvw|Ld-TB(rAub~R#CkDCG8K# z8-Kl~cc)7e@@e|hH0)k%Gt@lr(1Np7d$0bUv78(D+IyCBU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TU z9B>BkF7ycS5MV3x4Ddu?8}ushVqiP;1@I0Y&`c}LN$8!>8t7+$UC=GTUcheXF5oa= z4|FOx9(WJB06YlT3q2D260i??4tOf?KJ;4fGGIUSe((<91L%|BBftUZE8z3ML1;FJ z=q~gj=%&z(fDfTVz%77}pku)iz{k)T;1u96^bl}9@Co!~@L1qeXhksQC-i5~UeNBq z=g=#`{eUCTN5H#*qtF?xu^vJngFXxWDsUV+whhrk=o8Q*q4R++pdW%i0KSAyX^UT- z0bfC9fd>L#LvI6@0wqfc67^haLeA1#UuDfhPjD zpl^fc0k@&$9dSwy+<`6zy8(YdzXl!w+=c!gTm{^Nz5%`p+=p%*jyVAR06GG?GrtYp z8{8du1YHKs0vHmGVZsSzOKh;%J_qK&^JT*C6{$Cj&e(Q`Q4anZtN_n+5`M!--BIX* z?MGl0cq=Nof{RdzZ~s>?nxdOvzWqC3zWsY(G(iu+eEW=2Y@Y+eL~=0xlM6oh_SIm% M{YGHEeI5A!0B!-}?f?J) From 35f462f57135e957c17253127679e2af218d2b6f Mon Sep 17 00:00:00 2001 From: Madhukar Devaraju Date: Fri, 11 Sep 2015 14:56:37 -0700 Subject: [PATCH 075/219] Java: Support List of Enums in postProcessModels --- .../io/swagger/codegen/languages/JavaClientCodegen.java | 6 ++++++ 1 file changed, 6 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 fc72cbd21c5d..1c9118189384 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 @@ -349,6 +349,12 @@ public Map postProcessModels(Map objs) { CodegenModel cm = (CodegenModel) mo.get("model"); for (CodegenProperty var : cm.vars) { Map allowableValues = var.allowableValues; + + // handle ArrayProperty + if(var.items != null) { + allowableValues = var.items.allowableValues; + } + if (allowableValues == null) continue; List values = (List) allowableValues.get("values"); From 1321d5f9a55c62650f8a55eefcfd7aa1077b9f2b Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Fri, 11 Sep 2015 17:23:48 -0700 Subject: [PATCH 076/219] [Obj-C] Fixed an issue where NSNumber parameters would cause a crash in multipart/form-data upload endpoints --- .../src/main/resources/objc/api-body.mustache | 6 ++++++ 1 file changed, 6 insertions(+) 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 1aa22a0a0c62..d49a02dfbeb4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -115,6 +115,9 @@ static {{classname}}* singletonAPI = nil; NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; {{#headerParams}}if({{paramName}} != nil) + if([{{paramName}} isKindOfClass:[NSNumber class]]){ + headerParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; + } headerParams[@"{{baseName}}"] = {{paramName}}; {{/headerParams}} @@ -148,6 +151,9 @@ static {{classname}}* singletonAPI = nil; {{#formParams}} {{#notFile}} if ({{paramName}}) { + if([{{paramName}} isKindOfClass:[NSNumber class]]){ + formParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; + } formParams[@"{{baseName}}"] = {{paramName}}; } {{/notFile}}{{#isFile}} From 761f172c2f4a5e1844df93f21d08838f25d21d07 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Fri, 11 Sep 2015 17:27:25 -0700 Subject: [PATCH 077/219] forgot an 'else' statement --- .../src/main/resources/objc/api-body.mustache | 6 ++++-- 1 file changed, 4 insertions(+), 2 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 d49a02dfbeb4..ae049f66993e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -117,8 +117,9 @@ static {{classname}}* singletonAPI = nil; {{#headerParams}}if({{paramName}} != nil) if([{{paramName}} isKindOfClass:[NSNumber class]]){ headerParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; + }else{ + headerParams[@"{{baseName}}"] = {{paramName}}; } - headerParams[@"{{baseName}}"] = {{paramName}}; {{/headerParams}} // HTTP header `Accept` @@ -153,8 +154,9 @@ static {{classname}}* singletonAPI = nil; if ({{paramName}}) { if([{{paramName}} isKindOfClass:[NSNumber class]]){ formParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; + }else{ + formParams[@"{{baseName}}"] = {{paramName}}; } - formParams[@"{{baseName}}"] = {{paramName}}; } {{/notFile}}{{#isFile}} files[@"{{paramName}}"] = {{paramName}}; From 1268b0627ff3966ff101d06334f19f5957b9b5c0 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Fri, 11 Sep 2015 17:33:36 -0700 Subject: [PATCH 078/219] added NSNumber catch to pathParams as well --- .../src/main/resources/objc/api-body.mustache | 9 +++++++-- 1 file changed, 7 insertions(+), 2 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 ae049f66993e..3756704db71e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -100,7 +100,11 @@ static {{classname}}* singletonAPI = nil; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; {{#pathParams}}if ({{paramName}} != nil) { - pathParams[@"{{baseName}}"] = {{paramName}}; + if([{{paramName}} isKindOfClass:[NSNumber class]]){ + pathParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; + }else{ + pathParams[@"{{baseName}}"] = {{paramName}}; + } } {{/pathParams}} @@ -114,12 +118,13 @@ static {{classname}}* singletonAPI = nil; {{/queryParams}} NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - {{#headerParams}}if({{paramName}} != nil) + {{#headerParams}}if({{paramName}} != nil){ if([{{paramName}} isKindOfClass:[NSNumber class]]){ headerParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; }else{ headerParams[@"{{baseName}}"] = {{paramName}}; } + } {{/headerParams}} // HTTP header `Accept` From 8bb8a7a79ad72f6754b53bd705a7c3dcc9c6db62 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 12 Sep 2015 16:00:10 +0800 Subject: [PATCH 079/219] fix getHasXxxParam --- .../io/swagger/codegen/CodegenOperation.java | 41 +++++++++++++++---- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 0f24759db3e5..6eae2c6f0f58 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -30,24 +30,51 @@ public class CodegenOperation { public List> examples; public ExternalDocs externalDocs; public Map vendorExtensions; + public String nickname; // legacy support - private boolean nonempty(List params) - { + /** + * Check if there's at least one parameter + * + * @return true if parameter exists, false otherwise + */ + private boolean nonempty(List params) { return params != null && params.size() > 0; } + + /** + * Check if there's at least one body parameter + * + * @return true if body parameter exists, false otherwise + */ public boolean getHasBodyParam() { return nonempty(bodyParams); } + + /** + * Check if there's at least one query parameter + * + * @return true if query parameter exists, false otherwise + */ public boolean getHasQueryParams() { - return nonempty(bodyParams); + return nonempty(queryParams); } + + /** + * Check if there's at least one header parameter + * + * @return true if header parameter exists, false otherwise + */ public boolean getHasHeaderParams() { - return nonempty(bodyParams); + return nonempty(headerParams); } + + /** + * Check if there's at least one path parameter + * + * @return true if path parameter exists, false otherwise + */ public boolean getHasPathParams() { - return nonempty(bodyParams); + return nonempty(pathParams); } - // legacy support - public String nickname; } From 967c574f5bab1589926845f71aae3655ce3734e0 Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 13 Sep 2015 18:41:53 +0800 Subject: [PATCH 080/219] Support file downloading in Java okhttp-gson client --- .../libraries/okhttp-gson/ApiClient.mustache | 55 +++++++++++++++++++ .../java/io/swagger/client/ApiClient.java | 55 +++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index f8d7fad38490..43d8f86637b1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -22,6 +22,7 @@ import java.util.List; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URLEncoder; @@ -35,6 +36,9 @@ import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; +import okio.BufferedSink; +import okio.Okio; + import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; @@ -490,6 +494,10 @@ public class ApiClient { if (response == null || returnType == null) return null; + // Handle file downloading. + if (returnType.equals(File.class)) + return (T) downloadFileFromResponse(response); + String respBody; try { if (response.body() != null) @@ -538,6 +546,53 @@ public class ApiClient { } } + /** + * Download file from the given response. + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + return File.createTempFile(prefix, suffix); + } + /** * @see #execute(Call, Type) */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 33c009fa0a36..777e413e20ed 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -22,6 +22,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; +import java.util.regex.Matcher; import java.util.regex.Pattern; import java.net.URLEncoder; @@ -35,6 +36,9 @@ import java.text.SimpleDateFormat; import java.text.ParseException; +import okio.BufferedSink; +import okio.Okio; + import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; @@ -489,6 +493,10 @@ public T deserialize(Response response, Type returnType) throws ApiException if (response == null || returnType == null) return null; + // Handle file downloading. + if (returnType.equals(File.class)) + return (T) downloadFileFromResponse(response); + String respBody; try { if (response.body() != null) @@ -537,6 +545,53 @@ public String serialize(Object obj, String contentType) throws ApiException { } } + /** + * Download file from the given response. + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // File.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + return File.createTempFile(prefix, suffix); + } + /** * @see #execute(Call, Type) */ From 1ecb8a74c12d9cbb41298bfddcb0dc4bf2da61d3 Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 13 Sep 2015 21:02:22 +0800 Subject: [PATCH 081/219] Allow customizing temp folder for file downloading --- .../libraries/okhttp-gson/ApiClient.mustache | 22 ++++++++++++++++++- .../java/io/swagger/client/ApiClient.java | 22 ++++++++++++++++++- 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 43d8f86637b1..1c07a7483465 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -49,6 +49,7 @@ public class ApiClient { private boolean lenientOnJson = false; private boolean debugging = false; private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; private Map authentications; @@ -363,6 +364,22 @@ public class ApiClient { return this; } + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + /** * Format the given parameter object into string. */ @@ -590,7 +607,10 @@ public class ApiClient { prefix = "download-"; } - return File.createTempFile(prefix, suffix); + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); } /** diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 777e413e20ed..38d6a39cbccb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -49,6 +49,7 @@ public class ApiClient { private boolean lenientOnJson = false; private boolean debugging = false; private Map defaultHeaderMap = new HashMap(); + private String tempFolderPath = null; private Map authentications; @@ -362,6 +363,22 @@ public ApiClient setDebugging(boolean debugging) { return this; } + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default tempopary folder. + * + * @see https://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile(java.lang.String,%20java.lang.String,%20java.io.File) + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + /** * Format the given parameter object into string. */ @@ -589,7 +606,10 @@ public File prepareDownloadFile(Response response) throws IOException { prefix = "download-"; } - return File.createTempFile(prefix, suffix); + if (tempFolderPath == null) + return File.createTempFile(prefix, suffix); + else + return File.createTempFile(prefix, suffix, new File(tempFolderPath)); } /** From b0063d9e9f65085f59bb3e5f182013b38a85da89 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Mon, 14 Sep 2015 18:29:49 +0800 Subject: [PATCH 082/219] Objc client ssl verification --- .../resources/objc/ApiClient-body.mustache | 28 ++++++++-- .../resources/objc/ApiClient-header.mustache | 7 +++ .../objc/Configuration-body.mustache | 1 + .../objc/Configuration-header.mustache | 18 +++++-- .../petstore/objc/SwaggerClient.podspec | 5 ++ .../objc/SwaggerClient/SWGApiClient.h | 7 +++ .../objc/SwaggerClient/SWGApiClient.m | 28 ++++++++-- .../objc/SwaggerClient/SWGConfiguration.h | 18 +++++-- .../objc/SwaggerClient/SWGConfiguration.m | 1 + .../petstore/objc/SwaggerClient/SWGPetApi.m | 51 +++++++++++++++---- .../petstore/objc/SwaggerClient/SWGStoreApi.m | 12 ++++- .../petstore/objc/SwaggerClient/SWGUserApi.m | 18 +++++-- .../SwaggerClient/SWGViewController.m | 10 ++++ .../Tests/DeserializationTest.m | 5 +- 14 files changed, 182 insertions(+), 27 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 04c628ee5a32..6690dafc7cc8 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -28,6 +28,7 @@ static void (^reachabilityChangeBlock)(int); if (self) { self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; + self.securityPolicy = [self customSecurityPolicy]; // configure reachability [self configureCacheReachibility]; } @@ -278,7 +279,7 @@ static void (^reachabilityChangeBlock)(int); // pure object if ([class isEqualToString:@"NSObject"]) { - return [[NSObject alloc] init]; + return data; } // list of models @@ -407,7 +408,7 @@ static void (^reachabilityChangeBlock)(int); if([[{{classPrefix}}Configuration sharedConfig] debug]) [self logResponse:nil forRequest:request error:augmentedError]; - + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; @@ -740,5 +741,26 @@ static void (^reachabilityChangeBlock)(int); @throw e; } } - + +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:@[certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index fef1a2b79e7b..226033973f5a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -203,4 +203,11 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (id) sanitizeForSerialization:(id) object; +/** + * Custom security policy + * + * @return AFSecurityPolicy + */ +- (AFSecurityPolicy *) customSecurityPolicy; + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache index 9c941b107a02..167b05aef1fc 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache @@ -31,6 +31,7 @@ self.password = @""; self.tempFolderPath = nil; self.debug = NO; + self.verifySSL = YES; self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache index c9bac508bbbf..9abe135bc473 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache @@ -1,6 +1,6 @@ #import #import "{{classPrefix}}ApiClient.h" - + /** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. * * NOTE: This class is auto generated by the swagger code generator program. @@ -9,14 +9,14 @@ */ @class {{classPrefix}}ApiClient; - + @interface {{classPrefix}}Configuration : NSObject /** * Default api client */ @property (nonatomic) {{classPrefix}}ApiClient *apiClient; - + /** * Default base url */ @@ -75,6 +75,18 @@ */ + (instancetype) sharedConfig; +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + /** * Sets API key * diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index d9b02841cf98..0afb511073c3 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -20,6 +20,11 @@ Pod::Spec.new do |s| s.requires_arc = true s.framework = 'SystemConfiguration' + + s.homepage = "https://github.com/swagger-api/swagger-codegen" + s.license = "MIT" + s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } + s.author = { "Swagger" => "apiteam@swagger.io" } s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 580efa739a08..adf59bb25cfc 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -207,4 +207,11 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (id) sanitizeForSerialization:(id) object; +/** + * Custom security policy + * + * @return AFSecurityPolicy + */ +- (AFSecurityPolicy *) customSecurityPolicy; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 826443453b0e..8d640957decd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -28,6 +28,7 @@ - (instancetype)initWithBaseURL:(NSURL *)url { if (self) { self.requestSerializer = [AFJSONRequestSerializer serializer]; self.responseSerializer = [AFJSONResponseSerializer serializer]; + self.securityPolicy = [self customSecurityPolicy]; // configure reachability [self configureCacheReachibility]; } @@ -278,7 +279,7 @@ - (id) deserialize:(id) data class:(NSString *) class { // pure object if ([class isEqualToString:@"NSObject"]) { - return [[NSObject alloc] init]; + return data; } // list of models @@ -407,7 +408,7 @@ - (void) operationWithCompletionBlock: (NSURLRequest *)request if([[SWGConfiguration sharedConfig] debug]) [self logResponse:nil forRequest:request error:augmentedError]; - + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; @@ -740,5 +741,26 @@ - (id) sanitizeForSerialization:(id) object { @throw e; } } - + +- (AFSecurityPolicy *) customSecurityPolicy { + AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; + + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + + if (config.sslCaCert) { + NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; + [securityPolicy setPinnedCertificates:@[certData]]; + } + + if (config.verifySSL) { + [securityPolicy setAllowInvalidCertificates:NO]; + } + else { + [securityPolicy setAllowInvalidCertificates:YES]; + [securityPolicy setValidatesDomainName:NO]; + } + + return securityPolicy; +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h index 99f97cdec1b1..cd4e7117e892 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.h @@ -1,6 +1,6 @@ #import #import "SWGApiClient.h" - + /** The `SWGConfiguration` class manages the configurations for the sdk. * * NOTE: This class is auto generated by the swagger code generator program. @@ -9,14 +9,14 @@ */ @class SWGApiClient; - + @interface SWGConfiguration : NSObject /** * Default api client */ @property (nonatomic) SWGApiClient *apiClient; - + /** * Default base url */ @@ -75,6 +75,18 @@ */ + (instancetype) sharedConfig; +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + /** * Sets API key * diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 9cc1c07d9f9d..16ce311c59ed 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -31,6 +31,7 @@ - (instancetype) init { self.password = @""; self.tempFolderPath = nil; self.debug = NO; + self.verifySSL = YES; self.loggingFile = nil; self.mutableApiKey = [NSMutableDictionary dictionary]; self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 4b8eba705627..50a1583b8a33 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -421,7 +421,11 @@ -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - pathParams[@"petId"] = petId; + if([petId isKindOfClass:[NSNumber class]]){ + pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; + }else{ + pathParams[@"petId"] = petId; + } } @@ -513,7 +517,11 @@ -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - pathParams[@"petId"] = petId; + if([petId isKindOfClass:[NSNumber class]]){ + pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; + }else{ + pathParams[@"petId"] = petId; + } } @@ -551,13 +559,21 @@ -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId if (name) { - formParams[@"name"] = name; + if([name isKindOfClass:[NSNumber class]]){ + formParams[@"name"] = [((NSNumber *)name) stringValue]; + }else{ + formParams[@"name"] = name; + } } if (status) { - formParams[@"status"] = status; + if([status isKindOfClass:[NSNumber class]]){ + formParams[@"status"] = [((NSNumber *)status) stringValue]; + }else{ + formParams[@"status"] = status; + } } @@ -614,7 +630,11 @@ -(NSNumber*) deletePetWithCompletionBlock: (NSNumber*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - pathParams[@"petId"] = petId; + if([petId isKindOfClass:[NSNumber class]]){ + pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; + }else{ + pathParams[@"petId"] = petId; + } } @@ -622,8 +642,13 @@ -(NSNumber*) deletePetWithCompletionBlock: (NSNumber*) petId NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - if(apiKey != nil) - headerParams[@"api_key"] = apiKey; + if(apiKey != nil){ + if([apiKey isKindOfClass:[NSNumber class]]){ + headerParams[@"api_key"] = [((NSNumber *)apiKey) stringValue]; + }else{ + headerParams[@"api_key"] = apiKey; + } + } // HTTP header `Accept` @@ -708,7 +733,11 @@ -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - pathParams[@"petId"] = petId; + if([petId isKindOfClass:[NSNumber class]]){ + pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; + }else{ + pathParams[@"petId"] = petId; + } } @@ -746,7 +775,11 @@ -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId if (additionalMetadata) { - formParams[@"additionalMetadata"] = additionalMetadata; + if([additionalMetadata isKindOfClass:[NSNumber class]]){ + formParams[@"additionalMetadata"] = [((NSNumber *)additionalMetadata) stringValue]; + }else{ + formParams[@"additionalMetadata"] = additionalMetadata; + } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 5fdf86b43aff..e70a31561efd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -250,7 +250,11 @@ -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { - pathParams[@"orderId"] = orderId; + if([orderId isKindOfClass:[NSNumber class]]){ + pathParams[@"orderId"] = [((NSNumber *)orderId) stringValue]; + }else{ + pathParams[@"orderId"] = orderId; + } } @@ -336,7 +340,11 @@ -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { - pathParams[@"orderId"] = orderId; + if([orderId isKindOfClass:[NSNumber class]]){ + pathParams[@"orderId"] = [((NSNumber *)orderId) stringValue]; + }else{ + pathParams[@"orderId"] = orderId; + } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 75cf8d51b0ea..032c305d43ae 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -495,7 +495,11 @@ -(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { - pathParams[@"username"] = username; + if([username isKindOfClass:[NSNumber class]]){ + pathParams[@"username"] = [((NSNumber *)username) stringValue]; + }else{ + pathParams[@"username"] = username; + } } @@ -584,7 +588,11 @@ -(NSNumber*) updateUserWithCompletionBlock: (NSString*) username NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { - pathParams[@"username"] = username; + if([username isKindOfClass:[NSNumber class]]){ + pathParams[@"username"] = [((NSNumber *)username) stringValue]; + }else{ + pathParams[@"username"] = username; + } } @@ -670,7 +678,11 @@ -(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { - pathParams[@"username"] = username; + if([username isKindOfClass:[NSNumber class]]){ + pathParams[@"username"] = [((NSNumber *)username) stringValue]; + }else{ + pathParams[@"username"] = username; + } } diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index ab7f6e8f72e0..ea8adc5c0e54 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -21,6 +21,16 @@ @implementation SWGViewController - (void)viewDidLoad { [super viewDidLoad]; + + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + config.debug = YES; + config.verifySSL = NO; + + SWGPetApi *api = [[SWGPetApi alloc] init]; + SWGPet *pet = [self createPet]; + [api addPetWithCompletionBlock:pet completionHandler:^(NSError *error) { + NSLog(@"*** error: %@", error); + }]; } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m index 0460a4be4af1..7b4b348e4d50 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/DeserializationTest.m @@ -45,7 +45,10 @@ - (void)testDeserializeDateTime { } - (void)testDeserializeObject { - XCTAssertTrue([[apiClient deserialize:@"" class:@"NSObject*"] isKindOfClass:[NSObject class]]); + NSNumber *data = @1; + NSNumber *result = [apiClient deserialize:data class:@"NSObject*"]; + + XCTAssertEqualObjects(data, result); } - (void)testDeserializeString { From 0262d3c8d216074b67d6601130769de8995a597d Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 15 Sep 2015 09:57:55 +0800 Subject: [PATCH 083/219] Fix issue #1230 --- .../io/swagger/codegen/languages/PythonClientCodegen.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 8926a79343a5..a2960c512b56 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -41,6 +41,7 @@ public PythonClientCodegen() { typeMapping.clear(); typeMapping.put("integer", "int"); typeMapping.put("float", "float"); + typeMapping.put("number", "float"); typeMapping.put("long", "int"); typeMapping.put("double", "float"); typeMapping.put("array", "list"); @@ -272,12 +273,10 @@ public void setPackageVersion(String packageVersion) { /** * Generate Python package name from String `packageName` * - * (PEP 0008) Python packages should also have short, all-lowercase names, + * (PEP 0008) Python packages should also have short, all-lowercase names, * although the use of underscores is discouraged. */ public String generatePackageName(String packageName) { - return underscore(packageName.replaceAll("[^\\w]+", "")); + return underscore(packageName.replaceAll("[^\\w]+", "")); } } - - From 5d1e70544c91a91ddcb8ce0ca6ae1be510686c27 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 15 Sep 2015 15:04:39 +0800 Subject: [PATCH 084/219] Fix issue that using temp_folder_path from ApiClient It should use the one from the Configuration object --- .../src/main/resources/ruby/api_client.mustache | 5 +++-- samples/client/petstore/ruby/lib/petstore/api_client.rb | 5 +++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index c48629604c0b..0c7641a6b04c 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -160,7 +160,7 @@ module {{moduleName}} # @see Configuration#temp_folder_path # @return [File] the file downloaded def download_file(response) - tmp_file = Tempfile.new '', @temp_folder_path + tmp_file = Tempfile.new '', Configuration.temp_folder_path content_disposition = response.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] @@ -172,7 +172,8 @@ module {{moduleName}} tmp_file.close! File.open(path, 'w') { |file| file.write(response.body) } - logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + Configuration.logger.info "File written to #{path}. Please move the file to a proper "\ + "folder for further processing and delete the temp afterwards" File.new(path) end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index b025abd9eacc..6eda344b2d80 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -160,7 +160,7 @@ def convert_to_type(data, return_type) # @see Configuration#temp_folder_path # @return [File] the file downloaded def download_file(response) - tmp_file = Tempfile.new '', @temp_folder_path + tmp_file = Tempfile.new '', Configuration.temp_folder_path content_disposition = response.headers['Content-Disposition'] if content_disposition filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] @@ -172,7 +172,8 @@ def download_file(response) tmp_file.close! File.open(path, 'w') { |file| file.write(response.body) } - logger.info "File written to #{path}. Please move the file to a proper folder for further processing and delete the temp afterwards" + Configuration.logger.info "File written to #{path}. Please move the file to a proper "\ + "folder for further processing and delete the temp afterwards" File.new(path) end From bd63c1d9d96a7cc99ea75a167bb297aa5d1f0488 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 15 Sep 2015 16:40:23 +0800 Subject: [PATCH 085/219] Support OPTIONS http verb in python client. --- .../main/resources/python/api_client.mustache | 4 +++ .../src/main/resources/python/rest.mustache | 28 +++++-------------- .../python/swagger_client/__init__.py | 2 +- .../python/swagger_client/api_client.py | 12 +++++--- .../python/swagger_client/apis/__init__.py | 2 +- .../python/swagger_client/apis/pet_api.py | 2 +- .../petstore/python/swagger_client/rest.py | 28 +++++-------------- 7 files changed, 29 insertions(+), 49 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 84a1dca45ffc..5ec6ddbcccc4 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -338,6 +338,10 @@ class ApiClient(object): return self.rest_client.HEAD(url, query_params=query_params, headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 1481cbff3d52..6279daedec3f 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -103,7 +103,7 @@ class RESTClientObject(object): and `multipart/form-data` """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -138,7 +138,7 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, headers=headers) - # For `GET`, `HEAD`, `DELETE` + # For `GET`, `HEAD`, `DELETE`, `OPTIONS` else: r = self.pool_manager.request(method, url, fields=query_params, @@ -172,6 +172,11 @@ class RESTClientObject(object): headers=headers, query_params=query_params) + def OPTIONS(self, url, headers=None, query_params=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params) + def DELETE(self, url, headers=None, query_params=None): return self.request("DELETE", url, headers=headers, @@ -226,22 +231,3 @@ class ApiException(Exception): error_message += "HTTP response body: {0}\n".format(self.body) return error_message - - - - - - - - - - - - - - - - - - - diff --git a/samples/client/petstore/python/swagger_client/__init__.py b/samples/client/petstore/python/swagger_client/__init__.py index f61c5d55262a..6e7b59f36fde 100644 --- a/samples/client/petstore/python/swagger_client/__init__.py +++ b/samples/client/petstore/python/swagger_client/__init__.py @@ -9,8 +9,8 @@ # import apis into sdk package from .apis.user_api import UserApi -from .apis.pet_api import PetApi from .apis.store_api import StoreApi +from .apis.pet_api import PetApi # import ApiClient from .api_client import ApiClient diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 1030bf9a8385..a9d32c956ef4 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -270,7 +270,7 @@ def __deserialize(self, data, klass): if klass in [int, float, str, bool]: return self.__deserialize_primitive(data, klass) elif klass == object: - return self.__deserialize_object() + return self.__deserialize_object(data) elif klass == date: return self.__deserialize_date(data) elif klass == datetime: @@ -338,6 +338,10 @@ def request(self, method, url, query_params=None, headers=None, return self.rest_client.HEAD(url, query_params=query_params, headers=headers) + elif method == "OPTIONS": + return self.rest_client.OPTIONS(url, + query_params=query_params, + headers=headers) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, @@ -495,13 +499,13 @@ def __deserialize_primitive(self, data, klass): value = data return value - def __deserialize_object(self): + def __deserialize_object(self, value): """ - Deserializes empty object. + Return a original value. :return: object. """ - return object() + return value def __deserialize_date(self, string): """ diff --git a/samples/client/petstore/python/swagger_client/apis/__init__.py b/samples/client/petstore/python/swagger_client/apis/__init__.py index 592a56e282d2..c0e09458f950 100644 --- a/samples/client/petstore/python/swagger_client/apis/__init__.py +++ b/samples/client/petstore/python/swagger_client/apis/__init__.py @@ -2,5 +2,5 @@ # import apis into api package from .user_api import UserApi -from .pet_api import PetApi from .store_api import StoreApi +from .pet_api import PetApi diff --git a/samples/client/petstore/python/swagger_client/apis/pet_api.py b/samples/client/petstore/python/swagger_client/apis/pet_api.py index ad053a7d72d9..b162cc534c38 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -409,7 +409,7 @@ def get_pet_by_id(self, pet_id, **kwargs): select_header_content_type([]) # Authentication setting - auth_settings = ['api_key', 'petstore_auth'] + auth_settings = ['petstore_auth', 'api_key'] response = self.api_client.call_api(resource_path, method, path_params, diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 1481cbff3d52..6279daedec3f 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -103,7 +103,7 @@ def request(self, method, url, query_params=None, headers=None, and `multipart/form-data` """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH', 'OPTIONS'] if post_params and body: raise ValueError( @@ -138,7 +138,7 @@ def request(self, method, url, query_params=None, headers=None, fields=post_params, encode_multipart=True, headers=headers) - # For `GET`, `HEAD`, `DELETE` + # For `GET`, `HEAD`, `DELETE`, `OPTIONS` else: r = self.pool_manager.request(method, url, fields=query_params, @@ -172,6 +172,11 @@ def HEAD(self, url, headers=None, query_params=None): headers=headers, query_params=query_params) + def OPTIONS(self, url, headers=None, query_params=None): + return self.request("OPTIONS", url, + headers=headers, + query_params=query_params) + def DELETE(self, url, headers=None, query_params=None): return self.request("DELETE", url, headers=headers, @@ -226,22 +231,3 @@ def __str__(self): error_message += "HTTP response body: {0}\n".format(self.body) return error_message - - - - - - - - - - - - - - - - - - - From ade61c0701868c07b6ab9799a9e5772f3752a109 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 15 Sep 2015 17:48:59 +0800 Subject: [PATCH 086/219] Support http body in OPTIONS request in python client --- .../src/main/resources/python/api_client.mustache | 4 +++- .../src/main/resources/python/rest.mustache | 12 +++++++----- .../petstore/python/swagger_client/api_client.py | 4 +++- .../client/petstore/python/swagger_client/rest.py | 12 +++++++----- 4 files changed, 20 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 5ec6ddbcccc4..f62f341045b7 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -341,7 +341,9 @@ class ApiClient(object): elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, - headers=headers) + headers=headers, + post_params=post_params, + body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 6279daedec3f..07be648373ac 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -117,8 +117,8 @@ class RESTClientObject(object): headers['Content-Type'] = 'application/json' try: - # For `POST`, `PUT`, `PATCH` - if method in ['POST', 'PUT', 'PATCH']: + # For `POST`, `PUT`, `PATCH`, `OPTIONS` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS']: if query_params: url += '?' + urlencode(query_params) if headers['Content-Type'] == 'application/json': @@ -138,7 +138,7 @@ class RESTClientObject(object): fields=post_params, encode_multipart=True, headers=headers) - # For `GET`, `HEAD`, `DELETE`, `OPTIONS` + # For `GET`, `HEAD`, `DELETE` else: r = self.pool_manager.request(method, url, fields=query_params, @@ -172,10 +172,12 @@ class RESTClientObject(object): headers=headers, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("OPTIONS", url, headers=headers, - query_params=query_params) + query_params=query_params, + post_params=post_params, + body=body) def DELETE(self, url, headers=None, query_params=None): return self.request("DELETE", url, diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index a9d32c956ef4..b44c4a321a66 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -341,7 +341,9 @@ def request(self, method, url, query_params=None, headers=None, elif method == "OPTIONS": return self.rest_client.OPTIONS(url, query_params=query_params, - headers=headers) + headers=headers, + post_params=post_params, + body=body) elif method == "POST": return self.rest_client.POST(url, query_params=query_params, diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 6279daedec3f..07be648373ac 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -117,8 +117,8 @@ def request(self, method, url, query_params=None, headers=None, headers['Content-Type'] = 'application/json' try: - # For `POST`, `PUT`, `PATCH` - if method in ['POST', 'PUT', 'PATCH']: + # For `POST`, `PUT`, `PATCH`, `OPTIONS` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS']: if query_params: url += '?' + urlencode(query_params) if headers['Content-Type'] == 'application/json': @@ -138,7 +138,7 @@ def request(self, method, url, query_params=None, headers=None, fields=post_params, encode_multipart=True, headers=headers) - # For `GET`, `HEAD`, `DELETE`, `OPTIONS` + # For `GET`, `HEAD`, `DELETE` else: r = self.pool_manager.request(method, url, fields=query_params, @@ -172,10 +172,12 @@ def HEAD(self, url, headers=None, query_params=None): headers=headers, query_params=query_params) - def OPTIONS(self, url, headers=None, query_params=None): + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, body=None): return self.request("OPTIONS", url, headers=headers, - query_params=query_params) + query_params=query_params, + post_params=post_params, + body=body) def DELETE(self, url, headers=None, query_params=None): return self.request("DELETE", url, From 2ac41ff0800ef667e170d879242cdeceaaccd6dd Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 15 Sep 2015 22:14:13 +0800 Subject: [PATCH 087/219] repalced hard-coded fileDetail with {{baseName}} --- .../src/main/resources/JavaSpringMVC/formParams.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache index 402a684f86ac..65e84817a23a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache @@ -1,2 +1,2 @@ {{#isFormParam}}{{#notFile}} -@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile {{baseName}}{{/isFile}}{{/isFormParam}} From 7eec76965497a852c387ae8cfe544ac46fe4db0a Mon Sep 17 00:00:00 2001 From: Paul Ebermann Date: Wed, 16 Sep 2015 11:36:51 +0200 Subject: [PATCH 088/219] Use the swagger property names in all Java models. This changes `@JsonProperty({{name}})` to `@JsonProperty({{baseName}})` in model.mustache for JavaInflector, JavaJaxRS and JavaSpringMVC. In pull request #535 this was already done for the plain Java files (which get used on client side). This replaces the sanitized names in the generated code by the original property names from the swagger document. --- .../src/main/resources/JavaInflector/model.mustache | 2 +- .../swagger-codegen/src/main/resources/JavaJaxRS/model.mustache | 2 +- .../src/main/resources/JavaSpringMVC/model.mustache | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache index db2480a85403..39f0f0b6fa12 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/model.mustache @@ -28,7 +28,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * maximum: {{maximum}}{{/maximum}} **/ @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{name}}") + @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache index a959c224498e..72a371280b39 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/model.mustache @@ -28,7 +28,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * maximum: {{maximum}}{{/maximum}} **/ @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{name}}") + @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache index db2480a85403..39f0f0b6fa12 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/model.mustache @@ -28,7 +28,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { * maximum: {{maximum}}{{/maximum}} **/ @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @JsonProperty("{{name}}") + @JsonProperty("{{baseName}}") public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } From 460c8caa8acaff2594cdb887f2968e2145003572 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 16 Sep 2015 22:42:12 +0800 Subject: [PATCH 089/219] Support OPTIONS in Java okhttp-gson client --- .../libraries/okhttp-gson/ApiClient.mustache | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 1c07a7483465..fcbedb0e9f4b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -10,6 +10,7 @@ import com.squareup.okhttp.FormEncodingBuilder; import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; import java.lang.reflect.Type; @@ -698,7 +699,7 @@ public class ApiClient { * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE" + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters @@ -718,7 +719,7 @@ public class ApiClient { if (contentType == null) contentType = "application/json"; RequestBody reqBody; - if ("GET".equals(method) || "HEAD".equals(method)) { + if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); @@ -736,28 +737,7 @@ public class ApiClient { reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); } - Request request; - if ("GET".equals(method)) { - request = reqBuilder.get().build(); - } else if ("HEAD".equals(method)) { - request = reqBuilder.head().build(); - } else if ("POST".equals(method)) { - request = reqBuilder.post(reqBody).build(); - } else if ("PUT".equals(method)) { - request = reqBuilder.put(reqBody).build(); - } else if ("PATCH".equals(method)) { - request = reqBuilder.patch(reqBody).build(); - } else if ("DELETE".equals(method)) { - if (reqBody == null) { - // calling DELETE without sending a request body - request = reqBuilder.delete().build(); - } else { - request = reqBuilder.delete(reqBody).build(); - } - } else { - throw new ApiException("unknown method type: " + method); - } - + Request request = reqBuilder.method(method, reqBody).build(); return httpClient.newCall(request); } From 477d5c40d9d4526cf66f13c5eb342765a3ae1680 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 17 Sep 2015 10:21:11 +0800 Subject: [PATCH 090/219] Rebuild Java okhttp-gson client of Petstore sample --- .../java/io/swagger/client/ApiClient.java | 28 +++---------------- 1 file changed, 4 insertions(+), 24 deletions(-) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index 38d6a39cbccb..ba1a834fb8d6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -10,6 +10,7 @@ import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; +import com.squareup.okhttp.internal.http.HttpMethod; import java.lang.reflect.Type; @@ -697,7 +698,7 @@ public T handleResponse(Response response, Type returnType) throws ApiExcept * Build HTTP call with the given options. * * @param path The sub-path of the HTTP URL - * @param method The request method, one of "GET", "HEAD", "POST", "PUT", "PATCH" and "DELETE" + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" * @param queryParams The query parameters * @param body The request body object * @param headerParams The header parameters @@ -717,7 +718,7 @@ public Call buildCall(String path, String method, List queryParams, Object if (contentType == null) contentType = "application/json"; RequestBody reqBody; - if ("GET".equals(method) || "HEAD".equals(method)) { + if (!HttpMethod.permitsRequestBody(method)) { reqBody = null; } else if ("application/x-www-form-urlencoded".equals(contentType)) { reqBody = buildRequestBodyFormEncoding(formParams); @@ -735,28 +736,7 @@ public Call buildCall(String path, String method, List queryParams, Object reqBody = RequestBody.create(MediaType.parse(contentType), serialize(body, contentType)); } - Request request; - if ("GET".equals(method)) { - request = reqBuilder.get().build(); - } else if ("HEAD".equals(method)) { - request = reqBuilder.head().build(); - } else if ("POST".equals(method)) { - request = reqBuilder.post(reqBody).build(); - } else if ("PUT".equals(method)) { - request = reqBuilder.put(reqBody).build(); - } else if ("PATCH".equals(method)) { - request = reqBuilder.patch(reqBody).build(); - } else if ("DELETE".equals(method)) { - if (reqBody == null) { - // calling DELETE without sending a request body - request = reqBuilder.delete().build(); - } else { - request = reqBuilder.delete(reqBody).build(); - } - } else { - throw new ApiException("unknown method type: " + method); - } - + Request request = reqBuilder.method(method, reqBody).build(); return httpClient.newCall(request); } From 85df7c8ed7e37fde105b5f00ff0779784743fc9c Mon Sep 17 00:00:00 2001 From: Justin Chines Date: Wed, 16 Sep 2015 22:09:01 -0700 Subject: [PATCH 091/219] [DOC] fix typo in Python api_client template --- .../src/main/resources/python/api_client.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index f62f341045b7..13ec8ed43964 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -180,7 +180,7 @@ class ApiClient(object): If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. + If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the properties dict. From fb14585adf2a2235e9f2a1913d9a35cc53554431 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 17 Sep 2015 15:20:11 +0800 Subject: [PATCH 092/219] Add parameterToString method --- .../resources/objc/ApiClient-body.mustache | 29 ++++++++++- .../resources/objc/ApiClient-header.mustache | 5 ++ .../src/main/resources/objc/api-body.mustache | 20 ++------ .../petstore/objc/SwaggerClient.podspec | 8 +-- .../objc/SwaggerClient/SWGApiClient.h | 5 ++ .../objc/SwaggerClient/SWGApiClient.m | 29 ++++++++++- .../petstore/objc/SwaggerClient/SWGPetApi.m | 50 ++++--------------- .../petstore/objc/SwaggerClient/SWGStoreApi.m | 12 +---- .../petstore/objc/SwaggerClient/SWGUserApi.h | 2 +- .../petstore/objc/SwaggerClient/SWGUserApi.m | 20 ++------ .../SwaggerClient/SWGViewController.m | 5 +- 11 files changed, 92 insertions(+), 93 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 6690dafc7cc8..fed095c3c5ad 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -546,7 +546,8 @@ static void (^reachabilityChangeBlock)(int); parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; + NSString *objString = [self parameterToString:obj]; + NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { @@ -763,4 +764,30 @@ static void (^reachabilityChangeBlock)(int); return securityPolicy; } +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [param ISO8601String]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@", "]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 226033973f5a..6a9aadfa08b9 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -210,4 +210,9 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + @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 3756704db71e..60358e4e9da8 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -100,11 +100,7 @@ static {{classname}}* singletonAPI = nil; NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; {{#pathParams}}if ({{paramName}} != nil) { - if([{{paramName}} isKindOfClass:[NSNumber class]]){ - pathParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; - }else{ - pathParams[@"{{baseName}}"] = {{paramName}}; - } + pathParams[@"{{baseName}}"] = {{paramName}}; } {{/pathParams}} @@ -118,12 +114,8 @@ static {{classname}}* singletonAPI = nil; {{/queryParams}} NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - {{#headerParams}}if({{paramName}} != nil){ - if([{{paramName}} isKindOfClass:[NSNumber class]]){ - headerParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; - }else{ - headerParams[@"{{baseName}}"] = {{paramName}}; - } + {{#headerParams}}if({{paramName}} != nil) { + headerParams[@"{{baseName}}"] = {{paramName}}; } {{/headerParams}} @@ -157,11 +149,7 @@ static {{classname}}* singletonAPI = nil; {{#formParams}} {{#notFile}} if ({{paramName}}) { - if([{{paramName}} isKindOfClass:[NSNumber class]]){ - formParams[@"{{baseName}}"] = [((NSNumber *){{paramName}}) stringValue]; - }else{ - formParams[@"{{baseName}}"] = {{paramName}}; - } + formParams[@"{{baseName}}"] = {{paramName}}; } {{/notFile}}{{#isFile}} files[@"{{paramName}}"] = {{paramName}}; diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 0afb511073c3..4445bc52ad23 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -21,10 +21,10 @@ Pod::Spec.new do |s| s.framework = 'SystemConfiguration' - s.homepage = "https://github.com/swagger-api/swagger-codegen" - s.license = "MIT" - s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } - s.author = { "Swagger" => "apiteam@swagger.io" } + s.homepage = "" + s.license = "" + s.source = { :git => ".git", :tag => "#{s.version}" } + s.author = { "" => "" } s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index adf59bb25cfc..c703d8a22d25 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -214,4 +214,9 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (AFSecurityPolicy *) customSecurityPolicy; +/** + * Convert parameter to NSString + */ +- (NSString *) parameterToString: (id) param; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 8d640957decd..678589e7a02a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -546,7 +546,8 @@ -(NSNumber*) requestWithCompletionBlock: (NSString*) path parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; + NSString *objString = [self parameterToString:obj]; + NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { @@ -763,4 +764,30 @@ - (AFSecurityPolicy *) customSecurityPolicy { return securityPolicy; } +- (NSString *) parameterToString:(id)param { + if ([param isKindOfClass:[NSString class]]) { + return param; + } + else if ([param isKindOfClass:[NSNumber class]]) { + return [param stringValue]; + } + else if ([param isKindOfClass:[NSDate class]]) { + return [param ISO8601String]; + } + else if ([param isKindOfClass:[NSArray class]]) { + NSMutableArray *mutableParam; + [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [mutableParam addObject:[self parameterToString:obj]]; + }]; + return [mutableParam componentsJoinedByString:@", "]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", param] + userInfo:nil]; + @throw e; + } +} + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 50a1583b8a33..b890e03570fb 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -421,11 +421,7 @@ -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - if([petId isKindOfClass:[NSNumber class]]){ - pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; - }else{ - pathParams[@"petId"] = petId; - } + pathParams[@"petId"] = petId; } @@ -517,11 +513,7 @@ -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - if([petId isKindOfClass:[NSNumber class]]){ - pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; - }else{ - pathParams[@"petId"] = petId; - } + pathParams[@"petId"] = petId; } @@ -559,21 +551,13 @@ -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId if (name) { - if([name isKindOfClass:[NSNumber class]]){ - formParams[@"name"] = [((NSNumber *)name) stringValue]; - }else{ - formParams[@"name"] = name; - } + formParams[@"name"] = name; } if (status) { - if([status isKindOfClass:[NSNumber class]]){ - formParams[@"status"] = [((NSNumber *)status) stringValue]; - }else{ - formParams[@"status"] = status; - } + formParams[@"status"] = status; } @@ -630,11 +614,7 @@ -(NSNumber*) deletePetWithCompletionBlock: (NSNumber*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - if([petId isKindOfClass:[NSNumber class]]){ - pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; - }else{ - pathParams[@"petId"] = petId; - } + pathParams[@"petId"] = petId; } @@ -642,12 +622,8 @@ -(NSNumber*) deletePetWithCompletionBlock: (NSNumber*) petId NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; - if(apiKey != nil){ - if([apiKey isKindOfClass:[NSNumber class]]){ - headerParams[@"api_key"] = [((NSNumber *)apiKey) stringValue]; - }else{ - headerParams[@"api_key"] = apiKey; - } + if(apiKey != nil) { + headerParams[@"api_key"] = apiKey; } @@ -733,11 +709,7 @@ -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (petId != nil) { - if([petId isKindOfClass:[NSNumber class]]){ - pathParams[@"petId"] = [((NSNumber *)petId) stringValue]; - }else{ - pathParams[@"petId"] = petId; - } + pathParams[@"petId"] = petId; } @@ -775,11 +747,7 @@ -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId if (additionalMetadata) { - if([additionalMetadata isKindOfClass:[NSNumber class]]){ - formParams[@"additionalMetadata"] = [((NSNumber *)additionalMetadata) stringValue]; - }else{ - formParams[@"additionalMetadata"] = additionalMetadata; - } + formParams[@"additionalMetadata"] = additionalMetadata; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index e70a31561efd..5fdf86b43aff 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -250,11 +250,7 @@ -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { - if([orderId isKindOfClass:[NSNumber class]]){ - pathParams[@"orderId"] = [((NSNumber *)orderId) stringValue]; - }else{ - pathParams[@"orderId"] = orderId; - } + pathParams[@"orderId"] = orderId; } @@ -340,11 +336,7 @@ -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (orderId != nil) { - if([orderId isKindOfClass:[NSNumber class]]){ - pathParams[@"orderId"] = [((NSNumber *)orderId) stringValue]; - }else{ - pathParams[@"orderId"] = orderId; - } + pathParams[@"orderId"] = orderId; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 21f314684fd7..ec41ecd99078 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -99,7 +99,7 @@ /// Get user by user name /// /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// /// @return SWGUser* diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 032c305d43ae..5c3c313b2e23 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -470,7 +470,7 @@ -(NSNumber*) logoutUserWithCompletionBlock: /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// @returns SWGUser* /// @@ -495,11 +495,7 @@ -(NSNumber*) getUserByNameWithCompletionBlock: (NSString*) username NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { - if([username isKindOfClass:[NSNumber class]]){ - pathParams[@"username"] = [((NSNumber *)username) stringValue]; - }else{ - pathParams[@"username"] = username; - } + pathParams[@"username"] = username; } @@ -588,11 +584,7 @@ -(NSNumber*) updateUserWithCompletionBlock: (NSString*) username NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { - if([username isKindOfClass:[NSNumber class]]){ - pathParams[@"username"] = [((NSNumber *)username) stringValue]; - }else{ - pathParams[@"username"] = username; - } + pathParams[@"username"] = username; } @@ -678,11 +670,7 @@ -(NSNumber*) deleteUserWithCompletionBlock: (NSString*) username NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; if (username != nil) { - if([username isKindOfClass:[NSNumber class]]){ - pathParams[@"username"] = [((NSNumber *)username) stringValue]; - }else{ - pathParams[@"username"] = username; - } + pathParams[@"username"] = username; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m index ea8adc5c0e54..ec80b4e52b1e 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -24,11 +24,10 @@ - (void)viewDidLoad SWGConfiguration *config = [SWGConfiguration sharedConfig]; config.debug = YES; - config.verifySSL = NO; SWGPetApi *api = [[SWGPetApi alloc] init]; - SWGPet *pet = [self createPet]; - [api addPetWithCompletionBlock:pet completionHandler:^(NSError *error) { + NSURL *file = [NSURL fileURLWithPath:@"/Users/geekerzp/tmp/test.jpg"]; + [api uploadFileWithCompletionBlock:@2 additionalMetadata:@2 file:file completionHandler:^(NSError *error) { NSLog(@"*** error: %@", error); }]; } From 261ae795289acc590d4a2796ea59d9681318ef21 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 17 Sep 2015 15:59:03 +0800 Subject: [PATCH 093/219] Remove space from parameterToString in objc client --- .../src/main/resources/objc/ApiClient-body.mustache | 2 +- samples/client/petstore/objc/SwaggerClient/SWGApiClient.m | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index fed095c3c5ad..119ff67572bd 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -779,7 +779,7 @@ static void (^reachabilityChangeBlock)(int); [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [mutableParam addObject:[self parameterToString:obj]]; }]; - return [mutableParam componentsJoinedByString:@", "]; + return [mutableParam componentsJoinedByString:@","]; } else { NSException *e = [NSException diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 678589e7a02a..8767498dcafc 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -779,7 +779,7 @@ - (NSString *) parameterToString:(id)param { [param enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [mutableParam addObject:[self parameterToString:obj]]; }]; - return [mutableParam componentsJoinedByString:@", "]; + return [mutableParam componentsJoinedByString:@","]; } else { NSException *e = [NSException From cc1c495ea5ab7127128a28e9d8772edac6808ab9 Mon Sep 17 00:00:00 2001 From: DariusM Date: Wed, 16 Sep 2015 12:03:30 +0200 Subject: [PATCH 094/219] unicode type forgotten in api_client.mustache --- .../src/main/resources/python/api_client.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 13ec8ed43964..8b948b5f4e84 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -189,7 +189,7 @@ class ApiClient(object): """ if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, float, bool, tuple)): + elif isinstance(obj, (str, int, float, bool, tuple, unicode)): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) From 65f86dbb0f3549821c357171f44c86325bdbeb5b Mon Sep 17 00:00:00 2001 From: DariusM Date: Thu, 17 Sep 2015 10:31:40 +0200 Subject: [PATCH 095/219] unicode type forgotten in api_client.mustache for python2, works also with python3 --- .../src/main/resources/python/api_client.mustache | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 8b948b5f4e84..4b10f96a73e2 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -187,9 +187,12 @@ class ApiClient(object): :param obj: The data to serialize. :return: The serialized form of data. """ + types = (str, int, float, bool, tuple) + if sys.version_info < (3,0): + types = types + (unicode,) if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, float, bool, tuple, unicode)): + elif isinstance(obj, types): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) From 781458b0d19823d7b7e036c87fa2368468083f84 Mon Sep 17 00:00:00 2001 From: Laurent Van der Linden Date: Thu, 17 Sep 2015 12:46:20 +0200 Subject: [PATCH 096/219] Use the baseName when referring to path and query parameters. --- .../src/main/resources/TypeScript-Angular/api.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 23b5fe2ea50b..e459a7b419c0 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -27,7 +27,7 @@ module {{package}} { var path = this.basePath + '{{path}}'; {{#pathParams}} - path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); + path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); {{/pathParams}} var queryParameters: any = {}; @@ -44,7 +44,7 @@ module {{package}} { {{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters['{{paramName}}'] = {{paramName}}; + queryParameters['{{baseName}}'] = {{paramName}}; } {{/queryParams}} From e2ce427fb11ca2267085be17906e79887a3a7151 Mon Sep 17 00:00:00 2001 From: Sean Bright Date: Thu, 17 Sep 2015 14:33:21 -0400 Subject: [PATCH 097/219] Fix NPE in JavaClientCodegen when model has no properties of its own A model that inherits from another model and does not add its own properties causes JavaClientCodegen to crash silently with an NPE. Fixes #1141 --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 317b9de258b3..b7c0f19e0fec 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1439,6 +1439,8 @@ private void addVars(CodegenModel m, Map properties, Collectio } } else { m.emptyVars = true; + m.hasVars = false; + m.hasEnums = false; } } From 65cfa735d5a6a43b56b21004ed7f181edb353a82 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Thu, 17 Sep 2015 17:39:26 -0700 Subject: [PATCH 098/219] [Obj-C] removed extraneous logs unless logging is specifically enabled in the [SWGConfiguration sharedConfig] instance --- .../resources/objc/ApiClient-body.mustache | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 6690dafc7cc8..50aae6fd6af3 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -75,7 +75,9 @@ static void (^reachabilityChangeBlock)(int); [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; } - NSLog(@"%@", message); + if ([[{{classPrefix}}Configuration sharedConfig] debug]){ + NSLog(@"%@", message); + } } #pragma mark - Cache Methods @@ -177,8 +179,9 @@ static void (^reachabilityChangeBlock)(int); +(NSNumber*) queueRequest { NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; - if([[{{classPrefix}}Configuration sharedConfig] debug]) + if([[{{classPrefix}}Configuration sharedConfig] debug]) { NSLog(@"added %@ to request queue", requestId); + } [queuedRequests addObject:requestId]; return requestId; } @@ -198,8 +201,9 @@ static void (^reachabilityChangeBlock)(int); }]; if(matchingItems.count == 1) { - if([[{{classPrefix}}Configuration sharedConfig] debug]) + if([[{{classPrefix}}Configuration sharedConfig] debug]){ NSLog(@"removing request id %@", requestId); + } [queuedRequests removeObject:requestId]; return YES; } @@ -576,15 +580,21 @@ static void (^reachabilityChangeBlock)(int); hasHeaderParams = true; } if(offlineState) { - NSLog(@"%@ cache forced", resourcePath); + if ([[{{classPrefix}}Configuration sharedConfig] debug]){ + NSLog(@"%@ cache forced", resourcePath); + } [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", resourcePath); + if ([[{{classPrefix}}Configuration sharedConfig] debug]){ + NSLog(@"%@ cache enabled", resourcePath); + } [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - NSLog(@"%@ cache disabled", resourcePath); + if ([[{{classPrefix}}Configuration sharedConfig] debug]){ + NSLog(@"%@ cache disabled", resourcePath); + } [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } From c83c564a19e8497243b3d1adf1ea4428433a450a Mon Sep 17 00:00:00 2001 From: Laurent Van der Linden Date: Fri, 18 Sep 2015 08:05:13 +0200 Subject: [PATCH 099/219] Use the baseName when referring to header parameters. --- .../src/main/resources/TypeScript-Angular/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index e459a7b419c0..f08e66333755 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -49,7 +49,7 @@ module {{package}} { {{/queryParams}} {{#headerParams}} - headerParams['{{paramName}}'] = {{paramName}}; + headerParams['{{baseName}}'] = {{paramName}}; {{/headerParams}} var httpRequestParams: any = { From 1863aca0fa5e408a6bbc39935e6f33ae2c633cd1 Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 18 Sep 2015 14:21:48 +0200 Subject: [PATCH 100/219] set retrofit as a java library Fix #1247 Fix #1248 --- README.md | 1 + bin/all-petstore.sh | 2 +- bin/java-petstore-retrofit.json | 4 + ...-petstore.sh => java-petstore-retrofit.sh} | 2 +- .../codegen/languages/JavaClientCodegen.java | 54 ++++- .../languages/RetrofitClientCodegen.java | 220 ------------------ .../auth/OAuthFlow.mustache} | 2 +- .../libraries/retrofit/ApiClient.mustache} | 56 ++--- .../libraries}/retrofit/api.mustache | 8 +- .../retrofit/auth/ApiKeyAuth.mustache} | 4 +- .../retrofit/auth/HttpBasicAuth.mustache} | 2 +- .../libraries/retrofit/auth/OAuth.mustache} | 12 +- .../retrofit/auth/OAuthOkHttpClient.mustache} | 6 +- .../libraries}/retrofit/bodyParams.mustache | 0 .../libraries}/retrofit/formParams.mustache | 0 .../libraries}/retrofit/headerParams.mustache | 0 .../Java/libraries/retrofit/model.mustache | 58 +++++ .../libraries}/retrofit/pathParams.mustache | 0 .../libraries}/retrofit/pom.mustache | 0 .../libraries}/retrofit/queryParams.mustache | 0 .../main/resources/retrofit/model.mustache | 50 ---- pom.xml | 24 +- .../petstore/{ => java}/retrofit/pom.xml | 4 +- .../java/io/swagger/client/ApiClient.java} | 58 ++--- .../java/io/swagger/client/StringUtil.java | 51 ++++ .../java/io/swagger/client/api/PetApi.java | 19 +- .../java/io/swagger/client/api/StoreApi.java | 4 +- .../java/io/swagger/client/api/UserApi.java | 4 +- .../io/swagger/client/auth/ApiKeyAuth.java} | 4 +- .../swagger/client/auth/HttpBasicAuth.java} | 2 +- .../java/io/swagger/client/auth/OAuth.java} | 12 +- .../io/swagger/client/auth/OAuthFlow.java} | 2 +- .../client/auth/OAuthOkHttpClient.java} | 6 +- .../io/swagger/client/model/ApiResponse.java | 72 ++++++ .../io/swagger/client/model/Category.java | 57 +++++ .../java/io/swagger/client/model/Order.java | 142 +++++++++++ .../java/io/swagger/client/model/Pet.java | 144 ++++++++++++ .../java/io/swagger/client/model/Tag.java | 57 +++++ .../java/io/swagger/client/model/User.java | 148 ++++++++++++ .../io/swagger/petstore/test/PetApiTest.java | 12 +- .../swagger/petstore/test/StoreApiTest.java | 12 +- .../io/swagger/petstore/test/UserApiTest.java | 4 +- .../io/swagger/client/model/ApiResponse.java | 63 ----- .../io/swagger/client/model/Category.java | 49 ---- .../java/io/swagger/client/model/Order.java | 110 --------- .../java/io/swagger/client/model/Pet.java | 112 --------- .../java/io/swagger/client/model/Tag.java | 49 ---- .../java/io/swagger/client/model/User.java | 134 ----------- 48 files changed, 905 insertions(+), 931 deletions(-) create mode 100644 bin/java-petstore-retrofit.json rename bin/{retrofit-petstore.sh => java-petstore-retrofit.sh} (78%) delete mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java rename modules/swagger-codegen/src/main/resources/{retrofit/auth/oauthflow.mustache => Java/auth/OAuthFlow.mustache} (77%) rename modules/swagger-codegen/src/main/resources/{retrofit/service.mustache => Java/libraries/retrofit/ApiClient.mustache} (81%) rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/api.mustache (63%) rename modules/swagger-codegen/src/main/resources/{retrofit/auth/apikey.mustache => Java/libraries/retrofit/auth/ApiKeyAuth.mustache} (93%) rename modules/swagger-codegen/src/main/resources/{retrofit/auth/basic.mustache => Java/libraries/retrofit/auth/HttpBasicAuth.mustache} (95%) rename modules/swagger-codegen/src/main/resources/{retrofit/auth/oauth.mustache => Java/libraries/retrofit/auth/OAuth.mustache} (91%) rename modules/swagger-codegen/src/main/resources/{retrofit/auth/oauthokclient.mustache => Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache} (94%) rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/bodyParams.mustache (100%) rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/formParams.mustache (100%) rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/headerParams.mustache (100%) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/pathParams.mustache (100%) rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/pom.mustache (100%) rename modules/swagger-codegen/src/main/resources/{ => Java/libraries}/retrofit/queryParams.mustache (100%) delete mode 100644 modules/swagger-codegen/src/main/resources/retrofit/model.mustache rename samples/client/petstore/{ => java}/retrofit/pom.xml (97%) rename samples/client/petstore/{retrofit/src/main/java/io/swagger/client/ServiceGenerator.java => java/retrofit/src/main/java/io/swagger/client/ApiClient.java} (82%) create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java rename samples/client/petstore/{ => java}/retrofit/src/main/java/io/swagger/client/api/PetApi.java (90%) rename samples/client/petstore/{ => java}/retrofit/src/main/java/io/swagger/client/api/StoreApi.java (96%) rename samples/client/petstore/{ => java}/retrofit/src/main/java/io/swagger/client/api/UserApi.java (99%) rename samples/client/petstore/{retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java => java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java} (93%) rename samples/client/petstore/{retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java => java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java} (95%) rename samples/client/petstore/{retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java => java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java} (91%) rename samples/client/petstore/{retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java => java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java} (77%) rename samples/client/petstore/{retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java => java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java} (94%) create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java rename samples/client/petstore/{ => java}/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java (92%) rename samples/client/petstore/{ => java}/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java (80%) rename samples/client/petstore/{ => java}/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java (95%) delete mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java delete mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java delete mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java delete mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java delete mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java delete mode 100644 samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java diff --git a/README.md b/README.md index f288e847b09b..2edfbfa01d14 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,7 @@ CONFIG OPTIONS - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 jersey2 - HTTP client: Jersey client 2.6 okhttp-gson - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 + retrofit - HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0) ``` Your config file for java can look like diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 5b044167e7b6..180e95590be4 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -26,6 +26,7 @@ cd $APP_DIR ./bin/java-petstore.sh ./bin/java-petstore-jersey2.sh ./bin/java-petstore-okhttp-gson.sh +./bin/java-petstore-retrofit.sh ./bin/jaxrs-petstore-server.sh ./bin/nodejs-petstore-server.sh ./bin/objc-petstore.sh @@ -34,7 +35,6 @@ cd $APP_DIR ./bin/python-petstore.sh ./bin/python3-petstore.sh ./bin/qt5-petstore.sh -./bin/retrofit-petstore.sh ./bin/ruby-petstore.sh ./bin/scala-async-petstore.sh ./bin/scala-petstore.sh diff --git a/bin/java-petstore-retrofit.json b/bin/java-petstore-retrofit.json new file mode 100644 index 000000000000..86da9d170990 --- /dev/null +++ b/bin/java-petstore-retrofit.json @@ -0,0 +1,4 @@ +{ + "library": "retrofit", + "artifactId": "swagger-petstore-retrofit" +} diff --git a/bin/retrofit-petstore.sh b/bin/java-petstore-retrofit.sh similarity index 78% rename from bin/retrofit-petstore.sh rename to bin/java-petstore-retrofit.sh index 10b82e619638..d9228fb2ecaa 100755 --- a/bin/retrofit-petstore.sh +++ b/bin/java-petstore-retrofit.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/retrofit -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l retrofit -o samples/client/petstore/retrofit" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -c bin/java-petstore-retrofit.json -o samples/client/petstore/java/retrofit" java $JAVA_OPTS -jar $executable $ags 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 1c9118189384..07baa43b824d 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 @@ -5,6 +5,7 @@ import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; @@ -84,6 +85,7 @@ public JavaClientCodegen() { supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); supportedLibraries.put("okhttp-gson", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1"); + supportedLibraries.put("retrofit", "HTTP client: OkHttp 2.4.0. JSON processing: Gson 2.3.1 (Retrofit 1.9.0)"); cliOptions.add(buildLibraryCliOption(supportedLibraries)); } @@ -155,12 +157,22 @@ public void processOpts() { final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); - supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); - supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); - supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - + + final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuthFlow.mustache", authFolder, "OAuthFlow.java")); + + if (!"retrofit".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); + supportingFiles.add(new SupportingFile("Configuration.mustache", invokerFolder, "Configuration.java")); + supportingFiles.add(new SupportingFile("JSON.mustache", invokerFolder, "JSON.java")); + supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); + supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); + } + // library-specific files if ("okhttp-gson".equals(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call @@ -169,16 +181,11 @@ public void processOpts() { supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); - // and does not require "TypeRef.mustache" + } else if ("retrofit".equals(getLibrary())) { + supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); } else { supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); } - - final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); - supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); - supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); - supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); - supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); } private void sanitizeConfig() { @@ -373,6 +380,29 @@ public Map postProcessModels(Map objs) { } return objs; } + + public Map postProcessOperations(Map objs) { + if("retrofit".equals(getLibrary())) { + Map operations = (Map) objs.get("operations"); + if (operations != null) { + List ops = (List) operations.get("operation"); + for (CodegenOperation operation : ops) { + if (operation.hasConsumes == Boolean.TRUE) { + Map firstType = operation.consumes.get(0); + if (firstType != null) { + if ("multipart/form-data".equals(firstType.get("mediaType"))) { + operation.isMultipart = Boolean.TRUE; + } + } + } + if (operation.returnType == null) { + operation.returnType = "Void"; + } + } + } + } + return objs; + } private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java deleted file mode 100644 index 2acacd880267..000000000000 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RetrofitClientCodegen.java +++ /dev/null @@ -1,220 +0,0 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenConstants; -import io.swagger.codegen.CodegenOperation; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; - -import java.io.File; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Map; - -import org.apache.commons.lang.StringUtils; - -public class RetrofitClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-java-client"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; - - public RetrofitClientCodegen() { - super(); - outputFolder = "generated-code/java"; - modelTemplateFiles.put("model.mustache", ".java"); - apiTemplateFiles.put("api.mustache", ".java"); - templateDir = "retrofit"; - apiPackage = "io.swagger.client.api"; - modelPackage = "io.swagger.client.model"; - - reservedWords = new HashSet( - Arrays.asList( - "abstract", "continue", "for", "new", "switch", "assert", - "default", "if", "package", "synchronized", "boolean", "do", "goto", "private", - "this", "break", "double", "implements", "protected", "throw", "byte", "else", - "import", "public", "throws", "case", "enum", "instanceof", "return", "transient", - "catch", "extends", "int", "short", "try", "char", "final", "interface", "static", - "void", "class", "finally", "long", "strictfp", "volatile", "const", "float", - "native", "super", "while") - ); - - additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); - additionalProperties.put(CodegenConstants.GROUP_ID, groupId); - additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); - additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("service.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ServiceGenerator.java")); - supportingFiles.add(new SupportingFile("auth/basic.mustache", - (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "BasicAuthorization.java")); - supportingFiles.add(new SupportingFile("auth/apikey.mustache", - (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "ApiKeyAuthorization.java")); - supportingFiles.add(new SupportingFile("auth/oauth.mustache", - (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "OauthAuthorization.java")); - supportingFiles.add(new SupportingFile("auth/oauthflow.mustache", - (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "OauthFlow.java")); - supportingFiles.add(new SupportingFile("auth/oauthokclient.mustache", - (sourceFolder + File.separator + invokerPackage + File.separator + "auth").replace(".", java.io.File.separator), "OauthOkHttpClient.java")); - - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float", - "Object") - ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); - } - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "retrofit"; - } - - public String getHelp() { - return "Generates a Retrofit client library."; - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, do nothing - if (name.matches("^[A-Z_]*$")) { - return name; - } - - // camelize (lower first character) the variable name - // pet_id => petId - name = camelize(name, true); - - // for reserved word or word starting with number, append _ - if (reservedWords.contains(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if (reservedWords.contains(name)) { - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // should be the same as the model name - return toModelName(name); - } - - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + ""; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return toModelName(type); - } - } else { - type = swaggerType; - } - return toModelName(type); - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (reservedWords.contains(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - } - - return camelize(operationId, true); - } - - public Map postProcessOperations(Map objs) { - Map operations = (Map) objs.get("operations"); - if (operations != null) { - List ops = (List) operations.get("operation"); - for (CodegenOperation operation : ops) { - if (operation.hasConsumes == Boolean.TRUE) { - Map firstType = operation.consumes.get(0); - if (firstType != null) { - if ("multipart/form-data".equals(firstType.get("mediaType"))) { - operation.isMultipart = Boolean.TRUE; - } - } - } - if (operation.returnType == null) { - operation.returnType = "Void"; - } - } - } - return objs; - } -} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache similarity index 77% rename from modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache rename to modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache index 6d18cb3aa848..7ab35f6d890a 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthflow.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuthFlow.mustache @@ -1,5 +1,5 @@ package {{invokerPackage}}.auth; -public enum OauthFlow { +public enum OAuthFlow { accessCode, implicit, password, application } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache similarity index 81% rename from modules/swagger-codegen/src/main/resources/retrofit/service.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index aa7b73f21474..4046f9f107ca 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/service.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -25,24 +25,24 @@ import com.google.gson.JsonParseException; import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; -import {{invokerPackage}}.auth.BasicAuthorization; -import {{invokerPackage}}.auth.ApiKeyAuthorization; -import {{invokerPackage}}.auth.OauthAuthorization; -import {{invokerPackage}}.auth.OauthFlow; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; +import {{invokerPackage}}.auth.OAuthFlow; -public class ServiceGenerator { +public class ApiClient { private Map apiAuthorizations; private OkHttpClient okClient; private RestAdapter.Builder adapterBuilder; - public ServiceGenerator() { + public ApiClient() { apiAuthorizations = new LinkedHashMap(); createDefaultAdapter(); } - public ServiceGenerator(String[] authNames) { + public ApiClient(String[] authNames) { this(); okClient = new OkHttpClient(); adapterBuilder.setClient(new OkClient(okClient)); @@ -52,9 +52,9 @@ public class ServiceGenerator { } Interceptor auth;{{#authMethods}} if (authName == "{{name}}") { {{#isBasic}} - auth = new BasicAuthorization();{{/isBasic}}{{#isApiKey}} - auth = new ApiKeyAuthorization({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} - auth = new OauthAuthorization(OauthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{^-first}}, {{/-first}}{{this}}{{/scopes}}");{{/isOAuth}} + auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} + auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} + auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{^-first}}, {{/-first}}{{this}}{{/scopes}}");{{/isOAuth}} } else {{/authMethods}}{ throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -67,7 +67,7 @@ public class ServiceGenerator { * Basic constructor for single auth name * @param authName */ - public ServiceGenerator(String authName) { + public ApiClient(String authName) { this(new String[]{authName}); } @@ -76,7 +76,7 @@ public class ServiceGenerator { * @param authName * @param apiKey */ - public ServiceGenerator(String authName, String apiKey) { + public ApiClient(String authName, String apiKey) { this(authName); this.setApiKey(apiKey); } @@ -87,7 +87,7 @@ public class ServiceGenerator { * @param username * @param password */ - public ServiceGenerator(String authName, String username, String password) { + public ApiClient(String authName, String username, String password) { this(authName); this.setCredentials(username, password); } @@ -100,7 +100,7 @@ public class ServiceGenerator { * @param username * @param password */ - public ServiceGenerator(String authName, String clientId, String secret, String username, String password) { + public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); this.getTokenEndPoint() .setClientId(clientId) @@ -131,8 +131,8 @@ public class ServiceGenerator { */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof ApiKeyAuthorization) { - ApiKeyAuthorization keyAuth = (ApiKeyAuthorization) apiAuthorization; + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; keyAuth.setApiKey(apiKey); return; } @@ -146,13 +146,13 @@ public class ServiceGenerator { */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof BasicAuthorization) { - BasicAuthorization basicAuth = (BasicAuthorization) apiAuthorization; + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; basicAuth.setCredentials(username, password); return; } - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); return; } @@ -165,8 +165,8 @@ public class ServiceGenerator { */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; return oauth.getTokenRequestBuilder(); } } @@ -179,8 +179,8 @@ public class ServiceGenerator { */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; return oauth.getAuthenticationRequestBuilder(); } } @@ -193,8 +193,8 @@ public class ServiceGenerator { */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; oauth.setAccessToken(accessToken); return; } @@ -209,8 +209,8 @@ public class ServiceGenerator { */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; oauth.getTokenRequestBuilder() .setClientId(clientId) .setClientSecret(clientSecret) diff --git a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache similarity index 63% rename from modules/swagger-codegen/src/main/resources/retrofit/api.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index db4a997196fd..7f244c423bbf 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -24,7 +24,7 @@ public interface {{classname}} { {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} + {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} /** @@ -34,11 +34,11 @@ public interface {{classname}} { {{/allParams}} * @param cb callback method * @return void */ - {{#formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} + {{#libraries/retrofit/formParams}}{{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/libraries/retrofit/formParams}} @{{httpMethod}}("{{path}}") void {{nickname}}( - {{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb + {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb ); {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache similarity index 93% rename from modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache index 9f5eaef7fdcb..fec45262e930 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/auth/apikey.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/ApiKeyAuth.mustache @@ -8,13 +8,13 @@ import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; -public class ApiKeyAuthorization implements Interceptor { +public class ApiKeyAuth implements Interceptor { private final String location; private final String paramName; private String apiKey; - public ApiKeyAuthorization(String location, String paramName) { + public ApiKeyAuth(String location, String paramName) { this.location = location; this.paramName = paramName; } diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/HttpBasicAuth.mustache similarity index 95% rename from modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/HttpBasicAuth.mustache index f1c88fe90530..394592f64d9c 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/auth/basic.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/HttpBasicAuth.mustache @@ -7,7 +7,7 @@ import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; -public class BasicAuthorization implements Interceptor { +public class HttpBasicAuth implements Interceptor { private String username; private String password; diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache similarity index 91% rename from modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache index a1a2ecabfaaf..e6179d6c6902 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuth.mustache @@ -21,7 +21,7 @@ import com.squareup.okhttp.Request; import com.squareup.okhttp.Request.Builder; import com.squareup.okhttp.Response; -public class OauthAuthorization implements Interceptor { +public class OAuth implements Interceptor { private volatile String accessToken; private OAuthClient oauthClient; @@ -29,22 +29,22 @@ public class OauthAuthorization implements Interceptor { private TokenRequestBuilder tokenRequestBuilder; private AuthenticationRequestBuilder authenticationRequestBuilder; - public OauthAuthorization( OkHttpClient client, TokenRequestBuilder requestBuilder ) { - this.oauthClient = new OAuthClient(new OauthOkHttpClient(client)); + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); this.tokenRequestBuilder = requestBuilder; } - public OauthAuthorization(TokenRequestBuilder requestBuilder ) { + public OAuth(TokenRequestBuilder requestBuilder ) { this(new OkHttpClient(), requestBuilder); } - public OauthAuthorization(OauthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); setFlow(flow); authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); } - public void setFlow(OauthFlow flow) { + public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: diff --git a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache similarity index 94% rename from modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache index 61f651f76969..ea195f7df04b 100644 --- a/modules/swagger-codegen/src/main/resources/retrofit/auth/oauthokclient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/auth/OAuthOkHttpClient.mustache @@ -18,15 +18,15 @@ import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; -public class OauthOkHttpClient implements HttpClient { +public class OAuthOkHttpClient implements HttpClient { private OkHttpClient client; - public OauthOkHttpClient() { + public OAuthOkHttpClient() { this.client = new OkHttpClient(); } - public OauthOkHttpClient(OkHttpClient client) { + public OAuthOkHttpClient(OkHttpClient client) { this.client = client; } diff --git a/modules/swagger-codegen/src/main/resources/retrofit/bodyParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/retrofit/bodyParams.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/bodyParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/retrofit/formParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/retrofit/formParams.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/formParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/retrofit/headerParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/retrofit/headerParams.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/headerParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache new file mode 100644 index 000000000000..0987aa68f34e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/model.mustache @@ -0,0 +1,58 @@ +package {{package}}; + +import {{invokerPackage}}.StringUtil; +{{#imports}}import {{import}}; +{{/imports}} + +import com.google.gson.annotations.SerializedName; + +{{#serializableModel}} +import java.io.Serializable;{{/serializableModel}} + +import io.swagger.annotations.*; + +{{#models}} + +{{#model}}{{#description}} +/** + * {{description}} + **/{{/description}} +@ApiModel(description = "{{{description}}}") +public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#serializableModel}}implements Serializable{{/serializableModel}} { + {{#vars}}{{#isEnum}} + +{{>libraries/okhttp-gson/enumClass}}{{/isEnum}}{{#items.isEnum}}{{#items}} + +{{>libraries/okhttp-gson/enumClass}}{{/items}}{{/items.isEnum}} + @SerializedName("{{baseName}}") + private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}}; + {{/vars}} + + {{#vars}} + /**{{#description}} + * {{{description}}}{{/description}}{{#minimum}} + * minimum: {{minimum}}{{/minimum}}{{#maximum}} + * maximum: {{maximum}}{{/maximum}} + **/ + @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") + public {{{datatypeWithEnum}}} {{getter}}() { + return {{name}}; + } + public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + this.{{name}} = {{name}}; + } + + {{/vars}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}}sb.append(" ").append(StringUtil.toIndentedString(super.toString())).append("\n");{{/parent}} + {{#vars}}sb.append(" {{name}}: ").append(StringUtil.toIndentedString({{name}})).append("\n"); + {{/vars}}sb.append("}"); + return sb.toString(); + } +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pathParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/retrofit/pathParams.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pathParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/retrofit/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/retrofit/pom.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/pom.mustache diff --git a/modules/swagger-codegen/src/main/resources/retrofit/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/retrofit/queryParams.mustache rename to modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache diff --git a/modules/swagger-codegen/src/main/resources/retrofit/model.mustache b/modules/swagger-codegen/src/main/resources/retrofit/model.mustache deleted file mode 100644 index 85213ed4c957..000000000000 --- a/modules/swagger-codegen/src/main/resources/retrofit/model.mustache +++ /dev/null @@ -1,50 +0,0 @@ -package {{package}}; - -{{#imports}}import {{import}}; -{{/imports}} - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; -{{#models}} - -{{#model}}{{#description}} -/** - * {{description}} - **/{{/description}} -@ApiModel(description = "{{{description}}}") -public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} { - {{#vars}}{{#isEnum}} - public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#values}} {{.}}, {{/values}}{{/allowableValues}} - };{{/isEnum}} - - /**{{#description}} - * {{{description}}}{{/description}}{{#minimum}} - * minimum: {{minimum}}{{/minimum}}{{#maximum}} - * maximum: {{maximum}}{{/maximum}} - **/ - @ApiModelProperty({{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") - @SerializedName("{{baseName}}"){{#isEnum}} - private {{{datatypeWithEnum}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{^isEnum}} - private {{{datatype}}} {{name}} = {{{defaultValue}}};{{/isEnum}}{{/vars}} - - {{#vars}} - public {{{datatypeWithEnum}}} {{getter}}() { - return {{name}}; - } - public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - this.{{name}} = {{name}}; - } - {{/vars}} - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class {{classname}} {\n"); - {{#parent}}sb.append(" " + super.toString()).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append({{name}}).append("\n"); - {{/vars}}sb.append("}\n"); - return sb.toString(); - } -} -{{/model}} -{{/models}} diff --git a/pom.xml b/pom.xml index 883d22257c8b..f14e7b825cba 100644 --- a/pom.xml +++ b/pom.xml @@ -340,6 +340,18 @@ samples/client/petstore/java/okhttp-gson + + java-client-retrofit + + + env + java + + + + samples/client/petstore/java/retrofit + + scala-client @@ -388,18 +400,6 @@ samples/client/petstore/ruby - - retrofit-client - - - env - java - - - - samples/client/petstore/retrofit - - spring-mvc diff --git a/samples/client/petstore/retrofit/pom.xml b/samples/client/petstore/java/retrofit/pom.xml similarity index 97% rename from samples/client/petstore/retrofit/pom.xml rename to samples/client/petstore/java/retrofit/pom.xml index bcbfdbf797db..6e2a7b76ac23 100644 --- a/samples/client/petstore/retrofit/pom.xml +++ b/samples/client/petstore/java/retrofit/pom.xml @@ -2,9 +2,9 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4.0.0 io.swagger - swagger-java-client + swagger-petstore-retrofit jar - swagger-java-client + swagger-petstore-retrofit 1.0.0 scm:git:git@github.com:swagger-api/swagger-mustache.git diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java similarity index 82% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java index 244b9f50f843..83ad22c4de8e 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/ServiceGenerator.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/ApiClient.java @@ -25,24 +25,24 @@ import com.squareup.okhttp.Interceptor; import com.squareup.okhttp.OkHttpClient; -import io.swagger.client.auth.BasicAuthorization; -import io.swagger.client.auth.ApiKeyAuthorization; -import io.swagger.client.auth.OauthAuthorization; -import io.swagger.client.auth.OauthFlow; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; +import io.swagger.client.auth.OAuthFlow; -public class ServiceGenerator { +public class ApiClient { private Map apiAuthorizations; private OkHttpClient okClient; private RestAdapter.Builder adapterBuilder; - public ServiceGenerator() { + public ApiClient() { apiAuthorizations = new LinkedHashMap(); createDefaultAdapter(); } - public ServiceGenerator(String[] authNames) { + public ApiClient(String[] authNames) { this(); okClient = new OkHttpClient(); adapterBuilder.setClient(new OkClient(okClient)); @@ -51,11 +51,11 @@ public ServiceGenerator(String[] authNames) { throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); } Interceptor auth; - if (authName == "petstore_auth") { - auth = new OauthAuthorization(OauthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); - } else if (authName == "api_key") { - auth = new ApiKeyAuthorization("header", "api_key"); + auth = new ApiKeyAuth("header", "api_key"); + } else + if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -68,7 +68,7 @@ public ServiceGenerator(String[] authNames) { * Basic constructor for single auth name * @param authName */ - public ServiceGenerator(String authName) { + public ApiClient(String authName) { this(new String[]{authName}); } @@ -77,7 +77,7 @@ public ServiceGenerator(String authName) { * @param authName * @param apiKey */ - public ServiceGenerator(String authName, String apiKey) { + public ApiClient(String authName, String apiKey) { this(authName); this.setApiKey(apiKey); } @@ -88,7 +88,7 @@ public ServiceGenerator(String authName, String apiKey) { * @param username * @param password */ - public ServiceGenerator(String authName, String username, String password) { + public ApiClient(String authName, String username, String password) { this(authName); this.setCredentials(username, password); } @@ -101,7 +101,7 @@ public ServiceGenerator(String authName, String username, String password) { * @param username * @param password */ - public ServiceGenerator(String authName, String clientId, String secret, String username, String password) { + public ApiClient(String authName, String clientId, String secret, String username, String password) { this(authName); this.getTokenEndPoint() .setClientId(clientId) @@ -132,8 +132,8 @@ public S createService(Class serviceClass) { */ private void setApiKey(String apiKey) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof ApiKeyAuthorization) { - ApiKeyAuthorization keyAuth = (ApiKeyAuthorization) apiAuthorization; + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; keyAuth.setApiKey(apiKey); return; } @@ -147,13 +147,13 @@ private void setApiKey(String apiKey) { */ private void setCredentials(String username, String password) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof BasicAuthorization) { - BasicAuthorization basicAuth = (BasicAuthorization) apiAuthorization; + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; basicAuth.setCredentials(username, password); return; } - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); return; } @@ -166,8 +166,8 @@ private void setCredentials(String username, String password) { */ public TokenRequestBuilder getTokenEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; return oauth.getTokenRequestBuilder(); } } @@ -180,8 +180,8 @@ public TokenRequestBuilder getTokenEndPoint() { */ public AuthenticationRequestBuilder getAuthorizationEndPoint() { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; return oauth.getAuthenticationRequestBuilder(); } } @@ -194,8 +194,8 @@ public AuthenticationRequestBuilder getAuthorizationEndPoint() { */ public void setAccessToken(String accessToken) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; oauth.setAccessToken(accessToken); return; } @@ -210,8 +210,8 @@ public void setAccessToken(String accessToken) { */ public void configureAuthorizationFlow(String clientId, String clientSecret, String redirectURI) { for(Interceptor apiAuthorization : apiAuthorizations.values()) { - if (apiAuthorization instanceof OauthAuthorization) { - OauthAuthorization oauth = (OauthAuthorization) apiAuthorization; + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; oauth.getTokenRequestBuilder() .setClientId(clientId) .setClientSecret(clientSecret) diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java new file mode 100644 index 000000000000..27a06a7cfc2d --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -0,0 +1,51 @@ +package io.swagger.client; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-18T14:07:38.326+02:00") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) return true; + if (value != null && value.equalsIgnoreCase(str)) return true; + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

+ * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

+ * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) return ""; + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + public static String toIndentedString(Object o) { + if (o == null) return "null"; + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java similarity index 90% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 5efddc75dc40..5a3f5788e3f7 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -9,7 +9,6 @@ import io.swagger.client.model.Pet; import java.io.File; -import io.swagger.client.model.ApiResponse; public interface PetApi { @@ -120,8 +119,8 @@ void findPetsByTags( /** * Find pet by ID * Sync method - * Returns a single pet - * @param petId ID of pet to return + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched * @return Pet */ @@ -133,7 +132,7 @@ Pet getPetById( /** * Find pet by ID * Async method - * @param petId ID of pet to return + * @param petId ID of pet that needs to be fetched * @param cb callback method * @return void */ @@ -156,7 +155,7 @@ void getPetById( @FormUrlEncoded @POST("/pet/{petId}") Void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status + @Path("petId") String petId, @Field("name") String name, @Field("status") String status ); /** @@ -169,10 +168,9 @@ Void updatePetWithForm( * @return void */ - @FormUrlEncoded @POST("/pet/{petId}") void updatePetWithForm( - @Path("petId") Long petId, @Field("name") String name, @Field("status") String status, Callback cb + @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb ); /** @@ -210,12 +208,12 @@ void deletePet( * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @return ApiResponse + * @return Void */ @Multipart @POST("/pet/{petId}/uploadImage") - ApiResponse uploadFile( + Void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file ); @@ -229,10 +227,9 @@ ApiResponse uploadFile( * @return void */ - @Multipart @POST("/pet/{petId}/uploadImage") void uploadFile( - @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb + @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb ); } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java similarity index 96% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index 9fecd5c98d0e..1c0a8291d020 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -71,7 +71,7 @@ void placeOrder( @GET("/store/order/{orderId}") Order getOrderById( - @Path("orderId") Long orderId + @Path("orderId") String orderId ); /** @@ -84,7 +84,7 @@ Order getOrderById( @GET("/store/order/{orderId}") void getOrderById( - @Path("orderId") Long orderId, Callback cb + @Path("orderId") String orderId, Callback cb ); /** diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java similarity index 99% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index c74265f53fd8..162222bc0f1b 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -145,7 +145,7 @@ void logoutUser( * Get user by user name * Sync method * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ @@ -157,7 +157,7 @@ User getUserByName( /** * Get user by user name * Async method - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @param cb callback method * @return void */ diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java similarity index 93% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index a1292c1d7f14..59d012387962 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuthorization.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -8,13 +8,13 @@ import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; -public class ApiKeyAuthorization implements Interceptor { +public class ApiKeyAuth implements Interceptor { private final String location; private final String paramName; private String apiKey; - public ApiKeyAuthorization(String location, String paramName) { + public ApiKeyAuth(String location, String paramName) { this.location = location; this.paramName = paramName; } diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java similarity index 95% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 80903d49a341..cb7c617767b9 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/BasicAuthorization.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -7,7 +7,7 @@ import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; -public class BasicAuthorization implements Interceptor { +public class HttpBasicAuth implements Interceptor { private String username; private String password; diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java similarity index 91% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java index 01c2d3e09165..f7e488e0499e 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthAuthorization.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuth.java @@ -21,7 +21,7 @@ import com.squareup.okhttp.Request.Builder; import com.squareup.okhttp.Response; -public class OauthAuthorization implements Interceptor { +public class OAuth implements Interceptor { private volatile String accessToken; private OAuthClient oauthClient; @@ -29,22 +29,22 @@ public class OauthAuthorization implements Interceptor { private TokenRequestBuilder tokenRequestBuilder; private AuthenticationRequestBuilder authenticationRequestBuilder; - public OauthAuthorization( OkHttpClient client, TokenRequestBuilder requestBuilder ) { - this.oauthClient = new OAuthClient(new OauthOkHttpClient(client)); + public OAuth( OkHttpClient client, TokenRequestBuilder requestBuilder ) { + this.oauthClient = new OAuthClient(new OAuthOkHttpClient(client)); this.tokenRequestBuilder = requestBuilder; } - public OauthAuthorization(TokenRequestBuilder requestBuilder ) { + public OAuth(TokenRequestBuilder requestBuilder ) { this(new OkHttpClient(), requestBuilder); } - public OauthAuthorization(OauthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { this(OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); setFlow(flow); authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); } - public void setFlow(OauthFlow flow) { + public void setFlow(OAuthFlow flow) { switch(flow) { case accessCode: case implicit: diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java similarity index 77% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java index ba0a8f39f35c..597ec99b48b7 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthFlow.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthFlow.java @@ -1,5 +1,5 @@ package io.swagger.client.auth; -public enum OauthFlow { +public enum OAuthFlow { accessCode, implicit, password, application } \ No newline at end of file diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java similarity index 94% rename from samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java rename to samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java index a66bec0b1584..c872901ba246 100644 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/auth/OauthOkHttpClient.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/auth/OAuthOkHttpClient.java @@ -18,15 +18,15 @@ import com.squareup.okhttp.Response; -public class OauthOkHttpClient implements HttpClient { +public class OAuthOkHttpClient implements HttpClient { private OkHttpClient client; - public OauthOkHttpClient() { + public OAuthOkHttpClient() { this.client = new OkHttpClient(); } - public OauthOkHttpClient(OkHttpClient client) { + public OAuthOkHttpClient(OkHttpClient client) { this.client = client; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java new file mode 100644 index 000000000000..777de9a34e3e --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java @@ -0,0 +1,72 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class ApiResponse { + + @SerializedName("code") + private Integer code = null; + + @SerializedName("type") + private String type = null; + + @SerializedName("message") + private String message = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + @ApiModelProperty(value = "") + 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(StringUtil.toIndentedString(code)).append("\n"); + sb.append(" type: ").append(StringUtil.toIndentedString(type)).append("\n"); + sb.append(" message: ").append(StringUtil.toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java new file mode 100644 index 000000000000..0a7023ac7a52 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Category.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Category { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java new file mode 100644 index 000000000000..df8e77b6fb35 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -0,0 +1,142 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import java.util.Date; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Order { + + @SerializedName("id") + private Long id = null; + + @SerializedName("petId") + private Long petId = null; + + @SerializedName("quantity") + private Integer quantity = null; + + @SerializedName("shipDate") + private Date shipDate = null; + + +public enum StatusEnum { + @SerializedName("placed") + PLACED("placed"), + + @SerializedName("approved") + APPROVED("approved"), + + @SerializedName("delivered") + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + @SerializedName("complete") + private Boolean complete = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Long getPetId() { + return petId; + } + public void setPetId(Long petId) { + this.petId = petId; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getQuantity() { + return quantity; + } + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Date getShipDate() { + return shipDate; + } + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + + /** + * Order Status + **/ + @ApiModelProperty(value = "Order Status") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Boolean getComplete() { + return complete; + } + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(StringUtil.toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(StringUtil.toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(StringUtil.toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(StringUtil.toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java new file mode 100644 index 000000000000..9ab5457e26ac --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -0,0 +1,144 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; +import io.swagger.client.model.Category; +import java.util.*; +import io.swagger.client.model.Tag; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Pet { + + @SerializedName("id") + private Long id = null; + + @SerializedName("category") + private Category category = null; + + @SerializedName("name") + private String name = null; + + @SerializedName("photoUrls") + private List photoUrls = new ArrayList(); + + @SerializedName("tags") + private List tags = new ArrayList(); + + +public enum StatusEnum { + @SerializedName("available") + AVAILABLE("available"), + + @SerializedName("pending") + PENDING("pending"), + + @SerializedName("sold") + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @Override + public String toString() { + return value; + } +} + + @SerializedName("status") + private StatusEnum status = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public Category getCategory() { + return category; + } + public void setCategory(Category category) { + this.category = category; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + /** + **/ + @ApiModelProperty(required = true, value = "") + public List getPhotoUrls() { + return photoUrls; + } + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + /** + **/ + @ApiModelProperty(value = "") + public List getTags() { + return tags; + } + public void setTags(List tags) { + this.tags = tags; + } + + + /** + * pet status in the store + **/ + @ApiModelProperty(value = "pet status in the store") + public StatusEnum getStatus() { + return status; + } + public void setStatus(StatusEnum status) { + this.status = status; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" category: ").append(StringUtil.toIndentedString(category)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(StringUtil.toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(StringUtil.toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(StringUtil.toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java new file mode 100644 index 000000000000..9935b744f2dd --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Tag.java @@ -0,0 +1,57 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class Tag { + + @SerializedName("id") + private Long id = null; + + @SerializedName("name") + private String name = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" name: ").append(StringUtil.toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java new file mode 100644 index 000000000000..cba6abef8dd4 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/User.java @@ -0,0 +1,148 @@ +package io.swagger.client.model; + +import io.swagger.client.StringUtil; + +import com.google.gson.annotations.SerializedName; + + + +import io.swagger.annotations.*; + + + +@ApiModel(description = "") +public class User { + + @SerializedName("id") + private Long id = null; + + @SerializedName("username") + private String username = null; + + @SerializedName("firstName") + private String firstName = null; + + @SerializedName("lastName") + private String lastName = null; + + @SerializedName("email") + private String email = null; + + @SerializedName("password") + private String password = null; + + @SerializedName("phone") + private String phone = null; + + @SerializedName("userStatus") + private Integer userStatus = null; + + + + /** + **/ + @ApiModelProperty(value = "") + public Long getId() { + return id; + } + public void setId(Long id) { + this.id = id; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getUsername() { + return username; + } + public void setUsername(String username) { + this.username = username; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getFirstName() { + return firstName; + } + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getLastName() { + return lastName; + } + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getEmail() { + return email; + } + public void setEmail(String email) { + this.email = email; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPassword() { + return password; + } + public void setPassword(String password) { + this.password = password; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getPhone() { + return phone; + } + public void setPhone(String phone) { + this.phone = phone; + } + + + /** + * User Status + **/ + @ApiModelProperty(value = "User Status") + public Integer getUserStatus() { + return userStatus; + } + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(StringUtil.toIndentedString(id)).append("\n"); + sb.append(" username: ").append(StringUtil.toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(StringUtil.toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(StringUtil.toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(StringUtil.toIndentedString(email)).append("\n"); + sb.append(" password: ").append(StringUtil.toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(StringUtil.toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(StringUtil.toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } +} diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java similarity index 92% rename from samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java rename to samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java index d015095b5c95..ec93912b1f66 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,6 +1,6 @@ package io.swagger.petstore.test; -import io.swagger.client.ServiceGenerator; +import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -22,7 +22,7 @@ public class PetApiTest { @Before public void setup() { - api = new ServiceGenerator().createService(PetApi.class); + api = new ApiClient().createService(PetApi.class); } @Test @@ -55,7 +55,7 @@ public void testUpdatePet() throws Exception { public void testFindPetsByStatus() throws Exception { Pet pet = createRandomPet(); pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.available); + pet.setStatus(Pet.StatusEnum.AVAILABLE); api.updatePet(pet); @@ -77,7 +77,7 @@ public void testFindPetsByStatus() throws Exception { public void testFindPetsByTags() throws Exception { Pet pet = createRandomPet(); pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.available); + pet.setStatus(Pet.StatusEnum.AVAILABLE); List tags = new ArrayList(); Tag tag1 = new Tag(); @@ -108,7 +108,7 @@ public void testUpdatePetWithForm() throws Exception { Pet fetched = api.getPetById(pet.getId()); - api.updatePetWithForm(fetched.getId(), "furt", null); + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); Pet updated = api.getPetById(fetched.getId()); assertEquals(updated.getName(), "furt"); @@ -152,7 +152,7 @@ private Pet createRandomPet() { category.setName("really-happy"); pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.available); + pet.setStatus(Pet.StatusEnum.AVAILABLE); List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); pet.setPhotoUrls(photos); diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java similarity index 80% rename from samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java rename to samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 629a24cc7755..95079f71afa0 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,6 +1,6 @@ package io.swagger.petstore.test; -import io.swagger.client.ServiceGenerator; +import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -16,7 +16,7 @@ public class StoreApiTest { @Before public void setup() { - api = new ServiceGenerator().createService(StoreApi.class); + api = new ApiClient().createService(StoreApi.class); } @Test @@ -30,7 +30,7 @@ public void testPlaceOrder() throws Exception { Order order = createOrder(); api.placeOrder(order); - Order fetched = api.getOrderById(order.getId()); + Order fetched = api.getOrderById(String.valueOf(order.getId())); assertEquals(order.getId(), fetched.getId()); assertEquals(order.getPetId(), fetched.getPetId()); assertEquals(order.getQuantity(), fetched.getQuantity()); @@ -41,13 +41,13 @@ public void testDeleteOrder() throws Exception { Order order = createOrder(); api.placeOrder(order); - Order fetched = api.getOrderById(order.getId()); + Order fetched = api.getOrderById(String.valueOf(order.getId())); assertEquals(fetched.getId(), order.getId()); api.deleteOrder(String.valueOf(order.getId())); try { - api.getOrderById(order.getId()); + api.getOrderById(String.valueOf(order.getId())); // fail("expected an error"); } catch (RetrofitError e) { // ok @@ -60,7 +60,7 @@ private Order createOrder() { order.setPetId(new Long(200)); order.setQuantity(new Integer(13)); order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.placed); + order.setStatus(Order.StatusEnum.PLACED); order.setComplete(true); return order; diff --git a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java similarity index 95% rename from samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java rename to samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java index 45a5f1160e10..373218465f0f 100644 --- a/samples/client/petstore/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/retrofit/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,6 +1,6 @@ package io.swagger.petstore.test; -import io.swagger.client.ServiceGenerator; +import io.swagger.client.ApiClient; import io.swagger.client.api.*; import io.swagger.client.model.*; @@ -15,7 +15,7 @@ public class UserApiTest { @Before public void setup() { - api = new ServiceGenerator().createService(UserApi.class); + api = new ApiClient().createService(UserApi.class); } @Test diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java deleted file mode 100644 index a929a54dc81f..000000000000 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/ApiResponse.java +++ /dev/null @@ -1,63 +0,0 @@ -package io.swagger.client.model; - - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - -@ApiModel(description = "") -public class ApiResponse { - - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("code") - private Integer code = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("type") - private String type = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("message") - private String message = null; - - - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - 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/retrofit/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java deleted file mode 100644 index 7f89bcf57a07..000000000000 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Category.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.swagger.client.model; - - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - -@ApiModel(description = "") -public class Category { - - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("id") - private Long id = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("name") - private String name = null; - - - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Category {\n"); - - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java deleted file mode 100644 index 6be69df18c95..000000000000 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Order.java +++ /dev/null @@ -1,110 +0,0 @@ -package io.swagger.client.model; - -import java.util.Date; - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - -@ApiModel(description = "") -public class Order { - - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("id") - private Long id = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("petId") - private Long petId = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("quantity") - private Integer quantity = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("shipDate") - private Date shipDate = null; - public enum StatusEnum { - placed, approved, delivered, - }; - - /** - * Order Status - **/ - @ApiModelProperty(value = "Order Status") - @SerializedName("status") - private StatusEnum status = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("complete") - private Boolean complete = null; - - - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public Long getPetId() { - return petId; - } - public void setPetId(Long petId) { - this.petId = petId; - } - - public Integer getQuantity() { - return quantity; - } - public void setQuantity(Integer quantity) { - this.quantity = quantity; - } - - public Date getShipDate() { - return shipDate; - } - public void setShipDate(Date shipDate) { - this.shipDate = shipDate; - } - - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - public Boolean getComplete() { - return complete; - } - public void setComplete(Boolean complete) { - this.complete = complete; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Order {\n"); - - sb.append(" id: ").append(id).append("\n"); - sb.append(" petId: ").append(petId).append("\n"); - sb.append(" quantity: ").append(quantity).append("\n"); - sb.append(" shipDate: ").append(shipDate).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append(" complete: ").append(complete).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java deleted file mode 100644 index f74264708e35..000000000000 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ /dev/null @@ -1,112 +0,0 @@ -package io.swagger.client.model; - -import io.swagger.client.model.Category; -import java.util.*; -import io.swagger.client.model.Tag; - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - -@ApiModel(description = "") -public class Pet { - - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("id") - private Long id = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("category") - private Category category = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - @SerializedName("name") - private String name = null; - - /** - **/ - @ApiModelProperty(required = true, value = "") - @SerializedName("photoUrls") - private List photoUrls = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("tags") - private List tags = null; - public enum StatusEnum { - available, pending, sold, - }; - - /** - * pet status in the store - **/ - @ApiModelProperty(value = "pet status in the store") - @SerializedName("status") - private StatusEnum status = null; - - - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public Category getCategory() { - return category; - } - public void setCategory(Category category) { - this.category = category; - } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - public List getPhotoUrls() { - return photoUrls; - } - public void setPhotoUrls(List photoUrls) { - this.photoUrls = photoUrls; - } - - public List getTags() { - return tags; - } - public void setTags(List tags) { - this.tags = tags; - } - - public StatusEnum getStatus() { - return status; - } - public void setStatus(StatusEnum status) { - this.status = status; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Pet {\n"); - - sb.append(" id: ").append(id).append("\n"); - sb.append(" category: ").append(category).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append(" photoUrls: ").append(photoUrls).append("\n"); - sb.append(" tags: ").append(tags).append("\n"); - sb.append(" status: ").append(status).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java deleted file mode 100644 index c1a317bc45c0..000000000000 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/Tag.java +++ /dev/null @@ -1,49 +0,0 @@ -package io.swagger.client.model; - - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - -@ApiModel(description = "") -public class Tag { - - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("id") - private Long id = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("name") - private String name = null; - - - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class Tag {\n"); - - sb.append(" id: ").append(id).append("\n"); - sb.append(" name: ").append(name).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} diff --git a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java deleted file mode 100644 index 3beca5c5e867..000000000000 --- a/samples/client/petstore/retrofit/src/main/java/io/swagger/client/model/User.java +++ /dev/null @@ -1,134 +0,0 @@ -package io.swagger.client.model; - - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - -@ApiModel(description = "") -public class User { - - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("id") - private Long id = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("username") - private String username = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("firstName") - private String firstName = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("lastName") - private String lastName = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("email") - private String email = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("password") - private String password = null; - - /** - **/ - @ApiModelProperty(value = "") - @SerializedName("phone") - private String phone = null; - - /** - * User Status - **/ - @ApiModelProperty(value = "User Status") - @SerializedName("userStatus") - private Integer userStatus = null; - - - public Long getId() { - return id; - } - public void setId(Long id) { - this.id = id; - } - - public String getUsername() { - return username; - } - public void setUsername(String username) { - this.username = username; - } - - public String getFirstName() { - return firstName; - } - public void setFirstName(String firstName) { - this.firstName = firstName; - } - - public String getLastName() { - return lastName; - } - public void setLastName(String lastName) { - this.lastName = lastName; - } - - public String getEmail() { - return email; - } - public void setEmail(String email) { - this.email = email; - } - - public String getPassword() { - return password; - } - public void setPassword(String password) { - this.password = password; - } - - public String getPhone() { - return phone; - } - public void setPhone(String phone) { - this.phone = phone; - } - - public Integer getUserStatus() { - return userStatus; - } - public void setUserStatus(Integer userStatus) { - this.userStatus = userStatus; - } - - @Override - public String toString() { - StringBuilder sb = new StringBuilder(); - sb.append("class User {\n"); - - sb.append(" id: ").append(id).append("\n"); - sb.append(" username: ").append(username).append("\n"); - sb.append(" firstName: ").append(firstName).append("\n"); - sb.append(" lastName: ").append(lastName).append("\n"); - sb.append(" email: ").append(email).append("\n"); - sb.append(" password: ").append(password).append("\n"); - sb.append(" phone: ").append(phone).append("\n"); - sb.append(" userStatus: ").append(userStatus).append("\n"); - sb.append("}\n"); - return sb.toString(); - } -} From f29f5d6f131db614880da8cc381c2a05c1a09c14 Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 18 Sep 2015 14:45:37 +0200 Subject: [PATCH 101/219] fix error with formParams in async ops --- .../src/main/resources/Java/libraries/retrofit/api.mustache | 4 ++-- .../retrofit/src/main/java/io/swagger/client/api/PetApi.java | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index 7f244c423bbf..89850d92bdc1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -34,8 +34,8 @@ public interface {{classname}} { {{/allParams}} * @param cb callback method * @return void */ - {{#libraries/retrofit/formParams}}{{#-first}} - {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/libraries/retrofit/formParams}} + {{#formParams}}{{#-first}} + {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} @{{httpMethod}}("{{path}}") void {{nickname}}( {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 5a3f5788e3f7..cd4dbe866a51 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -168,6 +168,7 @@ Void updatePetWithForm( * @return void */ + @FormUrlEncoded @POST("/pet/{petId}") void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb @@ -227,6 +228,7 @@ Void uploadFile( * @return void */ + @Multipart @POST("/pet/{petId}/uploadImage") void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb From 047b06ac8496954042a3f2f263d8517ba2944d36 Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 18 Sep 2015 15:03:55 +0200 Subject: [PATCH 102/219] remove retrofit codegen from config --- README.md | 1 - .../resources/META-INF/services/io.swagger.codegen.CodegenConfig | 1 - 2 files changed, 2 deletions(-) diff --git a/README.md b/README.md index 2edfbfa01d14..f7ee2b9667fd 100644 --- a/README.md +++ b/README.md @@ -203,7 +203,6 @@ PhpClientCodegen.java Python3ClientCodegen.java PythonClientCodegen.java Qt5CPPGenerator.java -RetrofitClientCodegen.java RubyClientCodegen.java ScalaClientCodegen.java ScalatraServerCodegen.java diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index a73fe5f43880..489d81f411f2 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -13,7 +13,6 @@ io.swagger.codegen.languages.PhpClientCodegen io.swagger.codegen.languages.PythonClientCodegen io.swagger.codegen.languages.Python3ClientCodegen io.swagger.codegen.languages.Qt5CPPGenerator -io.swagger.codegen.languages.RetrofitClientCodegen io.swagger.codegen.languages.RubyClientCodegen io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen From 3dc3af8d18a68daecae111c3da4b33f96d7adba3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 20 Sep 2015 22:43:43 +0800 Subject: [PATCH 103/219] remove python3 generator --- bin/python3-petstore.sh | 31 -- .../languages/Python3ClientCodegen.java | 219 --------- .../services/io.swagger.codegen.CodegenConfig | 1 - .../main/resources/python3/__init__.mustache | 9 - .../src/main/resources/python3/api.mustache | 95 ---- .../src/main/resources/python3/model.mustache | 40 -- .../main/resources/python3/swagger.mustache | 230 ---------- samples/client/petstore/python3/PetApi.py | 409 ----------------- .../python3/Python3PetstoreCodegen.scala | 28 -- samples/client/petstore/python3/StoreApi.py | 158 ------- samples/client/petstore/python3/UserApi.py | 353 --------------- samples/client/petstore/python3/__init__.py | 10 - .../petstore/python3/client/__init__.py | 9 - .../python3/client/models/category.py | 40 -- .../petstore/python3/client/models/order.py | 65 --- .../petstore/python3/client/models/pet.py | 65 --- .../petstore/python3/client/models/tag.py | 40 -- .../petstore/python3/client/models/user.py | 77 ---- .../client/petstore/python3/client/pet_api.py | 422 ------------------ .../petstore/python3/client/store_api.py | 229 ---------- .../client/petstore/python3/client/swagger.py | 230 ---------- .../petstore/python3/client/user_api.py | 404 ----------------- .../petstore/python3/models/Category.py | 32 -- .../client/petstore/python3/models/Order.py | 39 -- samples/client/petstore/python3/models/Pet.py | 42 -- samples/client/petstore/python3/models/Tag.py | 32 -- .../client/petstore/python3/models/User.py | 45 -- .../petstore/python3/models/__init__.py | 10 - samples/client/petstore/python3/swagger.py | 204 --------- .../petstore/python3/tests/BaseApiTest.py | 37 -- .../petstore/python3/tests/PetApiTest.py | 134 ------ .../petstore/python3/tests/StoreApiTest.py | 50 --- .../petstore/python3/tests/UserApiTest.py | 229 ---------- 33 files changed, 4018 deletions(-) delete mode 100755 bin/python3-petstore.sh delete mode 100755 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java delete mode 100644 modules/swagger-codegen/src/main/resources/python3/__init__.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/python3/api.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/python3/model.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/python3/swagger.mustache delete mode 100644 samples/client/petstore/python3/PetApi.py delete mode 100644 samples/client/petstore/python3/Python3PetstoreCodegen.scala delete mode 100644 samples/client/petstore/python3/StoreApi.py delete mode 100644 samples/client/petstore/python3/UserApi.py delete mode 100644 samples/client/petstore/python3/__init__.py delete mode 100644 samples/client/petstore/python3/client/__init__.py delete mode 100644 samples/client/petstore/python3/client/models/category.py delete mode 100644 samples/client/petstore/python3/client/models/order.py delete mode 100644 samples/client/petstore/python3/client/models/pet.py delete mode 100644 samples/client/petstore/python3/client/models/tag.py delete mode 100644 samples/client/petstore/python3/client/models/user.py delete mode 100644 samples/client/petstore/python3/client/pet_api.py delete mode 100644 samples/client/petstore/python3/client/store_api.py delete mode 100644 samples/client/petstore/python3/client/swagger.py delete mode 100644 samples/client/petstore/python3/client/user_api.py delete mode 100644 samples/client/petstore/python3/models/Category.py delete mode 100644 samples/client/petstore/python3/models/Order.py delete mode 100644 samples/client/petstore/python3/models/Pet.py delete mode 100644 samples/client/petstore/python3/models/Tag.py delete mode 100644 samples/client/petstore/python3/models/User.py delete mode 100644 samples/client/petstore/python3/models/__init__.py delete mode 100644 samples/client/petstore/python3/swagger.py delete mode 100644 samples/client/petstore/python3/tests/BaseApiTest.py delete mode 100644 samples/client/petstore/python3/tests/PetApiTest.py delete mode 100644 samples/client/petstore/python3/tests/StoreApiTest.py delete mode 100644 samples/client/petstore/python3/tests/UserApiTest.py diff --git a/bin/python3-petstore.sh b/bin/python3-petstore.sh deleted file mode 100755 index e2da97830959..000000000000 --- a/bin/python3-petstore.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/sh - -SCRIPT="$0" - -while [ -h "$SCRIPT" ] ; do - ls=`ls -ld "$SCRIPT"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - SCRIPT="$link" - else - SCRIPT=`dirname "$SCRIPT"`/"$link" - fi -done - -if [ ! -d "${APP_DIR}" ]; then - APP_DIR=`dirname "$SCRIPT"`/.. - APP_DIR=`cd "${APP_DIR}"; pwd` -fi - -executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" - -if [ ! -f "$executable" ] -then - mvn clean package -fi - -# if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -t modules/swagger-codegen/src/main/resources/python3 -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python3 -o samples/client/petstore/python3" - -java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java deleted file mode 100755 index 70c090cd7a3b..000000000000 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/Python3ClientCodegen.java +++ /dev/null @@ -1,219 +0,0 @@ -package io.swagger.codegen.languages; - -import io.swagger.codegen.CodegenConfig; -import io.swagger.codegen.CodegenType; -import io.swagger.codegen.DefaultCodegen; -import io.swagger.codegen.SupportingFile; -import io.swagger.models.properties.ArrayProperty; -import io.swagger.models.properties.MapProperty; -import io.swagger.models.properties.Property; - -import java.io.File; -import java.util.Arrays; -import java.util.HashSet; - -import org.apache.commons.lang.StringUtils; - -public class Python3ClientCodegen extends DefaultCodegen implements CodegenConfig { - String module = "client"; - - public Python3ClientCodegen() { - super(); - outputFolder = "generated-code/python3"; - modelTemplateFiles.put("model.mustache", ".py"); - apiTemplateFiles.put("api.mustache", ".py"); - templateDir = "python3"; - - apiPackage = module; - modelPackage = module + ".models"; - - languageSpecificPrimitives.clear(); - languageSpecificPrimitives.add("int"); - languageSpecificPrimitives.add("float"); - //languageSpecificPrimitives.add("long"); - languageSpecificPrimitives.add("list"); - languageSpecificPrimitives.add("bool"); - languageSpecificPrimitives.add("str"); - languageSpecificPrimitives.add("datetime"); - languageSpecificPrimitives.add("date"); - - typeMapping.clear(); - typeMapping.put("integer", "int"); - typeMapping.put("float", "float"); - typeMapping.put("long", "int"); - typeMapping.put("double", "float"); - typeMapping.put("array", "list"); - typeMapping.put("map", "map"); - typeMapping.put("boolean", "bool"); - typeMapping.put("string", "str"); - typeMapping.put("date", "date"); - typeMapping.put("DateTime", "datetime"); - - // from https://docs.python.org/release/2.5.4/ref/keywords.html - reservedWords = new HashSet( - Arrays.asList( - "and", "del", "from", "not", "while", "as", "elif", "global", "or", "with", - "assert", "else", "if", "pass", "yield", "break", "except", "import", - "print", "class", "exec", "in", "raise", "continue", "finally", "is", - "return", "def", "for", "lambda", "try")); - - //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); - supportingFiles.add(new SupportingFile("swagger.mustache", module, "swagger.py")); - supportingFiles.add(new SupportingFile("__init__.mustache", module, "__init__.py")); - } - - public CodegenType getTag() { - return CodegenType.CLIENT; - } - - public String getName() { - return "python3"; - } - - public String getHelp() { - return "Generates a Python3 client library."; - } - - @Override - public String escapeReservedWord(String name) { - return "_" + name; - } - - @Override - public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); - } - - public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); - } - - @Override - public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; - } else if (p instanceof MapProperty) { - MapProperty mp = (MapProperty) p; - Property inner = mp.getAdditionalProperties(); - - return getSwaggerType(p) + "(String, " + getTypeDeclaration(inner) + ")"; - } - return super.getTypeDeclaration(p); - } - - @Override - public String getSwaggerType(Property p) { - String swaggerType = super.getSwaggerType(p); - String type = null; - if (typeMapping.containsKey(swaggerType)) { - type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { - return type; - } - } else { - type = swaggerType; - } - return type; - } - - public String toDefaultValue(Property p) { - // TODO: Support Python def value - return "null"; - } - - @Override - public String toVarName(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // if it's all uppper case, convert to lower case - if (name.matches("^[A-Z_]*$")) { - name = name.toLowerCase(); - } - - // camelize (lower first character) the variable name - // petId => pet_id - name = underscore(name); - - // for reserved word or word starting with number, append _ - if (reservedWords.contains(name) || name.matches("^\\d.*")) { - name = escapeReservedWord(name); - } - - return name; - } - - @Override - public String toParamName(String name) { - // should be the same as variable name - return toVarName(name); - } - - @Override - public String toModelName(String name) { - // model name cannot use reserved keyword, e.g. return - if (reservedWords.contains(name)) { - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - } - - // camelize the model name - // phone_number => PhoneNumber - return camelize(name); - } - - @Override - public String toModelFilename(String name) { - // model name cannot use reserved keyword, e.g. return - if (reservedWords.contains(name)) { - throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); - } - - // underscore the model file name - // PhoneNumber.rb => phone_number.rb - return underscore(name); - } - - @Override - public String toApiFilename(String name) { - // replace - with _ e.g. created-at => created_at - name = name.replaceAll("-", "_"); - - // e.g. PhoneNumberApi.rb => phone_number_api.rb - return underscore(name) + "_api"; - } - - @Override - public String toApiName(String name) { - if (name.length() == 0) { - return "DefaultApi"; - } - // e.g. phone_number_api => PhoneNumberApi - return camelize(name) + "Api"; - } - - @Override - public String toApiVarName(String name) { - if (name.length() == 0) { - return "default_api"; - } - return underscore(name) + "_api"; - } - - @Override - public String toOperationId(String operationId) { - // throw exception if method name is empty - if (StringUtils.isEmpty(operationId)) { - throw new RuntimeException("Empty method name (operationId) not allowed"); - } - - // method name cannot use reserved keyword, e.g. return - if (reservedWords.contains(operationId)) { - throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - } - - return underscore(operationId); - } - -} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index a73fe5f43880..984c33fa1103 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -11,7 +11,6 @@ io.swagger.codegen.languages.ObjcClientCodegen io.swagger.codegen.languages.PerlClientCodegen io.swagger.codegen.languages.PhpClientCodegen io.swagger.codegen.languages.PythonClientCodegen -io.swagger.codegen.languages.Python3ClientCodegen io.swagger.codegen.languages.Qt5CPPGenerator io.swagger.codegen.languages.RetrofitClientCodegen io.swagger.codegen.languages.RubyClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/python3/__init__.mustache b/modules/swagger-codegen/src/main/resources/python3/__init__.mustache deleted file mode 100644 index 4b41ee706c70..000000000000 --- a/modules/swagger-codegen/src/main/resources/python3/__init__.mustache +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/modules/swagger-codegen/src/main/resources/python3/api.mustache b/modules/swagger-codegen/src/main/resources/python3/api.mustache deleted file mode 100644 index 2ff659b11b50..000000000000 --- a/modules/swagger-codegen/src/main/resources/python3/api.mustache +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python -""" -{{classname}}.py -Copyright 2015 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -{{#operations}} -class {{classname}}(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - {{newline}} - {{#operation}} - def {{nickname}}(self, {{#requiredParams}}{{paramName}}{{#defaultValue}} = None{{/defaultValue}}, {{/requiredParams}}**kwargs): - """{{{summary}}} - {{{notes}}} - - Args: - {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{#required}}(required){{/required}}{{^required}}(optional){{/required}} - {{/allParams}} - - Returns: {{returnType}} - """ - - allParams = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '{{path}}' - resourcePath = resourcePath.replace('{format}', 'json') - method = '{{httpMethod}}' - - queryParams = {} - headerParams = {} - - {{#queryParams}} - if ('{{paramName}}' in params): - queryParams['{{paramName}}'] = self.apiClient.toPathValue(params['{{paramName}}']) - {{/queryParams}} - - {{#headerParams}} - if ('{{paramName}}' in params): - headerParams['{{paramName}}'] = params['{{paramName}}'] - {{/headerParams}} - - {{#pathParams}} - if ('{{paramName}}' in params): - replacement = str(self.apiClient.toPathValue(params['{{paramName}}'])) - resourcePath = resourcePath.replace('{' + '{{baseName}}' + '}', - replacement) - {{/pathParams}} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - {{#returnType}} - if not response: - return None - - responseObject = self.apiClient.deserialize(response, '{{returnType}}') - return responseObject - {{/returnType}} - {{newline}} - {{newline}} - {{/operation}} -{{newline}} -{{/operations}} -{{newline}} diff --git a/modules/swagger-codegen/src/main/resources/python3/model.mustache b/modules/swagger-codegen/src/main/resources/python3/model.mustache deleted file mode 100644 index ef3841a34b96..000000000000 --- a/modules/swagger-codegen/src/main/resources/python3/model.mustache +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2015 SmartBear Software - - 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. -""" -{{#models}} -{{#model}} - -class {{classname}}: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - {{#vars}} - '{{name}}': '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}} - {{/vars}}{{newline}} - } - - - {{#vars}} - {{#description}}#{{description}} - {{/description}} - self.{{name}} = None # {{{datatype}}} - {{/vars}} -{{/model}} -{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache b/modules/swagger-codegen/src/main/resources/python3/swagger.mustache deleted file mode 100644 index 57f959c380b4..000000000000 --- a/modules/swagger-codegen/src/main/resources/python3/swagger.mustache +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib.request, urllib.error, urllib.parse -import http.client -import json -import datetime - -from .models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None, cookie=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = cookie - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.items(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['PATCH', 'POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - if data: - data = data.encode('utf-8') - - requestParams = MethodRequest(method=method, url=url, - headers=headers, data=data) - - # Make the request - request = urllib.request.urlopen(requestParams) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - - try: - data = json.loads(response) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.parse.quote(','.join(obj)) - else: - return urllib.parse.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.items() - if key != 'swaggerTypes'} - - def _iso8601Format(self, timesep, microsecond, offset, zulu): - """Format for parsing a datetime string with given properties. - - Args: - timesep -- string separating time from date ('T' or 't') - microsecond -- microsecond portion of time ('.XXX') - offset -- time offset (+/-XX:XX) or None - zulu -- 'Z' or 'z' for UTC, or None for time offset (+/-XX:XX) - - Returns: - str - format string for datetime.strptime""" - - return '%Y-%m-%d{}%H:%M:%S{}{}'.format( - timesep, - '.%f' if microsecond else '', - zulu or ('%z' if offset else '')) - - # http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - _iso8601Regex = re.compile( - r'^\d\d\d\d-\d\d-\d\d([Tt])\d\d:\d\d:\d\d(\.\d+)?(([Zz])|(\+|-)\d\d:?\d\d)?$') - - def _parseDatetime(self, d): - if d is None: - return None - m = ApiClient._iso8601Regex.match(d) - if not m: - raise Exception('datetime regex match failed "%s"' % d) - timesep, microsecond, offset, zulu, plusminus = m.groups() - format = self._iso8601Format(timesep, microsecond, offset, zulu) - if offset and not zulu: - d = d.rsplit(sep=plusminus, maxsplit=1)[0] + offset.replace(':', '') - return datetime.datetime.strptime(d, format) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - return self._parseDatetime(obj) - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.items(): - - if attr in obj: - value = obj[attr] - if attrType in ['str', 'int', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, self._parseDatetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - attrType)) - - return instance - - -class MethodRequest(urllib.request.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib.request.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib.request.Request.get_method(self)) diff --git a/samples/client/petstore/python3/PetApi.py b/samples/client/petstore/python3/PetApi.py deleted file mode 100644 index 8469213d0d6f..000000000000 --- a/samples/client/petstore/python3/PetApi.py +++ /dev/null @@ -1,409 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class PetApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def getPetById(self, petId, **kwargs): - """Find pet by ID - - Args: - petId, int: ID of pet that needs to be fetched (required) - - - - Returns: Pet - """ - - allParams = ['petId'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getPetById" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Pet') - return responseObject - - - - - def deletePet(self, petId, **kwargs): - """Deletes a pet - - Args: - petId, str: Pet id to delete (required) - - - - Returns: - """ - - allParams = ['petId'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deletePet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def partialUpdate(self, petId, body, **kwargs): - """partial updates to a pet - - Args: - petId, str: ID of pet that needs to be fetched (required) - - body, Pet: Pet object that needs to be added to the store (required) - - - - Returns: Array[Pet] - """ - - allParams = ['petId', 'body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method partialUpdate" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PATCH' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Array[Pet]') - return responseObject - - - - - def updatePetWithForm(self, petId, **kwargs): - """Updates a pet in the store with form data - - Args: - petId, str: ID of pet that needs to be updated (required) - - name, str: Updated name of the pet (optional) - - status, str: Updated status of the pet (optional) - - - - Returns: - """ - - allParams = ['petId', 'name', 'status'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updatePetWithForm" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - if ('petId' in params): - replacement = str(self.apiClient.toPathValue(params['petId'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def uploadFile(self, **kwargs): - """uploads an image - - Args: - additionalMetadata, str: Additional data to pass to server (optional) - - body, File: file to upload (optional) - - - - Returns: - """ - - allParams = ['additionalMetadata', 'body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method uploadFile" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/uploadImage' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def addPet(self, body, **kwargs): - """Add a new pet to the store - - Args: - body, Pet: Pet object that needs to be added to the store (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method addPet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def updatePet(self, body, **kwargs): - """Update an existing pet - - Args: - body, Pet: Pet object that needs to be updated in the store (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updatePet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def findPetsByStatus(self, status= None, **kwargs): - """Finds Pets by status - - Args: - status, str: Status values that need to be considered for filter (required) - - - - Returns: Array[Pet] - """ - - allParams = ['status'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method findPetsByStatus" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByStatus' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('status' in params): - queryParams['status'] = self.apiClient.toPathValue(params['status']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Array[Pet]') - return responseObject - - - - - def findPetsByTags(self, tags, **kwargs): - """Finds Pets by tags - - Args: - tags, str: Tags to filter by (required) - - - - Returns: Array[Pet] - """ - - allParams = ['tags'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method findPetsByTags" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByTags' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('tags' in params): - queryParams['tags'] = self.apiClient.toPathValue(params['tags']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Array[Pet]') - return responseObject - - - - - - - - - diff --git a/samples/client/petstore/python3/Python3PetstoreCodegen.scala b/samples/client/petstore/python3/Python3PetstoreCodegen.scala deleted file mode 100644 index 270d19743a5e..000000000000 --- a/samples/client/petstore/python3/Python3PetstoreCodegen.scala +++ /dev/null @@ -1,28 +0,0 @@ -/** - * Copyright 2014 Wordnik, Inc. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import java.io.File - -object Python3PetstoreCodegen extends BasicPython3Generator { - def main(args: Array[String]) = generateClient(args) - - override def supportingFiles = List( - ("__init__.mustache", destinationDir, "__init__.py"), - ("swagger.mustache", destinationDir + File.separator + apiPackage.getOrElse(""), "swagger.py"), - ("__init__.mustache", destinationDir + File.separator + modelPackage.getOrElse(""), "__init__.py")) - - override def destinationDir = "samples/client/petstore/python3" -} diff --git a/samples/client/petstore/python3/StoreApi.py b/samples/client/petstore/python3/StoreApi.py deleted file mode 100644 index 64975ebc14dc..000000000000 --- a/samples/client/petstore/python3/StoreApi.py +++ /dev/null @@ -1,158 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class StoreApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def getOrderById(self, orderId, **kwargs): - """Find purchase order by ID - - Args: - orderId, str: ID of pet that needs to be fetched (required) - - - - Returns: Order - """ - - allParams = ['orderId'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getOrderById" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('orderId' in params): - replacement = str(self.apiClient.toPathValue(params['orderId'])) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def deleteOrder(self, orderId, **kwargs): - """Delete purchase order by ID - - Args: - orderId, str: ID of the order that needs to be deleted (required) - - - - Returns: - """ - - allParams = ['orderId'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteOrder" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('orderId' in params): - replacement = str(self.apiClient.toPathValue(params['orderId'])) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def placeOrder(self, body, **kwargs): - """Place an order for a pet - - Args: - body, Order: order placed for purchasing the pet (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method placeOrder" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - - - - diff --git a/samples/client/petstore/python3/UserApi.py b/samples/client/petstore/python3/UserApi.py deleted file mode 100644 index cff6cb7d6726..000000000000 --- a/samples/client/petstore/python3/UserApi.py +++ /dev/null @@ -1,353 +0,0 @@ -#!/usr/bin/env python -""" -WordAPI.py -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class UserApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def updateUser(self, username, body, **kwargs): - """Updated user - - Args: - username, str: name that need to be deleted (required) - - body, User: Updated user object (required) - - - - Returns: - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method updateUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def deleteUser(self, username, **kwargs): - """Delete user - - Args: - username, str: The name that needs to be deleted (required) - - - - Returns: - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method deleteUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def getUserByName(self, username, **kwargs): - """Get user by user name - - Args: - username, str: The name that needs to be fetched. Use user1 for testing. (required) - - - - Returns: User - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method getUserByName" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - def loginUser(self, username, password, **kwargs): - """Logs user into the system - - Args: - username, str: The user name for login (required) - - password, str: The password for login in clear text (required) - - - - Returns: str - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method loginUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/login' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - if ('username' in params): - queryParams['username'] = self.apiClient.toPathValue(params['username']) - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'str') - return responseObject - - - - - def logoutUser(self, **kwargs): - """Logs out current logged in user session - - Args: - - - Returns: - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method logoutUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/logout' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def createUser(self, body, **kwargs): - """Create user - - Args: - body, User: Created user object (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createUser" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def createUsersWithArrayInput(self, body, **kwargs): - """Creates list of users with given input array - - Args: - body, list[User]: List of user object (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithArrayInput" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithArray' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def createUsersWithListInput(self, body, **kwargs): - """Creates list of users with given list input - - Args: - body, list[User]: List of user object (required) - - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithListInput" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithList' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - - - - diff --git a/samples/client/petstore/python3/__init__.py b/samples/client/petstore/python3/__init__.py deleted file mode 100644 index 39f84514fe91..000000000000 --- a/samples/client/petstore/python3/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - diff --git a/samples/client/petstore/python3/client/__init__.py b/samples/client/petstore/python3/client/__init__.py deleted file mode 100644 index 4b41ee706c70..000000000000 --- a/samples/client/petstore/python3/client/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/samples/client/petstore/python3/client/models/category.py b/samples/client/petstore/python3/client/models/category.py deleted file mode 100644 index 25b5e7cce957..000000000000 --- a/samples/client/petstore/python3/client/models/category.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2015 SmartBear Software - - 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. -""" - -class Category: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - - 'id': 'int', - - - 'name': 'str' - - } - - - - - self.id = None # int - - - self.name = None # str - diff --git a/samples/client/petstore/python3/client/models/order.py b/samples/client/petstore/python3/client/models/order.py deleted file mode 100644 index 0988a3543389..000000000000 --- a/samples/client/petstore/python3/client/models/order.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2015 SmartBear Software - - 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. -""" - -class Order: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - - 'id': 'int', - - - 'pet_id': 'int', - - - 'quantity': 'int', - - - 'ship_date': 'DateTime', - - - 'status': 'str', - - - 'complete': 'bool' - - } - - - - - self.id = None # int - - - self.pet_id = None # int - - - self.quantity = None # int - - - self.ship_date = None # DateTime - - #Order Status - - self.status = None # str - - - self.complete = None # bool - diff --git a/samples/client/petstore/python3/client/models/pet.py b/samples/client/petstore/python3/client/models/pet.py deleted file mode 100644 index e6b96c475587..000000000000 --- a/samples/client/petstore/python3/client/models/pet.py +++ /dev/null @@ -1,65 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2015 SmartBear Software - - 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. -""" - -class Pet: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - - 'id': 'int', - - - 'category': 'Category', - - - 'name': 'str', - - - 'photo_urls': 'list[str]', - - - 'tags': 'list[Tag]', - - - 'status': 'str' - - } - - - - - self.id = None # int - - - self.category = None # Category - - - self.name = None # str - - - self.photo_urls = None # list[str] - - - self.tags = None # list[Tag] - - #pet status in the store - - self.status = None # str - diff --git a/samples/client/petstore/python3/client/models/tag.py b/samples/client/petstore/python3/client/models/tag.py deleted file mode 100644 index f9ed397123b9..000000000000 --- a/samples/client/petstore/python3/client/models/tag.py +++ /dev/null @@ -1,40 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2015 SmartBear Software - - 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. -""" - -class Tag: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - - 'id': 'int', - - - 'name': 'str' - - } - - - - - self.id = None # int - - - self.name = None # str - diff --git a/samples/client/petstore/python3/client/models/user.py b/samples/client/petstore/python3/client/models/user.py deleted file mode 100644 index 0f88d5fc3d4a..000000000000 --- a/samples/client/petstore/python3/client/models/user.py +++ /dev/null @@ -1,77 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2015 SmartBear Software - - 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. -""" - -class User: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - - 'id': 'int', - - - 'username': 'str', - - - 'first_name': 'str', - - - 'last_name': 'str', - - - 'email': 'str', - - - 'password': 'str', - - - 'phone': 'str', - - - 'user_status': 'int' - - } - - - - - self.id = None # int - - - self.username = None # str - - - self.first_name = None # str - - - self.last_name = None # str - - - self.email = None # str - - - self.password = None # str - - - self.phone = None # str - - #User Status - - self.user_status = None # int - diff --git a/samples/client/petstore/python3/client/pet_api.py b/samples/client/petstore/python3/client/pet_api.py deleted file mode 100644 index cebab131778f..000000000000 --- a/samples/client/petstore/python3/client/pet_api.py +++ /dev/null @@ -1,422 +0,0 @@ -#!/usr/bin/env python -""" -PetApi.py -Copyright 2015 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class PetApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def update_pet(self, **kwargs): - """Update an existing pet - - - Args: - body, Pet: Pet object that needs to be added to the store (optional) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def add_pet(self, **kwargs): - """Add a new pet to the store - - - Args: - body, Pet: Pet object that needs to be added to the store (optional) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def find_pets_by_status(self, **kwargs): - """Finds Pets by status - Multiple status values can be provided with comma seperated strings - - Args: - status, list[str]: Status values that need to be considered for filter (optional) - - - Returns: list[Pet] - """ - - allParams = ['status'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByStatus' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - if ('status' in params): - queryParams['status'] = self.apiClient.toPathValue(params['status']) - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Pet]') - return responseObject - - - - - def find_pets_by_tags(self, **kwargs): - """Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - - Args: - tags, list[str]: Tags to filter by (optional) - - - Returns: list[Pet] - """ - - allParams = ['tags'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByTags' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - if ('tags' in params): - queryParams['tags'] = self.apiClient.toPathValue(params['tags']) - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Pet]') - return responseObject - - - - - def get_pet_by_id(self, **kwargs): - """Find pet by ID - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - Args: - pet_id, int: ID of pet that needs to be fetched (required) - - - Returns: Pet - """ - - allParams = ['pet_id'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Pet') - return responseObject - - - - - def update_pet_with_form(self, **kwargs): - """Updates a pet in the store with form data - - - Args: - pet_id, str: ID of pet that needs to be updated (required) - name, str: Updated name of the pet (optional) - status, str: Updated status of the pet (optional) - - - Returns: - """ - - allParams = ['pet_id', 'name', 'status'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def delete_pet(self, **kwargs): - """Deletes a pet - - - Args: - api_key, str: (optional) - pet_id, int: Pet id to delete (required) - - - Returns: - """ - - allParams = ['api_key', 'pet_id'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - - - - if ('api_key' in params): - headerParams['api_key'] = params['api_key'] - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def upload_file(self, **kwargs): - """uploads an image - - - Args: - pet_id, int: ID of pet to update (required) - additional_metadata, str: Additional data to pass to server (optional) - file, file: file to upload (optional) - - - Returns: - """ - - allParams = ['pet_id', 'additional_metadata', 'file'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}/uploadImage' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - diff --git a/samples/client/petstore/python3/client/store_api.py b/samples/client/petstore/python3/client/store_api.py deleted file mode 100644 index 802e116f1ff1..000000000000 --- a/samples/client/petstore/python3/client/store_api.py +++ /dev/null @@ -1,229 +0,0 @@ -#!/usr/bin/env python -""" -StoreApi.py -Copyright 2015 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class StoreApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def get_inventory(self, **kwargs): - """Returns pet inventories by status - Returns a map of status codes to quantities - - Args: - - - Returns: map(String, int) - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/inventory' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'map(String, int)') - return responseObject - - - - - def place_order(self, **kwargs): - """Place an order for a pet - - - Args: - body, Order: order placed for purchasing the pet (optional) - - - Returns: Order - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def get_order_by_id(self, **kwargs): - """Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - Args: - order_id, str: ID of pet that needs to be fetched (required) - - - Returns: Order - """ - - allParams = ['order_id'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - - - - - if ('order_id' in params): - replacement = str(self.apiClient.toPathValue(params['order_id'])) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def delete_order(self, **kwargs): - """Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - - Args: - order_id, str: ID of the order that needs to be deleted (required) - - - Returns: - """ - - allParams = ['order_id'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - - - - - - if ('order_id' in params): - replacement = str(self.apiClient.toPathValue(params['order_id'])) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - diff --git a/samples/client/petstore/python3/client/swagger.py b/samples/client/petstore/python3/client/swagger.py deleted file mode 100644 index f99f0d4d250d..000000000000 --- a/samples/client/petstore/python3/client/swagger.py +++ /dev/null @@ -1,230 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib.request, urllib.error, urllib.parse -import http.client -import json -import datetime - -from .models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.items(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['PATCH', 'POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - if data: - data = data.encode('utf-8') - - requestParams = MethodRequest(method=method, url=url, - headers=headers, data=data) - - # Make the request - request = urllib.request.urlopen(requestParams) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - - try: - data = json.loads(response) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.parse.quote(','.join(obj)) - else: - return urllib.parse.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.items() - if key != 'swaggerTypes'} - - def _iso8601Format(self, timesep, microsecond, offset, zulu): - """Format for parsing a datetime string with given properties. - - Args: - timesep -- string separating time from date ('T' or 't') - microsecond -- microsecond portion of time ('.XXX') - offset -- time offset (+/-XX:XX) or None - zulu -- 'Z' or 'z' for UTC, or None for time offset (+/-XX:XX) - - Returns: - str - format string for datetime.strptime""" - - return '%Y-%m-%d{}%H:%M:%S{}{}'.format( - timesep, - '.%f' if microsecond else '', - zulu or ('%z' if offset else '')) - - # http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 - _iso8601Regex = re.compile( - r'^\d\d\d\d-\d\d-\d\d([Tt])\d\d:\d\d:\d\d(\.\d+)?(([Zz])|(\+|-)\d\d:?\d\d)?$') - - def _parseDatetime(self, d): - if d is None: - return None - m = ApiClient._iso8601Regex.match(d) - if not m: - raise Exception('datetime regex match failed "%s"' % d) - timesep, microsecond, offset, zulu, plusminus = m.groups() - format = self._iso8601Format(timesep, microsecond, offset, zulu) - if offset and not zulu: - d = d.rsplit(sep=plusminus, maxsplit=1)[0] + offset.replace(':', '') - return datetime.datetime.strptime(d, format) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - return self._parseDatetime(obj) - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.items(): - - if attr in obj: - value = obj[attr] - if attrType in ['str', 'int', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, self._parseDatetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - attrType)) - - return instance - - -class MethodRequest(urllib.request.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib.request.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib.request.Request.get_method(self)) diff --git a/samples/client/petstore/python3/client/user_api.py b/samples/client/petstore/python3/client/user_api.py deleted file mode 100644 index 54813ca2dddd..000000000000 --- a/samples/client/petstore/python3/client/user_api.py +++ /dev/null @@ -1,404 +0,0 @@ -#!/usr/bin/env python -""" -UserApi.py -Copyright 2015 SmartBear Software - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os - -from .models import * - - -class UserApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def create_user(self, **kwargs): - """Create user - This can only be done by the logged in user. - - Args: - body, User: Created user object (optional) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def create_users_with_array_input(self, **kwargs): - """Creates list of users with given input array - - - Args: - body, list[User]: List of user object (optional) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithArray' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def create_users_with_list_input(self, **kwargs): - """Creates list of users with given input array - - - Args: - body, list[User]: List of user object (optional) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithList' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def login_user(self, **kwargs): - """Logs user into the system - - - Args: - username, str: The user name for login (optional) - password, str: The password for login in clear text (optional) - - - Returns: str - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/login' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - if ('username' in params): - queryParams['username'] = self.apiClient.toPathValue(params['username']) - - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'str') - return responseObject - - - - - def logout_user(self, **kwargs): - """Logs out current logged in user session - - - Args: - - - Returns: - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/logout' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - - - - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def get_user_by_name(self, **kwargs): - """Get user by user name - - - Args: - username, str: The name that needs to be fetched. Use user1 for testing. (required) - - - Returns: User - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - def update_user(self, **kwargs): - """Updated user - This can only be done by the logged in user. - - Args: - username, str: name that need to be deleted (required) - body, User: Updated user object (optional) - - - Returns: - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - def delete_user(self, **kwargs): - """Delete user - This can only be done by the logged in user. - - Args: - username, str: The name that needs to be deleted (required) - - - Returns: - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - - - - - diff --git a/samples/client/petstore/python3/models/Category.py b/samples/client/petstore/python3/models/Category.py deleted file mode 100644 index 0957f81ded4d..000000000000 --- a/samples/client/petstore/python3/models/Category.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -""" -class Category: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'name': 'str' - - } - - - self.id = None # int - self.name = None # str - diff --git a/samples/client/petstore/python3/models/Order.py b/samples/client/petstore/python3/models/Order.py deleted file mode 100644 index 060205e76f69..000000000000 --- a/samples/client/petstore/python3/models/Order.py +++ /dev/null @@ -1,39 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -""" -class Order: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'petId': 'int', - 'quantity': 'int', - 'status': 'str', - 'shipDate': 'datetime' - - } - - - self.id = None # int - self.petId = None # int - self.quantity = None # int - #Order Status - self.status = None # str - self.shipDate = None # datetime - diff --git a/samples/client/petstore/python3/models/Pet.py b/samples/client/petstore/python3/models/Pet.py deleted file mode 100644 index f313b0681d53..000000000000 --- a/samples/client/petstore/python3/models/Pet.py +++ /dev/null @@ -1,42 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -""" -class Pet: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'category': 'Category', - 'name': 'str', - 'photoUrls': 'list[str]', - 'tags': 'list[Tag]', - 'status': 'str' - - } - - - #unique identifier for the pet - self.id = None # int - self.category = None # Category - self.name = None # str - self.photoUrls = None # list[str] - self.tags = None # list[Tag] - #pet status in the store - self.status = None # str - diff --git a/samples/client/petstore/python3/models/Tag.py b/samples/client/petstore/python3/models/Tag.py deleted file mode 100644 index 0adc9dfe8826..000000000000 --- a/samples/client/petstore/python3/models/Tag.py +++ /dev/null @@ -1,32 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -""" -class Tag: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'name': 'str' - - } - - - self.id = None # int - self.name = None # str - diff --git a/samples/client/petstore/python3/models/User.py b/samples/client/petstore/python3/models/User.py deleted file mode 100644 index 113229ca42f4..000000000000 --- a/samples/client/petstore/python3/models/User.py +++ /dev/null @@ -1,45 +0,0 @@ -#!/usr/bin/env python -""" -Copyright 2014 Wordnik, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. -""" -class User: - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" - - - def __init__(self): - self.swaggerTypes = { - 'id': 'int', - 'firstName': 'str', - 'username': 'str', - 'lastName': 'str', - 'email': 'str', - 'password': 'str', - 'phone': 'str', - 'userStatus': 'int' - - } - - - self.id = None # int - self.firstName = None # str - self.username = None # str - self.lastName = None # str - self.email = None # str - self.password = None # str - self.phone = None # str - #User Status - self.userStatus = None # int - diff --git a/samples/client/petstore/python3/models/__init__.py b/samples/client/petstore/python3/models/__init__.py deleted file mode 100644 index 39f84514fe91..000000000000 --- a/samples/client/petstore/python3/models/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" -import os - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) - diff --git a/samples/client/petstore/python3/swagger.py b/samples/client/petstore/python3/swagger.py deleted file mode 100644 index 293cc09cb552..000000000000 --- a/samples/client/petstore/python3/swagger.py +++ /dev/null @@ -1,204 +0,0 @@ -#!/usr/bin/env python -"""Wordnik.com's Swagger generic API client. This client handles the client- -server communication, and is invariant across implementations. Specifics of -the methods and models for each application are generated from the Swagger -templates.""" - -import sys -import os -import re -import urllib.request, urllib.error, urllib.parse -import http.client -import json -import datetime - -from .models import * - - -class ApiClient: - """Generic API client for Swagger client library builds""" - - def __init__(self, apiKey=None, apiServer=None): - if apiKey == None: - raise Exception('You must pass an apiKey when instantiating the ' - 'APIClient') - self.apiKey = apiKey - self.apiServer = apiServer - self.cookie = None - - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None): - - url = self.apiServer + resourcePath - headers = {} - if headerParams: - for param, value in headerParams.items(): - headers[param] = value - - #headers['Content-type'] = 'application/json' - headers['api_key'] = self.apiKey - - if self.cookie: - headers['Cookie'] = self.cookie - - data = None - - - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) - - if method in ['GET']: - - #Options to add statements later on and for compatibility - pass - - elif method in ['POST', 'PUT', 'DELETE']: - - if postData: - headers['Content-type'] = 'application/json' - data = self.sanitizeForSerialization(postData) - data = json.dumps(data) - - else: - raise Exception('Method ' + method + ' is not recognized.') - - if data: - data = data.encode('utf-8') - - requestParams = MethodRequest(method=method, url=url, - headers=headers, data=data) - - # Make the request - request = urllib.request.urlopen(requestParams) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - - try: - data = json.loads(response) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value - """ - if type(obj) == list: - return urllib.parse.quote(','.join(obj)) - else: - return urllib.parse.quote(str(obj)) - - def sanitizeForSerialization(self, obj): - """Dump an object into JSON for POSTing.""" - - if type(obj) == type(None): - return None - elif type(obj) in [str, int, float, bool]: - return obj - elif type(obj) == list: - return [self.sanitizeForSerialization(subObj) for subObj in obj] - elif type(obj) == datetime.datetime: - return obj.isoformat() - else: - if type(obj) == dict: - objDict = obj - else: - objDict = obj.__dict__ - return {key: self.sanitizeForSerialization(val) - for (key, val) in objDict.items() - if key != 'swaggerTypes'} - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a - # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] - - if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) - else: # not a native type, must be model class - objClass = eval(objClass + '.' + objClass) - - if objClass in [int, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: - # Server will always return a time stamp in UTC, but with - # trailing +0000 indicating no offset from UTC. So don't process - # last 5 characters. - return datetime.datetime.strptime(obj[:-5], - "%Y-%m-%dT%H:%M:%S.%f") - - instance = objClass() - - for attr, attrType in instance.swaggerTypes.items(): - - if attr in obj: - value = obj[attr] - if attrType in ['str', 'int', 'float', 'bool']: - attrType = eval(attrType) - try: - value = attrType(value) - except UnicodeEncodeError: - value = unicode(value) - except TypeError: - value = value - setattr(instance, attr, value) - elif (attrType == 'datetime'): - setattr(instance, attr, datetime.datetime.strptime(value[:-5], - "%Y-%m-%dT%H:%M:%S.%f")) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] - if not value: - setattr(instance, attr, None) - else: - for subValue in value: - subValues.append(self.deserialize(subValue, - subClass)) - setattr(instance, attr, subValues) - else: - setattr(instance, attr, self.deserialize(value, - objClass)) - - return instance - - -class MethodRequest(urllib.request.Request): - - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" - - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib.request.Request.__init__(self, *args, **kwargs) - - def get_method(self): - return getattr(self, 'method', urllib.request.Request.get_method(self)) - diff --git a/samples/client/petstore/python3/tests/BaseApiTest.py b/samples/client/petstore/python3/tests/BaseApiTest.py deleted file mode 100644 index b2b0e37a1968..000000000000 --- a/samples/client/petstore/python3/tests/BaseApiTest.py +++ /dev/null @@ -1,37 +0,0 @@ -#!/usr/bin/env python -"""Unit tests for SwaggerPython Petstore sample app API client. - -Run all tests: - - python BaseApiTest.py - -""" - -import sys -import os -import unittest - -sys.path = ['./'] + sys.path -from petstore import * - - -class BaseApiTest(unittest.TestCase): - - def setUp(self): - self.apiKey = 'special-key' - self.apiUrl = 'http://petstore.swagger.wordnik.com/api' - self.username = 'test' - self.password = 'test' - - client = swagger.ApiClient(self.apiKey, self.apiUrl) - self.petApi = PetApi.PetApi(client) - self.storeApi = StoreApi.StoreApi(client) - self.userApi = UserApi.UserApi(client) - -if __name__ == "__main__": - - from PetApiTest import PetApiTest - from StoreApiTest import StoreApiTest - from UserApiTest import UserApiTest - - unittest.main() diff --git a/samples/client/petstore/python3/tests/PetApiTest.py b/samples/client/petstore/python3/tests/PetApiTest.py deleted file mode 100644 index 1c6f09a4ba73..000000000000 --- a/samples/client/petstore/python3/tests/PetApiTest.py +++ /dev/null @@ -1,134 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import urllib.request, urllib.error, urllib.parse -import json -import random - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from petstore import * -from petstore.models import * - - -class PetApiTest(BaseApiTest): - - @classmethod - def setUpClass(cls): - # super(PetApiTest, self).setUp() - cls.randomId = int(90000 * random.random()) + 10000 - - def testPetApis(self): - url = self.apiUrl + '/pet.json' - request = urllib.request.urlopen(url) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - doc = json.loads(response) - assert len(doc['apis']) == 3, 'there should be 3 pet apis' - - def testPetApisAuthenticated(self): - url = self.apiUrl + '/pet.json?' + 'api_key=special-key' - request = urllib.request.urlopen(url) - encoding = request.headers.get_content_charset() - if not encoding: - encoding = 'iso-8859-1' - response = request.read().decode(encoding) - doc = json.loads(response) - - assert len(doc['apis']) == 4, 'there should be 4 pet apis when' + \ - 'authenticated' - - def testGetPetById(self): - res = self.petApi.getPetById(1) - assert res, 'null getWord result' - assert res.id == 1, 'pet id should be 1' - - def testAddPet(self): - pet = Pet.Pet() - - pet.id = self.randomId - tag1 = Tag.Tag() - tag1.name = "tag1" - tag2 = Tag.Tag() - tag2.name = "some tag" - pet.tags = [tag1, tag2] - category = Category.Category() - category.name = "Cats" - pet.category = category - pet.status = "sold" - pet.name = "Shermie" - pet.photoUrls = ["http://foo.com/1.jpg", "http://foo.com/1.jpg"] - self.petApi.addPet(pet) - - new_pet = self.petApi.getPetById(pet.id) - - assert new_pet.id == pet.id, 'ids should match' - assert new_pet.name == pet.name, 'names should match' - assert(set([tag.name for tag in new_pet.tags]) == - set([tag.name for tag in pet.tags])), 'tags should match' - assert new_pet.status == pet.status, 'status should match' - assert new_pet.category.name == pet.category.name, 'category should match' - assert new_pet.photoUrls == pet.photoUrls, 'photoUrls should match' - - def testUpdatePet(self): - alpahbet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') - - pet = Pet.Pet() - pet.id = self.randomId - - tag1 = Tag.Tag() - tag1.name = "special-tag" - tag2 = Tag.Tag() - random.shuffle(alpahbet) - tag2.name = ''.join(alpahbet) - pet.tags = [tag1, tag2] - category = Category.Category() - random.shuffle(alpahbet) - category.name = ''.join(alpahbet) - pet.category = category - pet.status = "sold" - random.shuffle(alpahbet) - pet.name = ''.join(alpahbet) - pet.photoUrls = ["http://foo.com/22.jpg", "http://foo.com/55.jpg"] - self.petApi.updatePet(pet) - - updated_pet = self.petApi.getPetById(pet.id) - - assert updated_pet.id == pet.id, 'ids should match' - assert updated_pet.name == pet.name, 'names should match' - assert(set([tag.name for tag in updated_pet.tags]) == - set([tag.name for tag in pet.tags])), 'tags should match' - assert updated_pet.status == pet.status, 'status should match' - assert updated_pet.category.name == pet.category.name, 'category should match' - assert updated_pet.photoUrls == pet.photoUrls, 'photoUrls should match' - - def testFindPetsByTags(self): - pet = Pet.Pet() - pet.id = self.randomId - - tag1 = Tag.Tag() - tag1.name = "special-tag" - pet.tags = [tag1] - self.petApi.updatePet(pet) - - res = self.petApi.findPetsByTags("special-tag") - assert self.randomId in [pet.id for pet in res], 'must find by tag' - - def testFindPetsByStatus(self): - pet = Pet.Pet() - pet.id = self.randomId - - tag1 = Tag.Tag() - tag1.name = "special-tag" - pet.status = "sold" - self.petApi.updatePet(pet) - - res = self.petApi.findPetsByStatus("sold") - assert self.randomId in [pet.id for pet in res], 'must find by status' - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/petstore/python3/tests/StoreApiTest.py b/samples/client/petstore/python3/tests/StoreApiTest.py deleted file mode 100644 index 7b393f98e990..000000000000 --- a/samples/client/petstore/python3/tests/StoreApiTest.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python - -import sys -import unittest -import datetime -import random - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from petstore import * -from petstore.models import * - - -class StoreApiTest(BaseApiTest): - - @classmethod - def setUpClass(cls): - # super(PetApiTest, self).setUp() - cls.randomId = int(9500 * random.random()) + 500 - - def testGetOrderById(self): - res = self.storeApi.getOrderById(1) - assert res, 'null getOrderById result' - assert 1 == res.id, 'order id should be int(1)' - - def testDeleteOrder(self): - self.storeApi.deleteOrder(3) - self.storeApi.deleteOrder("foo") - - def testPlaceOrder(self): - - order = Order.Order() - order.id = self.randomId - order.petId = 1 - order.status = 'ordered' - order.quantity = 10 - order.shipDate = datetime.datetime.strptime("2011-01-09T13:55:07.123", - "%Y-%m-%dT%H:%M:%S.%f") - self.storeApi.placeOrder(order) - - new_order = self.storeApi.getOrderById(self.randomId) - assert new_order.id == new_order.id, 'ids should match' - assert new_order.petId == new_order.petId, 'petIds should match' - assert new_order.status == new_order.status, 'status should match' - assert new_order.quantity == new_order.quantity, 'quantity should match' - assert new_order.shipDate == new_order.shipDate, 'shipDate should match' - -if __name__ == "__main__": - unittest.main() diff --git a/samples/client/petstore/python3/tests/UserApiTest.py b/samples/client/petstore/python3/tests/UserApiTest.py deleted file mode 100644 index 52d9f31b7035..000000000000 --- a/samples/client/petstore/python3/tests/UserApiTest.py +++ /dev/null @@ -1,229 +0,0 @@ -#!/usr/bin/env python -import sys -import unittest -import random -import urllib - -from BaseApiTest import BaseApiTest - -sys.path = ['./'] + sys.path -from petstore import * -from petstore.models import * - - -def randomString(): - return str(randomInt()) - - -def randomInt(): - return random.randint(1000, 100000) - - -class UserApiTest(BaseApiTest): - - @classmethod - def setUpClass(cls): - alpahbet = list('ABCDEFGHIJKLMNOPQRSTUVWXYZ') - random.shuffle(alpahbet) - cls.randomUsername1 = ''.join(alpahbet) - random.shuffle(alpahbet) - cls.randomUsername2 = ''.join(alpahbet) - random.shuffle(alpahbet) - cls.randomUsername3 = ''.join(alpahbet) - random.shuffle(alpahbet) - cls.randomUsername4 = ''.join(alpahbet) - random.shuffle(alpahbet) - cls.randomUsername5 = ''.join(alpahbet) - - def testCreateUsersWithArrayInput(self): - - user = User.User() - - user.id = randomInt() - user.lastName = randomString() - user.username = self.randomUsername1 - user.phone = randomString() - user.email = randomString() - user.userStatus = int(randomString()) - user.firstName = randomString() - user.password = randomString() - - otherUser = User.User() - - otherUser.id = randomInt() - otherUser.lastName = randomString() - otherUser.username = self.randomUsername2 - otherUser.phone = randomString() - otherUser.email = randomString() - otherUser.userStatus = int(randomString()) - otherUser.firstName = randomString() - otherUser.password = randomString() - - users = [user, otherUser] - self.userApi.createUsersWithArrayInput(users) - - newUser = self.userApi.getUserByName(self.randomUsername1) - - assert newUser.id == user.id, 'id matches user' - assert newUser.lastName == user.lastName, 'lastName matches user' - assert newUser.username == user.username, 'username matches user' - assert newUser.phone == user.phone, 'phone matches user' - assert newUser.email == user.email, 'email matches user' - assert newUser.userStatus == user.userStatus, 'status matches user' - assert newUser.firstName == user.firstName, 'firstName matches user' - assert newUser.password == user.password, 'password matches user' - - newUser = self.userApi.getUserByName(self.randomUsername2) - - assert newUser.id == otherUser.id, 'id matches user' - assert newUser.lastName == otherUser.lastName, 'lastName matches user' - assert newUser.username == otherUser.username, 'username matches user' - assert newUser.phone == otherUser.phone, 'phone matches user' - assert newUser.email == otherUser.email, 'email matches user' - assert newUser.userStatus == otherUser.userStatus, 'status matches user' - assert newUser.firstName == otherUser.firstName, 'firstName matches user' - assert newUser.password == otherUser.password, 'password matches user' - - def testCreateUsersWithListInput(self): - - user = User.User() - - user.id = randomInt() - user.lastName = randomString() - user.username = self.randomUsername3 - user.phone = randomString() - user.email = randomString() - user.userStatus = int(randomString()) - user.firstName = randomString() - user.password = randomString() - - otherUser = User.User() - - otherUser.id = randomInt() - otherUser.lastName = randomString() - otherUser.username = self.randomUsername4 - otherUser.phone = randomString() - otherUser.email = randomString() - otherUser.userStatus = int(randomString()) - otherUser.firstName = randomString() - otherUser.password = randomString() - - users = [user, otherUser] - self.userApi.createUsersWithListInput(users) - - newUser = self.userApi.getUserByName(self.randomUsername3) - - assert newUser.id == user.id, 'id matches user' - assert newUser.lastName == user.lastName, 'lastName matches user' - assert newUser.username == user.username, 'username matches user' - assert newUser.phone == user.phone, 'phone matches user' - assert newUser.email == user.email, 'email matches user' - assert newUser.userStatus == user.userStatus, 'status matches user' - assert newUser.firstName == user.firstName, 'firstName matches user' - assert newUser.password == user.password, 'password matches user' - - newUser = self.userApi.getUserByName(self.randomUsername4) - - assert newUser.id == otherUser.id, 'id matches user' - assert newUser.lastName == otherUser.lastName, 'lastName matches user' - assert newUser.username == otherUser.username, 'username matches user' - assert newUser.phone == otherUser.phone, 'phone matches user' - assert newUser.email == otherUser.email, 'email matches user' - assert newUser.userStatus == otherUser.userStatus, 'status matches user' - assert newUser.firstName == otherUser.firstName, 'firstName matches user' - assert newUser.password == otherUser.password, 'password matches user' - - def testCreateUser(self): - - user = User.User() - - user.id = randomInt() - user.lastName = randomString() - user.username = self.randomUsername5 - user.phone = randomString() - user.email = randomString() - user.userStatus = int(randomString()) - user.firstName = randomString() - user.password = randomString() - - self.userApi.createUser(user) - - newUser = self.userApi.getUserByName(self.randomUsername5) - - assert newUser.id, user.id - assert newUser.lastName, user.lastName - assert newUser.username, user.username - assert newUser.phone, user.phone - assert newUser.email, user.email - assert newUser.userStatus, user.userStatus - assert newUser.firstName, user.firstName - assert newUser.password, user.password - - def testUpdateUser(self): - - user = User.User() - username = randomString() - user.id = randomInt() - user.lastName = randomString() - user.username = username - user.phone = randomString() - user.email = randomString() - user.userStatus = int(randomString()) - user.firstName = randomString() - user.password = randomString() - - self.userApi.createUser(user) - - user = self.userApi.getUserByName(username) - - user.lastName = randomString() - user.phone = randomString() - user.email = randomString() - user.userStatus = int(randomString()) - user.firstName = randomString() - user.password = randomString() - - self.userApi.updateUser(username, user) - - updatedUser = self.userApi.getUserByName(username) - - assert updatedUser.lastName == user.lastName, 'should match lastName' - assert updatedUser.username == user.username, 'should match username' - assert updatedUser.phone == user.phone, 'should match phone' - assert updatedUser.email == user.email, 'should match email' - assert updatedUser.userStatus == user.userStatus, 'should match status' - assert updatedUser.firstName == user.firstName, 'should match firstName' - assert updatedUser.password == user.password, 'should match password' - - def testDeleteUser(self): - - user = User.User() - username = randomString() - user.username = username - - self.userApi.createUser(user) - - self.userApi.deleteUser(username) - - userGone = False - - try: - self.userApi.getUserByName(username) - except urllib.request.HTTPError: - userGone = True - - assert userGone, 'user should be deleted' - - def testLoginUser(self): - - res = self.userApi.loginUser("anyusername", "anypassword") - - assert res[:23] == "logged in user session:", 'should get session' - - def testLogoutUser(self): - # We just want to make sure there are no errors in this test. - self.userApi.logoutUser() - - -if __name__ == "__main__": - unittest.main() From c203854254af4a44e8e59709fb691d4df1353669 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 20 Sep 2015 22:59:56 +0800 Subject: [PATCH 104/219] fix parameter name for typescript-node using baseName --- .../main/resources/TypeScript-node/api.mustache | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 5f6428ce7e2a..eab02d5c4d15 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -160,37 +160,35 @@ export class {{classname}} { var path = this.url + this.basePath + '{{path}}'; {{#pathParams}} - path = path.replace('{' + '{{paramName}}' + '}', String({{paramName}})); + path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); {{/pathParams}} var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; -{{#allParams}} -{{#required}} +{{#allParams}}{{#required}} // verify required parameter '{{paramName}}' is set if (!{{paramName}}) { throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } -{{/required}} -{{/allParams}} +{{/required}}{{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { - queryParameters['{{paramName}}'] = {{paramName}}; + queryParameters['{{baseName}}'] = {{paramName}}; } {{/queryParams}} {{#headerParams}} - headerParams['{{paramName}}'] = {{paramName}}; + headerParams['{{baseName}}'] = {{paramName}}; {{/headerParams}} var useFormData = false; {{#formParams}} if ({{paramName}} !== undefined) { - formParams['{{paramName}}'] = {{paramName}}; + formParams['{baseName}}'] = {{paramName}}; } {{#isFile}} useFormData = true; From 8733be9ac95364221bb6b233ef7d9294adc1e6fb Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 20 Sep 2015 23:06:29 +0800 Subject: [PATCH 105/219] update sample, fix formData basename --- .../resources/TypeScript-node/api.mustache | 2 +- .../client/petstore/typescript-node/api.ts | 39 ++++++++++++++++--- 2 files changed, 35 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index eab02d5c4d15..95373b21da24 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -188,7 +188,7 @@ export class {{classname}} { {{#formParams}} if ({{paramName}} !== undefined) { - formParams['{baseName}}'] = {{paramName}}; + formParams['{{baseName}}'] = {{paramName}}; } {{#isFile}} useFormData = true; diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 52a3d7f97064..0cdad04ba385 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -149,6 +149,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -194,6 +195,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -239,6 +241,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -284,6 +287,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + if (username !== undefined) { queryParameters['username'] = username; } @@ -336,6 +340,7 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -382,11 +387,13 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); @@ -433,11 +440,13 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -485,11 +494,13 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -559,6 +570,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -606,6 +618,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -653,6 +666,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + if (status !== undefined) { queryParameters['status'] = status; } @@ -703,6 +717,7 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + if (tags !== undefined) { queryParameters['tags'] = tags; } @@ -755,11 +770,13 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); @@ -810,19 +827,21 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } + var useFormData = false; if (name !== undefined) { - formParams['name'] = name; + formParams['{baseName}}'] = name; } if (status !== undefined) { - formParams['status'] = status; + formParams['{baseName}}'] = status; } var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -871,12 +890,14 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - headerParams['apiKey'] = apiKey; + + headerParams['api_key'] = apiKey; var useFormData = false; @@ -926,19 +947,21 @@ export class PetApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } + var useFormData = false; if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = additionalMetadata; + formParams['{baseName}}'] = additionalMetadata; } if (file !== undefined) { - formParams['file'] = file; + formParams['{baseName}}'] = file; } useFormData = true; @@ -1011,6 +1034,7 @@ export class StoreApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); @@ -1057,6 +1081,7 @@ export class StoreApi { var headerParams: any = {}; var formParams: any = {}; + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); @@ -1104,11 +1129,13 @@ export class StoreApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); @@ -1155,11 +1182,13 @@ export class StoreApi { var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); } + var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); From b1728aed7c140f626dc9862c554c976fcbb62568 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 20 Sep 2015 23:11:46 +0800 Subject: [PATCH 106/219] update sample for typescript-node --- samples/client/petstore/typescript-node/api.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 0cdad04ba385..0723e067be4e 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -837,11 +837,11 @@ export class PetApi { var useFormData = false; if (name !== undefined) { - formParams['{baseName}}'] = name; + formParams['name'] = name; } if (status !== undefined) { - formParams['{baseName}}'] = status; + formParams['status'] = status; } var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -957,11 +957,11 @@ export class PetApi { var useFormData = false; if (additionalMetadata !== undefined) { - formParams['{baseName}}'] = additionalMetadata; + formParams['additionalMetadata'] = additionalMetadata; } if (file !== undefined) { - formParams['{baseName}}'] = file; + formParams['file'] = file; } useFormData = true; From 956624f1a4470584fffc4088e5948471db8421e7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 20 Sep 2015 23:15:02 +0800 Subject: [PATCH 107/219] remove extra line break for typescript-node --- .../src/main/resources/TypeScript-node/api.mustache | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 95373b21da24..6528a5d3a22c 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -172,7 +172,6 @@ export class {{classname}} { if (!{{paramName}}) { throw new Error('Missing required parameter {{paramName}} when calling {{nickname}}'); } - {{/required}}{{/allParams}} {{#queryParams}} if ({{paramName}} !== undefined) { From 2b06a81a52ce7f6bac92b7057bfc2dfa50846a21 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 20 Sep 2015 23:17:04 +0800 Subject: [PATCH 108/219] remove extra line break in typescript-node sample code --- samples/client/petstore/typescript-node/api.ts | 9 --------- 1 file changed, 9 deletions(-) diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 0723e067be4e..148782a4000a 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -393,7 +393,6 @@ export class UserApi { throw new Error('Missing required parameter username when calling getUserByName'); } - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: User; }>(); @@ -446,7 +445,6 @@ export class UserApi { throw new Error('Missing required parameter username when calling updateUser'); } - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -500,7 +498,6 @@ export class UserApi { throw new Error('Missing required parameter username when calling deleteUser'); } - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -776,7 +773,6 @@ export class PetApi { throw new Error('Missing required parameter petId when calling getPetById'); } - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); @@ -833,7 +829,6 @@ export class PetApi { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } - var useFormData = false; if (name !== undefined) { @@ -896,7 +891,6 @@ export class PetApi { throw new Error('Missing required parameter petId when calling deletePet'); } - headerParams['api_key'] = apiKey; var useFormData = false; @@ -953,7 +947,6 @@ export class PetApi { throw new Error('Missing required parameter petId when calling uploadFile'); } - var useFormData = false; if (additionalMetadata !== undefined) { @@ -1135,7 +1128,6 @@ export class StoreApi { throw new Error('Missing required parameter orderId when calling getOrderById'); } - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); @@ -1188,7 +1180,6 @@ export class StoreApi { throw new Error('Missing required parameter orderId when calling deleteOrder'); } - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); From 6dcaa890cff06badcff86596f0aac3efb0193c8f Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 21 Sep 2015 17:29:26 +0800 Subject: [PATCH 109/219] Improvements on enum var name in Java client * Place each enum var in a separate line * Truncate common prefix when present --- .../codegen/languages/JavaClientCodegen.java | 35 ++++++++++++++++--- .../main/resources/Java/enumClass.mustache | 3 +- .../java/io/swagger/client/model/Order.java | 6 ++-- .../java/io/swagger/client/model/Pet.java | 6 ++-- 4 files changed, 40 insertions(+), 10 deletions(-) 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 1c9118189384..60309c0e0947 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 @@ -351,20 +351,34 @@ public Map postProcessModels(Map objs) { Map allowableValues = var.allowableValues; // handle ArrayProperty - if(var.items != null) { + if (var.items != null) { allowableValues = var.items.allowableValues; } - if (allowableValues == null) + if (allowableValues == null) { continue; + } List values = (List) allowableValues.get("values"); - // put "enumVars" map into `allowableValues", including `name` and `value` - if (values == null) + if (values == null) { continue; + } + + // put "enumVars" map into `allowableValues", including `name` and `value` List> enumVars = new ArrayList>(); + String commonPrefix = findCommonPrefixOfVars(values); + int truncateIdx = "".equals(commonPrefix) ? 0 : commonPrefix.length(); for (String value : values) { Map enumVar = new HashMap(); - enumVar.put("name", toVarName(value.toUpperCase())); + String enumName; + if (truncateIdx == 0) { + enumName = value; + } else { + enumName = value.substring(truncateIdx); + if ("".equals(enumName)) { + enumName = value; + } + } + enumVar.put("name", toEnumVarName(enumName)); enumVar.put("value", value); enumVars.add(enumVar); } @@ -374,6 +388,17 @@ public Map postProcessModels(Map objs) { return objs; } + private String findCommonPrefixOfVars(List vars) { + String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); + // exclude trailing characters that should be part of a valid variable + // e.g. ["status-on", "status-off"] => "status-" (not "status-o") + return prefix.replaceAll("[a-zA-Z0-9]+\\z", ""); + } + + private String toEnumVarName(String value) { + return value.replaceAll("\\W+", "_").toUpperCase(); + } + private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { // This generator uses inline classes to define enums, which breaks when // dealing with models that have subTypes. To clean this up, we will analyze diff --git a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache index 68fc07aae7d7..fd8e8442254a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/enumClass.mustache @@ -1,5 +1,6 @@ public enum {{datatypeWithEnum}} { - {{#allowableValues}}{{#enumVars}}{{name}}("{{value}}"){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + {{#allowableValues}}{{#enumVars}}{{name}}("{{value}}"){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} private String value; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index 16855721cd0d..35757b9101be 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -10,7 +10,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-21T17:24:54.566+08:00") public class Order { private Long id = null; @@ -19,7 +19,9 @@ public class Order { private Date shipDate = null; public enum StatusEnum { - PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index 9f06fc171aad..f346800528d5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -12,7 +12,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-21T17:24:54.566+08:00") public class Pet { private Long id = null; @@ -22,7 +22,9 @@ public class Pet { private List tags = new ArrayList(); public enum StatusEnum { - AVAILABLE("available"), PENDING("pending"), SOLD("sold"); + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; From bcbf9c54c7dc1c4f38daabc34d22201ea160cea4 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 21 Sep 2015 18:11:58 +0800 Subject: [PATCH 110/219] Remove unnecessary checking of empty string --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 60309c0e0947..b1beb1ae65c6 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 @@ -366,7 +366,7 @@ public Map postProcessModels(Map objs) { // put "enumVars" map into `allowableValues", including `name` and `value` List> enumVars = new ArrayList>(); String commonPrefix = findCommonPrefixOfVars(values); - int truncateIdx = "".equals(commonPrefix) ? 0 : commonPrefix.length(); + int truncateIdx = commonPrefix.length(); for (String value : values) { Map enumVar = new HashMap(); String enumName; From a6df340cdc80f71cc4bdb88aa7174013a5d41c5c Mon Sep 17 00:00:00 2001 From: Evan Fossier Date: Mon, 21 Sep 2015 17:34:23 -0700 Subject: [PATCH 111/219] Expose readOnly attribute on model properties to templates, can now use isReadOnly property in model templates --- .../src/main/java/io/swagger/codegen/CodegenProperty.java | 1 + .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 1 + 2 files changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 076d6cbfbdbe..9960c590a7d3 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -32,6 +32,7 @@ public class CodegenProperty { public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; public boolean isEnum; + public Boolean isReadOnly = false; public List _enum; public Map allowableValues; public CodegenProperty items; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 1422b1c36a0c..433f4627e9b5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -628,6 +628,7 @@ public CodegenProperty fromProperty(String name, Property p) { property.example = p.getExample(); property.defaultValue = toDefaultValue(p); property.jsonSchema = Json.pretty(p); + property.isReadOnly = p.getReadOnly(); String type = getSwaggerType(p); if (p instanceof AbstractNumericProperty) { From 0622838947cc909039c2f0d7f7d1aaeb5663e5f8 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 22 Sep 2015 09:29:48 +0800 Subject: [PATCH 112/219] Fixed issues about logging in objc client --- .../resources/objc/ApiClient-body.mustache | 7 +++-- .../objc/SwaggerClient/SWGApiClient.m | 27 ++++++++++++++----- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 42cf8768c99f..07e000450d07 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -65,6 +65,10 @@ static void (^reachabilityChangeBlock)(int); error:(NSError*)error { {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + if (!config.debug) { + return; + } + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], @@ -74,8 +78,7 @@ static void (^reachabilityChangeBlock)(int); [config.loggingFileHanlder seekToEndOfFile]; [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; } - - if ([[{{classPrefix}}Configuration sharedConfig] debug]){ + else { NSLog(@"%@", message); } } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 8767498dcafc..8197569e0b50 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -65,6 +65,10 @@ - (void)logResponse:(AFHTTPRequestOperation *)operation error:(NSError*)error { SWGConfiguration *config = [SWGConfiguration sharedConfig]; + if (!config.debug) { + return; + } + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], @@ -74,8 +78,9 @@ - (void)logResponse:(AFHTTPRequestOperation *)operation [config.loggingFileHanlder seekToEndOfFile]; [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; } - - NSLog(@"%@", message); + else { + NSLog(@"%@", message); + } } #pragma mark - Cache Methods @@ -177,8 +182,9 @@ +(NSNumber*) nextRequestId { +(NSNumber*) queueRequest { NSNumber* requestId = [SWGApiClient nextRequestId]; - if([[SWGConfiguration sharedConfig] debug]) + if([[SWGConfiguration sharedConfig] debug]) { NSLog(@"added %@ to request queue", requestId); + } [queuedRequests addObject:requestId]; return requestId; } @@ -198,8 +204,9 @@ -(Boolean) executeRequestWithId:(NSNumber*) requestId { }]; if(matchingItems.count == 1) { - if([[SWGConfiguration sharedConfig] debug]) + if([[SWGConfiguration sharedConfig] debug]){ NSLog(@"removing request id %@", requestId); + } [queuedRequests removeObject:requestId]; return YES; } @@ -577,15 +584,21 @@ -(NSNumber*) requestWithCompletionBlock: (NSString*) path hasHeaderParams = true; } if(offlineState) { - NSLog(@"%@ cache forced", resourcePath); + if ([[SWGConfiguration sharedConfig] debug]){ + NSLog(@"%@ cache forced", resourcePath); + } [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", resourcePath); + if ([[SWGConfiguration sharedConfig] debug]){ + NSLog(@"%@ cache enabled", resourcePath); + } [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - NSLog(@"%@ cache disabled", resourcePath); + if ([[SWGConfiguration sharedConfig] debug]){ + NSLog(@"%@ cache disabled", resourcePath); + } [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } From 9cbf2d370762fc69ce434c916e8dfa200b94e2e2 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 22 Sep 2015 11:32:25 +0800 Subject: [PATCH 113/219] Fix #1145: sanitize model name in PHP client --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 2 ++ 1 file changed, 2 insertions(+) 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 ac2cddfefa98..3a43e91c777a 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 @@ -330,6 +330,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { + name = sanitizeName(name); + // model name cannot use reserved keyword if (reservedWords.contains(name)) { escapeReservedWord(name); // e.g. return => _return From 09add2d87183a86486c6203ad1bf2f5e46c7eba1 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 22 Sep 2015 14:03:27 +0800 Subject: [PATCH 114/219] Fix test failure by allowing backslash in model name --- .../java/io/swagger/codegen/languages/PhpClientCodegen.java | 3 ++- 1 file changed, 2 insertions(+), 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 3a43e91c777a..538a5c494a61 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 @@ -330,7 +330,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - name = sanitizeName(name); + // Note: backslash ("\\") is allowed for e.g. "\\DateTime" + name = name.replaceAll("[^\\w\\\\]+", "_"); // model name cannot use reserved keyword if (reservedWords.contains(name)) { From 1cd81416459c48d09197e5cf54af47b65189dbb4 Mon Sep 17 00:00:00 2001 From: Laurent Van der Linden Date: Tue, 22 Sep 2015 08:37:49 +0200 Subject: [PATCH 115/219] implement form parameter support using Angular $httpParamSerializer --- .../io/swagger/codegen/CodegenOperation.java | 9 +++++++++ .../resources/TypeScript-Angular/api.mustache | 19 ++++++++++++++++--- 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 6eae2c6f0f58..373c5b2b7857 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -77,4 +77,13 @@ public boolean getHasPathParams() { return nonempty(pathParams); } + /** + * Check if there's at least one form parameter + * + * @return true if any form parameter exists, false otherwise + */ + public boolean getHasFormParams() { + return nonempty(formParams); + } + } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index f08e66333755..80ed286cea10 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -14,9 +14,9 @@ module {{package}} { export class {{classname}} { private basePath = '{{basePath}}'; - static $inject: string[] = ['$http']; + static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string) { + constructor(private $http: ng.IHttpService, private $httpParamSerializer: (any) => any, basePath?: string) { if (basePath) { this.basePath = basePath; } @@ -32,7 +32,10 @@ module {{package}} { {{/pathParams}} var queryParameters: any = {}; var headerParams: any = {}; +{{#hasFormParams}} + var formParams: any = {}; +{{/hasFormParams}} {{#allParams}} {{#required}} // verify required parameter '{{paramName}}' is set @@ -52,12 +55,22 @@ module {{package}} { headerParams['{{baseName}}'] = {{paramName}}; {{/headerParams}} +{{#hasFormParams}} + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + +{{/hasFormParams}} +{{#formParams}} + formParams['{{baseName}}'] = {{paramName}}; + +{{/formParams}} var httpRequestParams: any = { method: '{{httpMethod}}', url: path, - json: true, + json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, {{#bodyParam}}data: {{paramName}}, {{/bodyParam}} + {{#hasFormParams}}data: this.$httpParamSerializer(formParams), + {{/hasFormParams}} params: queryParameters, headers: headerParams }; From 61690d625f28d89196c1bd3e86667f4d287a2ad0 Mon Sep 17 00:00:00 2001 From: Laurent Van der Linden Date: Tue, 22 Sep 2015 09:20:52 +0200 Subject: [PATCH 116/219] change the constructor signature to be backwards compatible update petstore samples for angular and node --- .../resources/TypeScript-Angular/api.mustache | 2 +- .../typescript-angular/API/Client/PetApi.ts | 40 ++- .../typescript-angular/API/Client/StoreApi.ts | 12 +- .../typescript-angular/API/Client/UserApi.ts | 20 +- .../typescript-angular/API/Client/api.d.ts | 2 +- .../client/petstore/typescript-node/api.ts | 278 ++++++++---------- 6 files changed, 176 insertions(+), 178 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 80ed286cea10..233ead8bee48 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -16,7 +16,7 @@ module {{package}} { static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, private $httpParamSerializer: (any) => any, basePath?: string) { + constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { if (basePath) { this.basePath = basePath; } diff --git a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts index 3189f6166e42..b8eb8c3ae12e 100644 --- a/samples/client/petstore/typescript-angular/API/Client/PetApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/PetApi.ts @@ -8,9 +8,9 @@ module API.Client { export class PetApi { private basePath = 'http://petstore.swagger.io/v2'; - static $inject: string[] = ['$http']; + static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string) { + constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { if (basePath) { this.basePath = basePath; } @@ -21,13 +21,13 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'PUT', url: path, json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -48,13 +48,13 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'POST', url: path, json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -75,7 +75,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - if (status !== undefined) { queryParameters['status'] = status; } @@ -85,6 +84,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -105,7 +105,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - if (tags !== undefined) { queryParameters['tags'] = tags; } @@ -115,6 +114,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -137,7 +137,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling getPetById'); @@ -148,6 +147,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -170,16 +170,25 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling updatePetWithForm'); } + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['name'] = name; + + formParams['status'] = status; + var httpRequestParams: any = { method: 'POST', url: path, - json: true, + json: false, + + data: this.$httpParamSerializer(formParams), params: queryParameters, headers: headerParams @@ -203,19 +212,19 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling deletePet'); } - headerParams['apiKey'] = apiKey; + headerParams['api_key'] = apiKey; var httpRequestParams: any = { method: 'DELETE', url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -238,16 +247,25 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; + var formParams: any = {}; // verify required parameter 'petId' is set if (!petId) { throw new Error('Missing required parameter petId when calling uploadFile'); } + headerParams['Content-Type'] = 'application/x-www-form-urlencoded'; + + formParams['additionalMetadata'] = additionalMetadata; + + formParams['file'] = file; + var httpRequestParams: any = { method: 'POST', url: path, - json: true, + json: false, + + data: this.$httpParamSerializer(formParams), params: queryParameters, headers: headerParams diff --git a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts index 443ea5d0c589..739f6039e6c5 100644 --- a/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/StoreApi.ts @@ -8,9 +8,9 @@ module API.Client { export class StoreApi { private basePath = 'http://petstore.swagger.io/v2'; - static $inject: string[] = ['$http']; + static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string) { + constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { if (basePath) { this.basePath = basePath; } @@ -21,12 +21,12 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'GET', url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -47,13 +47,13 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'POST', url: path, json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -76,7 +76,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling getOrderById'); @@ -87,6 +86,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -109,7 +109,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'orderId' is set if (!orderId) { throw new Error('Missing required parameter orderId when calling deleteOrder'); @@ -120,6 +119,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts index aaf2ef81bb15..26ebd693db94 100644 --- a/samples/client/petstore/typescript-angular/API/Client/UserApi.ts +++ b/samples/client/petstore/typescript-angular/API/Client/UserApi.ts @@ -8,9 +8,9 @@ module API.Client { export class UserApi { private basePath = 'http://petstore.swagger.io/v2'; - static $inject: string[] = ['$http']; + static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string) { + constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { if (basePath) { this.basePath = basePath; } @@ -21,13 +21,13 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'POST', url: path, json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -48,13 +48,13 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'POST', url: path, json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -75,13 +75,13 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'POST', url: path, json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -102,7 +102,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - if (username !== undefined) { queryParameters['username'] = username; } @@ -116,6 +115,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -136,12 +136,12 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - var httpRequestParams: any = { method: 'GET', url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -164,7 +164,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); @@ -175,6 +174,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; @@ -197,7 +197,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); @@ -209,6 +208,7 @@ module API.Client { json: true, data: body, + params: queryParameters, headers: headerParams }; @@ -231,7 +231,6 @@ module API.Client { var queryParameters: any = {}; var headerParams: any = {}; - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); @@ -242,6 +241,7 @@ module API.Client { url: path, json: true, + params: queryParameters, headers: headerParams }; diff --git a/samples/client/petstore/typescript-angular/API/Client/api.d.ts b/samples/client/petstore/typescript-angular/API/Client/api.d.ts index 19c60623dc94..46123a07ad33 100644 --- a/samples/client/petstore/typescript-angular/API/Client/api.d.ts +++ b/samples/client/petstore/typescript-angular/API/Client/api.d.ts @@ -5,5 +5,5 @@ /// /// -/// /// +/// diff --git a/samples/client/petstore/typescript-node/api.ts b/samples/client/petstore/typescript-node/api.ts index 148782a4000a..742169a608e6 100644 --- a/samples/client/petstore/typescript-node/api.ts +++ b/samples/client/petstore/typescript-node/api.ts @@ -149,7 +149,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -195,7 +194,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -241,7 +239,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -287,7 +284,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - if (username !== undefined) { queryParameters['username'] = username; } @@ -340,7 +336,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - var useFormData = false; var deferred = promise.defer<{ response: http.ClientResponse; }>(); @@ -387,7 +382,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling getUserByName'); @@ -439,7 +433,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling updateUser'); @@ -492,7 +485,6 @@ export class UserApi { var headerParams: any = {}; var formParams: any = {}; - // verify required parameter 'username' is set if (!username) { throw new Error('Missing required parameter username when calling deleteUser'); @@ -535,7 +527,7 @@ export class UserApi { return deferred.promise; } } -export class PetApi { +export class StoreApi { private basePath = 'http://petstore.swagger.io/v2'; public authentications = { 'default': new VoidAuth(), @@ -560,28 +552,26 @@ export class PetApi { this.authentications.api_key.apiKey = key; } - public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; + public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { + var path = this.url + this.basePath + '/store/inventory'; var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); var requestOptions: request.Options = { - method: 'PUT', + method: 'GET', qs: queryParameters, headers: headerParams, uri: path, json: true, - body: body, } - this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(requestOptions); this.authentications.default.applyToRequest(requestOptions); @@ -608,17 +598,16 @@ export class PetApi { return deferred.promise; } - public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet'; + public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order'; var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); var requestOptions: request.Options = { method: 'POST', @@ -629,8 +618,6 @@ export class PetApi { body: body, } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -656,21 +643,23 @@ export class PetApi { return deferred.promise; } - public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByStatus'; + public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - if (status !== undefined) { - queryParameters['status'] = status; + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling getOrderById'); } var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); var requestOptions: request.Options = { method: 'GET', @@ -680,8 +669,6 @@ export class PetApi { json: true, } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -707,32 +694,32 @@ export class PetApi { return deferred.promise; } - public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { - var path = this.url + this.basePath + '/pet/findByTags'; + public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/store/order/{orderId}'; + + path = path.replace('{' + 'orderId' + '}', String(orderId)); var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - if (tags !== undefined) { - queryParameters['tags'] = tags; + // verify required parameter 'orderId' is set + if (!orderId) { + throw new Error('Missing required parameter orderId when calling deleteOrder'); } var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; }>(); var requestOptions: request.Options = { - method: 'GET', + method: 'DELETE', qs: queryParameters, headers: headerParams, uri: path, json: true, } - this.authentications.petstore_auth.applyToRequest(requestOptions); - this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -757,36 +744,52 @@ export class PetApi { return deferred.promise; } +} +export class PetApi { + private basePath = 'http://petstore.swagger.io/v2'; + public authentications = { + 'default': new VoidAuth(), + 'api_key': new ApiKeyAuth('header', 'api_key'), + 'petstore_auth': new OAuth(), + } - public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { - var path = this.url + this.basePath + '/pet/{petId}'; + constructor(url: string, basePath?: string); + constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername + } + } + } - path = path.replace('{' + 'petId' + '}', String(petId)); + set apiKey(key: string) { + this.authentications.api_key.apiKey = key; + } + + public updatePet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling getPetById'); - } - var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; }>(); var requestOptions: request.Options = { - method: 'GET', + method: 'PUT', qs: queryParameters, headers: headerParams, uri: path, json: true, + body: body, } - this.authentications.api_key.applyToRequest(requestOptions); - this.authentications.petstore_auth.applyToRequest(requestOptions); this.authentications.default.applyToRequest(requestOptions); @@ -814,31 +817,15 @@ export class PetApi { return deferred.promise; } - public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - path = path.replace('{' + 'petId' + '}', String(petId)); + public addPet (body?: Pet) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet'; var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling updatePetWithForm'); - } - var useFormData = false; - if (name !== undefined) { - formParams['name'] = name; - } - - if (status !== undefined) { - formParams['status'] = status; - } - var deferred = promise.defer<{ response: http.ClientResponse; }>(); var requestOptions: request.Options = { @@ -847,6 +834,7 @@ export class PetApi { headers: headerParams, uri: path, json: true, + body: body, } this.authentications.petstore_auth.applyToRequest(requestOptions); @@ -876,29 +864,23 @@ export class PetApi { return deferred.promise; } - public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}'; - - path = path.replace('{' + 'petId' + '}', String(petId)); + public findPetsByStatus (status?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByStatus'; var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling deletePet'); + if (status !== undefined) { + queryParameters['status'] = status; } - headerParams['api_key'] = apiKey; - var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); var requestOptions: request.Options = { - method: 'DELETE', + method: 'GET', qs: queryParameters, headers: headerParams, uri: path, @@ -932,36 +914,23 @@ export class PetApi { return deferred.promise; } - public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; - - path = path.replace('{' + 'petId' + '}', String(petId)); + public findPetsByTags (tags?: Array) : Promise<{ response: http.ClientResponse; body: Array; }> { + var path = this.url + this.basePath + '/pet/findByTags'; var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - // verify required parameter 'petId' is set - if (!petId) { - throw new Error('Missing required parameter petId when calling uploadFile'); + if (tags !== undefined) { + queryParameters['tags'] = tags; } var useFormData = false; - if (additionalMetadata !== undefined) { - formParams['additionalMetadata'] = additionalMetadata; - } - - if (file !== undefined) { - formParams['file'] = file; - } - useFormData = true; - - var deferred = promise.defer<{ response: http.ClientResponse; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; body: Array; }>(); var requestOptions: request.Options = { - method: 'POST', + method: 'GET', qs: queryParameters, headers: headerParams, uri: path, @@ -994,43 +963,24 @@ export class PetApi { return deferred.promise; } -} -export class StoreApi { - private basePath = 'http://petstore.swagger.io/v2'; - public authentications = { - 'default': new VoidAuth(), - 'api_key': new ApiKeyAuth('header', 'api_key'), - 'petstore_auth': new OAuth(), - } - - constructor(url: string, basePath?: string); - constructor(private url: string, basePathOrUsername: string, password?: string, basePath?: string) { - if (password) { - if (basePath) { - this.basePath = basePath; - } - } else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername - } - } - } - set apiKey(key: string) { - this.authentications.api_key.apiKey = key; - } + public getPetById (petId: number) : Promise<{ response: http.ClientResponse; body: Pet; }> { + var path = this.url + this.basePath + '/pet/{petId}'; - public getInventory () : Promise<{ response: http.ClientResponse; body: { [key: string]: number; }; }> { - var path = this.url + this.basePath + '/store/inventory'; + path = path.replace('{' + 'petId' + '}', String(petId)); var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling getPetById'); + } var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: { [key: string]: number; }; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; body: Pet; }>(); var requestOptions: request.Options = { method: 'GET', @@ -1040,6 +990,8 @@ export class StoreApi { json: true, } + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.api_key.applyToRequest(requestOptions); this.authentications.default.applyToRequest(requestOptions); @@ -1067,17 +1019,31 @@ export class StoreApi { return deferred.promise; } - public placeOrder (body?: Order) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order'; + public updatePetWithForm (petId: string, name?: string, status?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; + + path = path.replace('{' + 'petId' + '}', String(petId)); var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling updatePetWithForm'); + } var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + if (name !== undefined) { + formParams['name'] = name; + } + + if (status !== undefined) { + formParams['status'] = status; + } + + var deferred = promise.defer<{ response: http.ClientResponse; }>(); var requestOptions: request.Options = { method: 'POST', @@ -1085,9 +1051,10 @@ export class StoreApi { headers: headerParams, uri: path, json: true, - body: body, } + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1113,33 +1080,36 @@ export class StoreApi { return deferred.promise; } - public getOrderById (orderId: string) : Promise<{ response: http.ClientResponse; body: Order; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; + public deletePet (petId: number, apiKey?: string) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}'; - path = path.replace('{' + 'orderId' + '}', String(orderId)); + path = path.replace('{' + 'petId' + '}', String(petId)); var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling getOrderById'); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling deletePet'); } + headerParams['apiKey'] = apiKey; + var useFormData = false; - var deferred = promise.defer<{ response: http.ClientResponse; body: Order; }>(); + var deferred = promise.defer<{ response: http.ClientResponse; }>(); var requestOptions: request.Options = { - method: 'GET', + method: 'DELETE', qs: queryParameters, headers: headerParams, uri: path, json: true, } + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { @@ -1165,33 +1135,43 @@ export class StoreApi { return deferred.promise; } - public deleteOrder (orderId: string) : Promise<{ response: http.ClientResponse; }> { - var path = this.url + this.basePath + '/store/order/{orderId}'; + public uploadFile (petId: number, additionalMetadata?: string, file?: any) : Promise<{ response: http.ClientResponse; }> { + var path = this.url + this.basePath + '/pet/{petId}/uploadImage'; - path = path.replace('{' + 'orderId' + '}', String(orderId)); + path = path.replace('{' + 'petId' + '}', String(petId)); var queryParameters: any = {}; var headerParams: any = {}; var formParams: any = {}; - - // verify required parameter 'orderId' is set - if (!orderId) { - throw new Error('Missing required parameter orderId when calling deleteOrder'); + // verify required parameter 'petId' is set + if (!petId) { + throw new Error('Missing required parameter petId when calling uploadFile'); } var useFormData = false; + if (additionalMetadata !== undefined) { + formParams['additionalMetadata'] = additionalMetadata; + } + + if (file !== undefined) { + formParams['file'] = file; + } + useFormData = true; + var deferred = promise.defer<{ response: http.ClientResponse; }>(); var requestOptions: request.Options = { - method: 'DELETE', + method: 'POST', qs: queryParameters, headers: headerParams, uri: path, json: true, } + this.authentications.petstore_auth.applyToRequest(requestOptions); + this.authentications.default.applyToRequest(requestOptions); if (Object.keys(formParams).length) { From 4e4e9e78932db872eefa105b9855cadb7210ce94 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 22 Sep 2015 15:57:22 +0800 Subject: [PATCH 117/219] add a CLI option to sort method argument --- .../java/io/swagger/codegen/CodegenConstants.java | 3 +++ .../main/java/io/swagger/codegen/DefaultCodegen.java | 11 ++++++++++- .../php/SwaggerClient-php/lib/Api/UserApi.php | 2 +- .../petstore/php/SwaggerClient-php/lib/ApiClient.php | 7 +++++++ 4 files changed, 21 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java index 9978160b557e..b2ada4a19812 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConstants.java @@ -37,4 +37,7 @@ public class CodegenConstants { public static final String LIBRARY = "library"; public static final String LIBRARY_DESC = "library template (sub-template)"; + public static final String SORT_PARAMS_BY_REQUIRED_FLAG = "sortParamsByRequiredFlag"; + public static final String SORT_PARAMS_BY_REQUIRED_FLAG_DESC = "Sort method arguments to place required parameters before optional parameters. Default: true"; + } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index b7c0f19e0fec..b5c8c1f8be9b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -103,6 +103,10 @@ public void processOpts() { if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { this.setApiPackage((String) additionalProperties.get(CodegenConstants.API_PACKAGE)); } + + if (additionalProperties.containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { + this.setSortParamsByRequiredFlag(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString())); + } } // override with any special post-processing @@ -227,6 +231,10 @@ public void setApiPackage(String apiPackage) { this.apiPackage = apiPackage; } + public void setSortParamsByRequiredFlag(Boolean sortParamsByRequiredFlag) { + this.sortParamsByRequiredFlag = sortParamsByRequiredFlag; + } + public String toApiFilename(String name) { return toApiName(name); } @@ -344,6 +352,7 @@ public DefaultCodegen() { cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC)); } @@ -1033,8 +1042,8 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation } op.bodyParam = bodyParam; op.httpMethod = httpMethod.toUpperCase(); - // move "required" parameters in front of "optional" parameters + // move "required" parameters in front of "optional" parameters if(sortParamsByRequiredFlag) { Collections.sort(allParams, new Comparator() { @Override 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 773181a52fc0..d23731e08ffd 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -409,7 +409,7 @@ public function logoutUser() * * Get user by user name * - * @param string $username The name that needs to be fetched. Use user1 for testing. (required) + * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @return \Swagger\Client\Model\User * @throws \Swagger\Client\ApiException on non-2xx response */ diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index bf4f4e482bf6..20150b7160bb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -48,6 +48,8 @@ class ApiClient public static $PATCH = "PATCH"; public static $POST = "POST"; public static $GET = "GET"; + public static $HEAD = "HEAD"; + public static $OPTIONS = "OPTIONS"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; @@ -170,6 +172,11 @@ public function callApi($resourcePath, $method, $queryParams, $postData, $header if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); + } else if ($method == self::$HEAD) { + curl_setopt($curl, CURLOPT_NOBODY, true); + } else if ($method == self::$OPTIONS) { + curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "OPTIONS"); + curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method == self::$PATCH) { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PATCH"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); From 844cae75b726e08dd0798f9e7cc524f403231231 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 22 Sep 2015 16:32:15 +0800 Subject: [PATCH 118/219] Update debug logging in objc client --- .../resources/objc/ApiClient-body.mustache | 85 ++++++++++--------- .../resources/objc/ApiClient-header.mustache | 9 ++ .../objc/SwaggerClient/SWGApiClient.h | 9 ++ .../objc/SwaggerClient/SWGApiClient.m | 85 ++++++++++--------- .../SwaggerClient/SwaggerClient-Info.plist | 5 ++ 5 files changed, 109 insertions(+), 84 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 07e000450d07..b1e2c3fc8bf4 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -60,20 +60,26 @@ static void (^reachabilityChangeBlock)(int); #pragma mark - Log Methods -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request - error:(NSError*)error { ++ (void)debugLog:(NSString *)method + message:(NSString *)format, ... { {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - if (!config.debug) { return; } - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - operation.responseString]; + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendString:[NSString stringWithFormat:@"%@: ", method]]; + } + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. if (config.loggingFileHanlder) { [config.loggingFileHanlder seekToEndOfFile]; [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; @@ -81,6 +87,20 @@ static void (^reachabilityChangeBlock)(int); else { NSLog(@"%@", message); } + + va_end(args); +} + +- (void)logResponse:(AFHTTPRequestOperation *)operation + forRequest:(NSURLRequest *)request + error:(NSError*)error { + + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + operation.responseString]; + + DebugLog(message); } #pragma mark - Cache Methods @@ -174,17 +194,14 @@ static void (^reachabilityChangeBlock)(int); +(NSNumber*) nextRequestId { @synchronized(self) { long nextId = ++requestId; - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"got id %ld", nextId); + DebugLog(@"got id %ld", nextId); return [NSNumber numberWithLong:nextId]; } } +(NSNumber*) queueRequest { NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; - if([[{{classPrefix}}Configuration sharedConfig] debug]) { - NSLog(@"added %@ to request queue", requestId); - } + DebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; } @@ -204,9 +221,7 @@ static void (^reachabilityChangeBlock)(int); }]; if(matchingItems.count == 1) { - if([[{{classPrefix}}Configuration sharedConfig] debug]){ - NSLog(@"removing request id %@", requestId); - } + DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; } @@ -230,26 +245,22 @@ static void (^reachabilityChangeBlock)(int); reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); [{{classPrefix}}ApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusNotReachable: - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); [{{classPrefix}}ApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusReachableViaWWAN: - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); [{{classPrefix}}ApiClient setOfflineState:false]; break; case AFNetworkReachabilityStatusReachableViaWiFi: - if([[{{classPrefix}}Configuration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); [{{classPrefix}}ApiClient setOfflineState:false]; break; default: @@ -397,9 +408,7 @@ static void (^reachabilityChangeBlock)(int); AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) { if([self executeRequestWithId:requestId]) { - if([[{{classPrefix}}Configuration sharedConfig] debug]) { - [self logResponse:operation forRequest:request error:nil]; - } + [self logResponse:operation forRequest:request error:nil]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); @@ -412,9 +421,7 @@ static void (^reachabilityChangeBlock)(int); userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; } NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if([[{{classPrefix}}Configuration sharedConfig] debug]) - [self logResponse:nil forRequest:request error:augmentedError]; + [self logResponse:nil forRequest:request error:augmentedError]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; @@ -474,9 +481,9 @@ static void (^reachabilityChangeBlock)(int); NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - if ([[{{classPrefix}}Configuration sharedConfig] debug]) { - [self logResponse:nil forRequest:request error:augmentedError]; - } + + [self logResponse:nil forRequest:request error:augmentedError]; + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(nil, augmentedError); @@ -584,21 +591,15 @@ static void (^reachabilityChangeBlock)(int); hasHeaderParams = true; } if(offlineState) { - if ([[{{classPrefix}}Configuration sharedConfig] debug]){ - NSLog(@"%@ cache forced", resourcePath); - } + DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - if ([[{{classPrefix}}Configuration sharedConfig] debug]){ - NSLog(@"%@ cache enabled", resourcePath); - } + DebugLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - if ([[{{classPrefix}}Configuration sharedConfig] debug]){ - NSLog(@"%@ cache disabled", resourcePath); - } + DebugLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 6a9aadfa08b9..212e361bb793 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -24,6 +24,10 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; +/** + * Log debug message macro + */ +#define DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; @interface {{classPrefix}}ApiClient : AFHTTPRequestOperationManager @@ -215,4 +219,9 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; */ - (NSString *) parameterToString: (id) param; +/** + * Log debug message + */ ++(void)debugLog:(NSString *)method message:(NSString *)format, ...; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index c703d8a22d25..b6e6cf57a475 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -28,6 +28,10 @@ */ extern NSString *const SWGResponseObjectErrorKey; +/** + * Log debug message macro + */ +#define DebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; @interface SWGApiClient : AFHTTPRequestOperationManager @@ -219,4 +223,9 @@ extern NSString *const SWGResponseObjectErrorKey; */ - (NSString *) parameterToString: (id) param; +/** + * Log debug message + */ ++(void)debugLog:(NSString *)method message:(NSString *)format, ...; + @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index 8197569e0b50..fc5ca43440dd 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -60,20 +60,26 @@ - (void)setHeaderValue:(NSString*) value #pragma mark - Log Methods -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request - error:(NSError*)error { ++ (void)debugLog:(NSString *)method + message:(NSString *)format, ... { SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (!config.debug) { return; } - NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ - "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", - [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - operation.responseString]; + NSMutableString *message = [NSMutableString stringWithCapacity:1]; + + if (method) { + [message appendString:[NSString stringWithFormat:@"%@: ", method]]; + } + va_list args; + va_start(args, format); + + [message appendString:[[NSString alloc] initWithFormat:format arguments:args]]; + + // If set logging file handler, log into file, + // otherwise log into console. if (config.loggingFileHanlder) { [config.loggingFileHanlder seekToEndOfFile]; [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; @@ -81,6 +87,20 @@ - (void)logResponse:(AFHTTPRequestOperation *)operation else { NSLog(@"%@", message); } + + va_end(args); +} + +- (void)logResponse:(AFHTTPRequestOperation *)operation + forRequest:(NSURLRequest *)request + error:(NSError*)error { + + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + operation.responseString]; + + DebugLog(message); } #pragma mark - Cache Methods @@ -174,17 +194,14 @@ +(unsigned long)requestQueueSize { +(NSNumber*) nextRequestId { @synchronized(self) { long nextId = ++requestId; - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"got id %ld", nextId); + DebugLog(@"got id %ld", nextId); return [NSNumber numberWithLong:nextId]; } } +(NSNumber*) queueRequest { NSNumber* requestId = [SWGApiClient nextRequestId]; - if([[SWGConfiguration sharedConfig] debug]) { - NSLog(@"added %@ to request queue", requestId); - } + DebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; } @@ -204,9 +221,7 @@ -(Boolean) executeRequestWithId:(NSNumber*) requestId { }]; if(matchingItems.count == 1) { - if([[SWGConfiguration sharedConfig] debug]){ - NSLog(@"removing request id %@", requestId); - } + DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; } @@ -230,26 +245,22 @@ - (void) configureCacheReachibility { reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); [SWGApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusNotReachable: - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); [SWGApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusReachableViaWWAN: - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); [SWGApiClient setOfflineState:false]; break; case AFNetworkReachabilityStatusReachableViaWiFi: - if([[SWGConfiguration sharedConfig] debug]) - NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); [SWGApiClient setOfflineState:false]; break; default: @@ -397,9 +408,7 @@ - (void) operationWithCompletionBlock: (NSURLRequest *)request AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id response) { if([self executeRequestWithId:requestId]) { - if([[SWGConfiguration sharedConfig] debug]) { - [self logResponse:operation forRequest:request error:nil]; - } + [self logResponse:operation forRequest:request error:nil]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(response, nil); @@ -412,9 +421,7 @@ - (void) operationWithCompletionBlock: (NSURLRequest *)request userInfo[SWGResponseObjectErrorKey] = operation.responseObject; } NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if([[SWGConfiguration sharedConfig] debug]) - [self logResponse:nil forRequest:request error:augmentedError]; + [self logResponse:nil forRequest:request error:augmentedError]; NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; @@ -474,9 +481,9 @@ - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - if ([[SWGConfiguration sharedConfig] debug]) { - [self logResponse:nil forRequest:request error:augmentedError]; - } + + [self logResponse:nil forRequest:request error:augmentedError]; + NSDictionary *responseHeaders = [[operation response] allHeaderFields]; self.HTTPResponseHeaders = responseHeaders; completionBlock(nil, augmentedError); @@ -584,21 +591,15 @@ -(NSNumber*) requestWithCompletionBlock: (NSString*) path hasHeaderParams = true; } if(offlineState) { - if ([[SWGConfiguration sharedConfig] debug]){ - NSLog(@"%@ cache forced", resourcePath); - } + DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - if ([[SWGConfiguration sharedConfig] debug]){ - NSLog(@"%@ cache enabled", resourcePath); - } + DebugLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - if ([[SWGConfiguration sharedConfig] debug]){ - NSLog(@"%@ cache disabled", resourcePath); - } + DebugLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist index d2cd320c27d6..d617744f3f41 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist @@ -2,6 +2,11 @@ + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + CFBundleDevelopmentRegion en CFBundleDisplayName From d4a94fbf520a8f99167d5776a4048c89d765d9a3 Mon Sep 17 00:00:00 2001 From: Adrian Moos Date: Tue, 22 Sep 2015 18:01:29 +0200 Subject: [PATCH 119/219] - DefaultGenerator now communicates failures by throwing exceptions rather than setting a status flag in a public field - DefaultGenerator now decorates exceptions to record where a failure occured (which api, model or operation?) - CodeGenMojo now propagates this exception to maven to abort the build --- .../swagger/codegen/plugin/CodeGenMojo.java | 11 +- .../io/swagger/codegen/DefaultGenerator.java | 244 +++++++++--------- .../codegen/languages/CodeGenStatus.java | 5 - 3 files changed, 134 insertions(+), 126 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java 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 index 7500fcfeb398..fbb961dc199e 100644 --- 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 @@ -162,7 +162,16 @@ public void execute() throws MojoExecutionException { ClientOptInput input = new ClientOptInput().opts(new ClientOpts()).swagger(swagger); input.setConfig(config); - new DefaultGenerator().opts(input).generate(); + + try { + new DefaultGenerator().opts(input).generate(); + } catch (Exception e) { + // Maven logs exceptions thrown by plugins only if invoked with -e + // I find it annoying to jump through hoops to get basic diagnostic information, + // so let's log it in any case: + getLog().error(e); + throw new MojoExecutionException("Code generation failed. See above for the full exception."); + } if (addCompileSourceRoot) { project.addCompileSourceRoot(output.toString()); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b464c706d31e..88feb5376416 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -5,7 +5,6 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Template; -import io.swagger.codegen.languages.CodeGenStatus; import io.swagger.models.ComposedModel; import io.swagger.models.Contact; import io.swagger.models.Info; @@ -47,8 +46,6 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { protected ClientOptInput opts = null; protected Swagger swagger = null; - public CodeGenStatus status = CodeGenStatus.UNRUN; - @Override public Generator opts(ClientOptInput opts) { this.opts = opts; @@ -69,76 +66,76 @@ public List generate() { Json.prettyPrint(swagger); } List files = new ArrayList(); - try { - config.processOpts(); - config.preprocessSwagger(swagger); + config.processOpts(); + config.preprocessSwagger(swagger); - config.additionalProperties().put("generatedDate", DateTime.now().toString()); - config.additionalProperties().put("generatorClass", config.getClass().toString()); + config.additionalProperties().put("generatedDate", DateTime.now().toString()); + config.additionalProperties().put("generatorClass", config.getClass().toString()); - if (swagger.getInfo() != null) { - Info info = swagger.getInfo(); - if (info.getTitle() != null) { - config.additionalProperties().put("appName", info.getTitle()); - } - if (info.getVersion() != null) { - config.additionalProperties().put("appVersion", info.getVersion()); - } - if (info.getDescription() != null) { - config.additionalProperties().put("appDescription", - config.escapeText(info.getDescription())); - } - if (info.getContact() != null) { - Contact contact = info.getContact(); - config.additionalProperties().put("infoUrl", contact.getUrl()); - if (contact.getEmail() != null) { - config.additionalProperties().put("infoEmail", contact.getEmail()); - } + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (info.getTitle() != null) { + config.additionalProperties().put("appName", info.getTitle()); + } + if (info.getVersion() != null) { + config.additionalProperties().put("appVersion", info.getVersion()); + } + if (info.getDescription() != null) { + config.additionalProperties().put("appDescription", + config.escapeText(info.getDescription())); + } + if (info.getContact() != null) { + Contact contact = info.getContact(); + config.additionalProperties().put("infoUrl", contact.getUrl()); + if (contact.getEmail() != null) { + config.additionalProperties().put("infoEmail", contact.getEmail()); } - if (info.getLicense() != null) { - License license = info.getLicense(); - if (license.getName() != null) { - config.additionalProperties().put("licenseInfo", license.getName()); - } - if (license.getUrl() != null) { - config.additionalProperties().put("licenseUrl", license.getUrl()); - } + } + if (info.getLicense() != null) { + License license = info.getLicense(); + if (license.getName() != null) { + config.additionalProperties().put("licenseInfo", license.getName()); } - if (info.getVersion() != null) { - config.additionalProperties().put("version", info.getVersion()); + if (license.getUrl() != null) { + config.additionalProperties().put("licenseUrl", license.getUrl()); } } - - StringBuilder hostBuilder = new StringBuilder(); - String scheme; - if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { - scheme = swagger.getSchemes().get(0).toValue(); - } else { - scheme = "https"; - } - hostBuilder.append(scheme); - hostBuilder.append("://"); - if (swagger.getHost() != null) { - hostBuilder.append(swagger.getHost()); - } else { - hostBuilder.append("localhost"); - } - if (swagger.getBasePath() != null) { - hostBuilder.append(swagger.getBasePath()); + if (info.getVersion() != null) { + config.additionalProperties().put("version", info.getVersion()); } - String contextPath = swagger.getBasePath() == null ? "" : swagger.getBasePath(); - String basePath = hostBuilder.toString(); + } + + StringBuilder hostBuilder = new StringBuilder(); + String scheme; + if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { + scheme = swagger.getSchemes().get(0).toValue(); + } else { + scheme = "https"; + } + hostBuilder.append(scheme); + hostBuilder.append("://"); + if (swagger.getHost() != null) { + hostBuilder.append(swagger.getHost()); + } else { + hostBuilder.append("localhost"); + } + if (swagger.getBasePath() != null) { + hostBuilder.append(swagger.getBasePath()); + } + String contextPath = swagger.getBasePath() == null ? "" : swagger.getBasePath(); + String basePath = hostBuilder.toString(); - List allOperations = new ArrayList(); - List allModels = new ArrayList(); + List allOperations = new ArrayList(); + List allModels = new ArrayList(); - // models - Map definitions = swagger.getDefinitions(); - if (definitions != null) { - List sortedModelKeys = sortModelsByInheritance(definitions); + // models + Map definitions = swagger.getDefinitions(); + if (definitions != null) { + List sortedModelKeys = sortModelsByInheritance(definitions); - for (String name : sortedModelKeys) { + for (String name : sortedModelKeys) { + try { //dont generate models that have an import mapping if(config.importMapping().containsKey(name)) { @@ -173,16 +170,20 @@ public Reader getTemplate(String name) { writeToFile(filename, tmpl.execute(models)); files.add(new File(filename)); } + } catch (Exception e) { + throw new RuntimeException("Could not generate model '" + name + "'", e); } } - if (System.getProperty("debugModels") != null) { - System.out.println("############ Model info ############"); - Json.prettyPrint(allModels); - } + } + if (System.getProperty("debugModels") != null) { + System.out.println("############ Model info ############"); + Json.prettyPrint(allModels); + } - // apis - Map> paths = processPaths(swagger.getPaths()); - for (String tag : paths.keySet()) { + // apis + Map> paths = processPaths(swagger.getPaths()); + for (String tag : paths.keySet()) { + try { List ops = paths.get(tag); Map operation = processOperations(config, tag, ops); @@ -207,7 +208,6 @@ public Reader getTemplate(String name) { } for (String templateName : config.apiTemplateFiles().keySet()) { - String filename = config.apiFilename(templateName, tag); if (!config.shouldOverwrite(filename) && new File(filename).exists()) { continue; @@ -228,51 +228,55 @@ public Reader getTemplate(String name) { writeToFile(filename, tmpl.execute(operation)); files.add(new File(filename)); } - } - if (System.getProperty("debugOperations") != null) { - System.out.println("############ Operation info ############"); - Json.prettyPrint(allOperations); - } + } catch (Exception e) { + throw new RuntimeException("Could not generate api file for '" + tag + "'", e); + } + } + if (System.getProperty("debugOperations") != null) { + System.out.println("############ Operation info ############"); + Json.prettyPrint(allOperations); + } - // supporting files - Map bundle = new HashMap(); - bundle.putAll(config.additionalProperties()); - bundle.put("apiPackage", config.apiPackage()); + // supporting files + Map bundle = new HashMap(); + bundle.putAll(config.additionalProperties()); + bundle.put("apiPackage", config.apiPackage()); - Map apis = new HashMap(); - apis.put("apis", allOperations); - if (swagger.getHost() != null) { - bundle.put("host", swagger.getHost()); - } - bundle.put("basePath", basePath); - bundle.put("scheme", scheme); - bundle.put("contextPath", contextPath); - bundle.put("apiInfo", apis); - bundle.put("models", allModels); - bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); - bundle.put("modelPackage", config.modelPackage()); - List authMethods = config.fromSecurity(swagger.getSecurityDefinitions()); - if (authMethods != null && !authMethods.isEmpty()) { - bundle.put("authMethods", authMethods); - bundle.put("hasAuthMethods", true); - } - if (swagger.getExternalDocs() != null) { - bundle.put("externalDocs", swagger.getExternalDocs()); - } - for (int i = 0; i < allModels.size() - 1; i++) { - HashMap cm = (HashMap) allModels.get(i); - CodegenModel m = cm.get("model"); - m.hasMoreModels = true; - } + Map apis = new HashMap(); + apis.put("apis", allOperations); + if (swagger.getHost() != null) { + bundle.put("host", swagger.getHost()); + } + bundle.put("basePath", basePath); + bundle.put("scheme", scheme); + bundle.put("contextPath", contextPath); + bundle.put("apiInfo", apis); + bundle.put("models", allModels); + bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); + bundle.put("modelPackage", config.modelPackage()); + List authMethods = config.fromSecurity(swagger.getSecurityDefinitions()); + if (authMethods != null && !authMethods.isEmpty()) { + bundle.put("authMethods", authMethods); + bundle.put("hasAuthMethods", true); + } + if (swagger.getExternalDocs() != null) { + bundle.put("externalDocs", swagger.getExternalDocs()); + } + for (int i = 0; i < allModels.size() - 1; i++) { + HashMap cm = (HashMap) allModels.get(i); + CodegenModel m = cm.get("model"); + m.hasMoreModels = true; + } - config.postProcessSupportingFileData(bundle); + config.postProcessSupportingFileData(bundle); - if (System.getProperty("debugSupportingFiles") != null) { - System.out.println("############ Supporting file info ############"); - Json.prettyPrint(bundle); - } + if (System.getProperty("debugSupportingFiles") != null) { + System.out.println("############ Supporting file info ############"); + Json.prettyPrint(bundle); + } - for (SupportingFile support : config.supportingFiles()) { + for (SupportingFile support : config.supportingFiles()) { + try { String outputFolder = config.outputFolder(); if (isNotEmpty(support.folder)) { outputFolder += File.separator + support.folder; @@ -329,14 +333,13 @@ public Reader getTemplate(String name) { files.add(outputFile); } + } catch (Exception e) { + throw new RuntimeException("Could not generate supporting file '" + support + "'", e); } + } - config.processSwagger(swagger); + config.processSwagger(swagger); - status = CodeGenStatus.SUCCESSFUL; - } catch (Exception e) { - status = CodeGenStatus.FAILED; - } return files; } @@ -508,11 +511,12 @@ public void processOperation(String resourcePath, String httpMethod, Operation o } } catch (Exception ex) { - LOGGER.error("Error while trying to get Config from Operation for tag(" + tag + ")\n" // - + "\tResource: " + httpMethod + " " + resourcePath + "\n"// - + "\tOperation:" + operation + "\n" // - + "\tDefinitions: " + swagger.getDefinitions() + "\n"); - ex.printStackTrace(); + String msg = "Could not process operation:\n" // + + " Tag: " + tag + "\n"// + + " Operation: " + operation.getOperationId() + "\n" // + + " Resource: " + httpMethod + " " + resourcePath + "\n"// + + " Definitions: " + swagger.getDefinitions(); + throw new RuntimeException(msg, ex); } } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java deleted file mode 100644 index aa22958517fd..000000000000 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CodeGenStatus.java +++ /dev/null @@ -1,5 +0,0 @@ -package io.swagger.codegen.languages; - -public enum CodeGenStatus { - UNRUN, SUCCESSFUL, FAILED -} From 66dee928d28292f3be06384e89d8b6e9fe3710f8 Mon Sep 17 00:00:00 2001 From: Adrian Moos Date: Tue, 22 Sep 2015 18:08:47 +0200 Subject: [PATCH 120/219] consistent indentation (spaces, not tabs) --- .../src/main/java/io/swagger/codegen/plugin/CodeGenMojo.java | 2 +- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) 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 index fbb961dc199e..21eef59b0104 100644 --- 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 @@ -166,7 +166,7 @@ public void execute() throws MojoExecutionException { try { new DefaultGenerator().opts(input).generate(); } catch (Exception e) { - // Maven logs exceptions thrown by plugins only if invoked with -e + // Maven logs exceptions thrown by plugins only if invoked with -e // I find it annoying to jump through hoops to get basic diagnostic information, // so let's log it in any case: getLog().error(e); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 88feb5376416..b69f9ae56afc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -511,8 +511,8 @@ public void processOperation(String resourcePath, String httpMethod, Operation o } } catch (Exception ex) { - String msg = "Could not process operation:\n" // - + " Tag: " + tag + "\n"// + String msg = "Could not process operation:\n" // + + " Tag: " + tag + "\n"// + " Operation: " + operation.getOperationId() + "\n" // + " Resource: " + httpMethod + " " + resourcePath + "\n"// + " Definitions: " + swagger.getDefinitions(); From 44bbe301cbd06452b9c0259f507f52fea8b03bd1 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 23 Sep 2015 12:49:34 +0800 Subject: [PATCH 121/219] Support primitive string response in Java clients --- .../src/main/resources/Java/ApiClient.mustache | 9 ++++++++- .../Java/libraries/jersey2/ApiClient.mustache | 11 +++++++++-- .../Java/libraries/okhttp-gson/ApiClient.mustache | 5 ++++- 3 files changed, 21 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 5e18c854cba4..339951b27507 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -385,8 +385,15 @@ public class ApiClient { if (contentType.startsWith("application/json")) { return json.deserialize(body, returnType); + } else if (returnType.getType().equals(String.class)) { + // Expecting string, return the raw response body. + return (T) body; } else { - throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + throw new ApiException( + 500, + "Content type \"" + contentType + "\" is not supported for type: " + + returnType.getType() + ); } } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 5033c1986f83..6a7189e9d338 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -389,8 +389,15 @@ public class ApiClient { if (contentType.startsWith("application/json")) { return json.deserialize(body, returnType); + } else if (returnType.getType().equals(String.class)) { + // Expecting string, return the raw response body. + return (T) body; } else { - throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + throw new ApiException( + 500, + "Content type \"" + contentType + "\" is not supported for type: " + + returnType.getType() + ); } } @@ -429,7 +436,7 @@ public class ApiClient { } } - Invocation.Builder invocationBuilder = target.request(contentType).accept(accept); + Invocation.Builder invocationBuilder = target.request().accept(accept); for (String key : headerParams.keySet()) { String value = headerParams.get(key); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index fcbedb0e9f4b..c1a3ea44c373 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -536,9 +536,12 @@ public class ApiClient { } if (contentType.startsWith("application/json")) { return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; } else { throw new ApiException( - "Content type \"" + contentType + "\" is not supported", + "Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); From a284bb7a519b5a291431e329d52d9580e9d0cc54 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 23 Sep 2015 13:31:28 +0800 Subject: [PATCH 122/219] Rebuild Java clients of the Petstore sample --- .../src/main/java/io/swagger/client/ApiClient.java | 11 +++++++++-- .../src/main/java/io/swagger/client/ApiClient.java | 13 ++++++++++--- .../src/main/java/io/swagger/client/ApiClient.java | 5 ++++- 3 files changed, 23 insertions(+), 6 deletions(-) diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 0d531986afa3..ffbd78cc1ce8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-23T12:52:56.012+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -384,8 +384,15 @@ public T deserialize(ClientResponse response, TypeRef returnType) throws Api if (contentType.startsWith("application/json")) { return json.deserialize(body, returnType); + } else if (returnType.getType().equals(String.class)) { + // Expecting string, return the raw response body. + return (T) body; } else { - throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + throw new ApiException( + 500, + "Content type \"" + contentType + "\" is not supported for type: " + + returnType.getType() + ); } } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index 56d7a5453ede..be8414c91131 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -43,7 +43,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-23T12:52:46.364+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -388,8 +388,15 @@ public T deserialize(Response response, TypeRef returnType) throws ApiExcept if (contentType.startsWith("application/json")) { return json.deserialize(body, returnType); + } else if (returnType.getType().equals(String.class)) { + // Expecting string, return the raw response body. + return (T) body; } else { - throw new ApiException(500, "can not deserialize Content-Type: " + contentType); + throw new ApiException( + 500, + "Content type \"" + contentType + "\" is not supported for type: " + + returnType.getType() + ); } } @@ -428,7 +435,7 @@ public T invokeAPI(String path, String method, List queryParams, Objec } } - Invocation.Builder invocationBuilder = target.request(contentType).accept(accept); + Invocation.Builder invocationBuilder = target.request().accept(accept); for (String key : headerParams.keySet()) { String value = headerParams.get(key); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index ba1a834fb8d6..e68d6ab3cb26 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -535,9 +535,12 @@ public T deserialize(Response response, Type returnType) throws ApiException } if (contentType.startsWith("application/json")) { return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; } else { throw new ApiException( - "Content type \"" + contentType + "\" is not supported", + "Content type \"" + contentType + "\" is not supported for type: " + returnType, response.code(), response.headers().toMultimap(), respBody); From 13c079342ef1dad6515d971a4f284ce74d42add2 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 23 Sep 2015 14:55:46 +0800 Subject: [PATCH 123/219] Fixed issue #1262 --- .../main/resources/python/api_client.mustache | 1 + .../resources/python/configuration.mustache | 72 +++++++++++-------- .../python/swagger_client/api_client.py | 8 ++- .../python/swagger_client/configuration.py | 72 +++++++++++-------- 4 files changed, 93 insertions(+), 60 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 4b10f96a73e2..62048f4b29f3 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -25,6 +25,7 @@ from .rest import ApiException import os import re +import sys import urllib import json import mimetypes diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 07625c67e484..f2691c0528ec 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -15,7 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. - ref: https://github.com/swagger-api/swagger-codegen + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -27,10 +27,11 @@ try: except ImportError: # for python3 import http.client as httplib - + import sys import logging +from six import iteritems def singleton(cls, *args, **kw): instances = {} @@ -72,36 +73,23 @@ class Configuration(object): self.password = "" # Logging Settings + self.logger = {} + self.logger["package_logger"] = logging.getLogger("{{packageName}}") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + # Log format self.logging_format = '%(asctime)s %(levelname)s %(message)s' # Debug file location - self.__logging_file = None + self.logging_stream_handler = None + self.logging_file_handler = None + self.logging_file = None # Debug switch - self.__debug = False - self.init_logger() + self.debug = False # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None - - def init_logger(self): - """ - Initializes logger settings. - """ - self.logger = logging.getLogger() - formatter = logging.Formatter(self.logging_format) - stream_handler = logging.StreamHandler() - stream_handler.setFormatter(formatter) - self.logger.addHandler(stream_handler) - if self.__debug: - self.logger.setLevel(logging.DEBUG) - else: - self.logger.setLevel(logging.WARNING) - if self.__logging_file: - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formatter) - self.logger.addFilter(file_handler) @property def logging_file(self): @@ -111,10 +99,23 @@ class Configuration(object): def logging_file(self, value): self.__logging_file = value if self.__logging_file: - formater = logging.Formatter(self.logging_format) - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formater) - self.logger.addHandler(file_handler) + # If set logging file, + # then add file handler and remove stream handler. + self.logging_file_handler = logging.FileHandler(self.__logging_file) + self.logging_file_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_file_handler) + if self.logging_stream_handler: + logger.removeHandler(self.logging_stream_handler) + else: + # If not set logging file, + # then add stream handler and remove file handler. + self.logging_stream_handler = logging.StreamHandler() + self.logging_stream_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_stream_handler) + if self.logging_file_handler: + logger.removeHandler(self.logging_file_handler) @property def debug(self): @@ -125,13 +126,26 @@ class Configuration(object): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - self.logger.setLevel(logging.DEBUG) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - self.logger.setLevel(logging.WARNING) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logging_format(self): + return self.__logging_format + + @logging_format.setter + def logging_format(self, value): + self.__logging_format = value + self.logging_formatter = logging.Formatter(self.__logging_format) def get_api_key_with_prefix(self, identifier): """ diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index b44c4a321a66..86c4a1611107 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -25,6 +25,7 @@ import os import re +import sys import urllib import json import mimetypes @@ -180,16 +181,19 @@ def sanitize_for_serialization(self, obj): If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. + If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ + types = (str, int, float, bool, tuple) + if sys.version_info < (3,0): + types = types + (unicode,) if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, float, bool, tuple)): + elif isinstance(obj, types): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 4ca9342c0571..4b5ed06f27ef 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. - ref: https://github.com/swagger-api/swagger-codegen + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -27,10 +27,11 @@ except ImportError: # for python3 import http.client as httplib - + import sys import logging +from six import iteritems def singleton(cls, *args, **kw): instances = {} @@ -72,36 +73,23 @@ def __init__(self): self.password = "" # Logging Settings + self.logger = {} + self.logger["package_logger"] = logging.getLogger("swagger_client") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + # Log format self.logging_format = '%(asctime)s %(levelname)s %(message)s' # Debug file location - self.__logging_file = None + self.logging_stream_handler = None + self.logging_file_handler = None + self.logging_file = None # Debug switch - self.__debug = False - self.init_logger() + self.debug = False # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None - - def init_logger(self): - """ - Initializes logger settings. - """ - self.logger = logging.getLogger() - formatter = logging.Formatter(self.logging_format) - stream_handler = logging.StreamHandler() - stream_handler.setFormatter(formatter) - self.logger.addHandler(stream_handler) - if self.__debug: - self.logger.setLevel(logging.DEBUG) - else: - self.logger.setLevel(logging.WARNING) - if self.__logging_file: - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formatter) - self.logger.addFilter(file_handler) @property def logging_file(self): @@ -111,10 +99,23 @@ def logging_file(self): def logging_file(self, value): self.__logging_file = value if self.__logging_file: - formater = logging.Formatter(self.logging_format) - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formater) - self.logger.addHandler(file_handler) + # If set logging file, + # then add file handler and remove stream handler. + self.logging_file_handler = logging.FileHandler(self.__logging_file) + self.logging_file_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_file_handler) + if self.logging_stream_handler: + logger.removeHandler(self.logging_stream_handler) + else: + # If not set logging file, + # then add stream handler and remove file handler. + self.logging_stream_handler = logging.StreamHandler() + self.logging_stream_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_stream_handler) + if self.logging_file_handler: + logger.removeHandler(self.logging_file_handler) @property def debug(self): @@ -125,13 +126,26 @@ def debug(self, value): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - self.logger.setLevel(logging.DEBUG) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - self.logger.setLevel(logging.WARNING) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logging_format(self): + return self.__logging_format + + @logging_format.setter + def logging_format(self, value): + self.__logging_format = value + self.logging_formatter = logging.Formatter(self.__logging_format) def get_api_key_with_prefix(self, identifier): """ From 30fbdd4d059395000ed77a89a043eea01e2eb91d Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 23 Sep 2015 17:18:07 +0800 Subject: [PATCH 124/219] Add class prefix to macro `DebugLog` in objc client --- .../resources/objc/ApiClient-body.mustache | 22 +++++++++---------- .../resources/objc/ApiClient-header.mustache | 2 +- .../objc/SwaggerClient/SWGApiClient.h | 2 +- .../objc/SwaggerClient/SWGApiClient.m | 22 +++++++++---------- 4 files changed, 24 insertions(+), 24 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index b1e2c3fc8bf4..fb2bad76aa4e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -100,7 +100,7 @@ static void (^reachabilityChangeBlock)(int); [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], operation.responseString]; - DebugLog(message); + {{classPrefix}}DebugLog(message); } #pragma mark - Cache Methods @@ -194,14 +194,14 @@ static void (^reachabilityChangeBlock)(int); +(NSNumber*) nextRequestId { @synchronized(self) { long nextId = ++requestId; - DebugLog(@"got id %ld", nextId); + {{classPrefix}}DebugLog(@"got id %ld", nextId); return [NSNumber numberWithLong:nextId]; } } +(NSNumber*) queueRequest { NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; - DebugLog(@"added %@ to request queue", requestId); + {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; } @@ -221,7 +221,7 @@ static void (^reachabilityChangeBlock)(int); }]; if(matchingItems.count == 1) { - DebugLog(@"removed request id %@", requestId); + {{classPrefix}}DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; } @@ -245,22 +245,22 @@ static void (^reachabilityChangeBlock)(int); reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); [{{classPrefix}}ApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusNotReachable: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); [{{classPrefix}}ApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusReachableViaWWAN: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); [{{classPrefix}}ApiClient setOfflineState:false]; break; case AFNetworkReachabilityStatusReachableViaWiFi: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); [{{classPrefix}}ApiClient setOfflineState:false]; break; default: @@ -591,15 +591,15 @@ static void (^reachabilityChangeBlock)(int); hasHeaderParams = true; } if(offlineState) { - DebugLog(@"%@ cache forced", resourcePath); + {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - DebugLog(@"%@ cache enabled", resourcePath); + {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - DebugLog(@"%@ cache disabled", resourcePath); + {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 212e361bb793..7aded8aabeb7 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -27,7 +27,7 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; /** * Log debug message macro */ -#define DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; @interface {{classPrefix}}ApiClient : AFHTTPRequestOperationManager diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index b6e6cf57a475..2c78694bbde3 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -31,7 +31,7 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Log debug message macro */ -#define DebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; +#define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; @interface SWGApiClient : AFHTTPRequestOperationManager diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index fc5ca43440dd..fc3c79078625 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -100,7 +100,7 @@ - (void)logResponse:(AFHTTPRequestOperation *)operation [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], operation.responseString]; - DebugLog(message); + SWGDebugLog(message); } #pragma mark - Cache Methods @@ -194,14 +194,14 @@ +(unsigned long)requestQueueSize { +(NSNumber*) nextRequestId { @synchronized(self) { long nextId = ++requestId; - DebugLog(@"got id %ld", nextId); + SWGDebugLog(@"got id %ld", nextId); return [NSNumber numberWithLong:nextId]; } } +(NSNumber*) queueRequest { NSNumber* requestId = [SWGApiClient nextRequestId]; - DebugLog(@"added %@ to request queue", requestId); + SWGDebugLog(@"added %@ to request queue", requestId); [queuedRequests addObject:requestId]; return requestId; } @@ -221,7 +221,7 @@ -(Boolean) executeRequestWithId:(NSNumber*) requestId { }]; if(matchingItems.count == 1) { - DebugLog(@"removed request id %@", requestId); + SWGDebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; } @@ -245,22 +245,22 @@ - (void) configureCacheReachibility { reachabilityStatus = status; switch (status) { case AFNetworkReachabilityStatusUnknown: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); [SWGApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusNotReachable: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); [SWGApiClient setOfflineState:true]; break; case AFNetworkReachabilityStatusReachableViaWWAN: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); [SWGApiClient setOfflineState:false]; break; case AFNetworkReachabilityStatusReachableViaWiFi: - DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); [SWGApiClient setOfflineState:false]; break; default: @@ -591,15 +591,15 @@ -(NSNumber*) requestWithCompletionBlock: (NSString*) path hasHeaderParams = true; } if(offlineState) { - DebugLog(@"%@ cache forced", resourcePath); + SWGDebugLog(@"%@ cache forced", resourcePath); [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; } else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - DebugLog(@"%@ cache enabled", resourcePath); + SWGDebugLog(@"%@ cache enabled", resourcePath); [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; } else { - DebugLog(@"%@ cache disabled", resourcePath); + SWGDebugLog(@"%@ cache disabled", resourcePath); [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; } From 4ef69794a344f7d0c387a038ef02bfd447544fb0 Mon Sep 17 00:00:00 2001 From: Adam Brown Date: Wed, 23 Sep 2015 14:16:26 -0700 Subject: [PATCH 125/219] Fixed method name in Java ApiClient mustache template --- .../swagger-codegen/src/main/resources/Java/ApiClient.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 5e18c854cba4..fedbe47baba8 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -212,7 +212,7 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. */ - public ApiClient getDateFormat(DateFormat dateFormat) { + public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; return this; } From c59e2b88b18193bc6a0ea85aebc64dcb97b73cdb Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 24 Sep 2015 09:30:49 +0800 Subject: [PATCH 126/219] Revert "[Python] Fix issue in python client" --- .../main/resources/python/api_client.mustache | 1 - .../resources/python/configuration.mustache | 72 ++++++++----------- .../python/swagger_client/api_client.py | 8 +-- .../python/swagger_client/configuration.py | 72 ++++++++----------- 4 files changed, 60 insertions(+), 93 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 62048f4b29f3..4b10f96a73e2 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -25,7 +25,6 @@ from .rest import ApiException import os import re -import sys import urllib import json import mimetypes diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index f2691c0528ec..07625c67e484 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -15,7 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. - ref: https://github.com/swagger-api/swagger-codegen + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -27,11 +27,10 @@ try: except ImportError: # for python3 import http.client as httplib - + import sys import logging -from six import iteritems def singleton(cls, *args, **kw): instances = {} @@ -73,23 +72,36 @@ class Configuration(object): self.password = "" # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("{{packageName}}") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format self.logging_format = '%(asctime)s %(levelname)s %(message)s' # Debug file location - self.logging_stream_handler = None - self.logging_file_handler = None - self.logging_file = None + self.__logging_file = None # Debug switch - self.debug = False + self.__debug = False + self.init_logger() # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None + + def init_logger(self): + """ + Initializes logger settings. + """ + self.logger = logging.getLogger() + formatter = logging.Formatter(self.logging_format) + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + self.logger.addHandler(stream_handler) + if self.__debug: + self.logger.setLevel(logging.DEBUG) + else: + self.logger.setLevel(logging.WARNING) + if self.__logging_file: + file_handler = logging.FileHandler(self.__logging_file) + file_handler.setFormatter(formatter) + self.logger.addFilter(file_handler) @property def logging_file(self): @@ -99,23 +111,10 @@ class Configuration(object): def logging_file(self, value): self.__logging_file = value if self.__logging_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logging_file_handler = logging.FileHandler(self.__logging_file) - self.logging_file_handler.setFormatter(self.logging_formatter) - for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_file_handler) - if self.logging_stream_handler: - logger.removeHandler(self.logging_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logging_stream_handler = logging.StreamHandler() - self.logging_stream_handler.setFormatter(self.logging_formatter) - for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_stream_handler) - if self.logging_file_handler: - logger.removeHandler(self.logging_file_handler) + formater = logging.Formatter(self.logging_format) + file_handler = logging.FileHandler(self.__logging_file) + file_handler.setFormatter(formater) + self.logger.addHandler(file_handler) @property def debug(self): @@ -126,26 +125,13 @@ class Configuration(object): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): - logger.setLevel(logging.DEBUG) + self.logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logging_format(self): - return self.__logging_format - - @logging_format.setter - def logging_format(self, value): - self.__logging_format = value - self.logging_formatter = logging.Formatter(self.__logging_format) + self.logger.setLevel(logging.WARNING) def get_api_key_with_prefix(self, identifier): """ diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 86c4a1611107..b44c4a321a66 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -25,7 +25,6 @@ import os import re -import sys import urllib import json import mimetypes @@ -181,19 +180,16 @@ def sanitize_for_serialization(self, obj): If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, sanitize each element in the list. + If obj is list, santize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ - types = (str, int, float, bool, tuple) - if sys.version_info < (3,0): - types = types + (unicode,) if isinstance(obj, type(None)): return None - elif isinstance(obj, types): + elif isinstance(obj, (str, int, float, bool, tuple)): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 4b5ed06f27ef..4ca9342c0571 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. - ref: https://github.com/swagger-api/swagger-codegen + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -27,11 +27,10 @@ except ImportError: # for python3 import http.client as httplib - + import sys import logging -from six import iteritems def singleton(cls, *args, **kw): instances = {} @@ -73,23 +72,36 @@ def __init__(self): self.password = "" # Logging Settings - self.logger = {} - self.logger["package_logger"] = logging.getLogger("swagger_client") - self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format self.logging_format = '%(asctime)s %(levelname)s %(message)s' # Debug file location - self.logging_stream_handler = None - self.logging_file_handler = None - self.logging_file = None + self.__logging_file = None # Debug switch - self.debug = False + self.__debug = False + self.init_logger() # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None + + def init_logger(self): + """ + Initializes logger settings. + """ + self.logger = logging.getLogger() + formatter = logging.Formatter(self.logging_format) + stream_handler = logging.StreamHandler() + stream_handler.setFormatter(formatter) + self.logger.addHandler(stream_handler) + if self.__debug: + self.logger.setLevel(logging.DEBUG) + else: + self.logger.setLevel(logging.WARNING) + if self.__logging_file: + file_handler = logging.FileHandler(self.__logging_file) + file_handler.setFormatter(formatter) + self.logger.addFilter(file_handler) @property def logging_file(self): @@ -99,23 +111,10 @@ def logging_file(self): def logging_file(self, value): self.__logging_file = value if self.__logging_file: - # If set logging file, - # then add file handler and remove stream handler. - self.logging_file_handler = logging.FileHandler(self.__logging_file) - self.logging_file_handler.setFormatter(self.logging_formatter) - for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_file_handler) - if self.logging_stream_handler: - logger.removeHandler(self.logging_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logging_stream_handler = logging.StreamHandler() - self.logging_stream_handler.setFormatter(self.logging_formatter) - for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_stream_handler) - if self.logging_file_handler: - logger.removeHandler(self.logging_file_handler) + formater = logging.Formatter(self.logging_format) + file_handler = logging.FileHandler(self.__logging_file) + file_handler.setFormatter(formater) + self.logger.addHandler(file_handler) @property def debug(self): @@ -126,26 +125,13 @@ def debug(self, value): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in iteritems(self.logger): - logger.setLevel(logging.DEBUG) + self.logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in iteritems(self.logger): - logger.setLevel(logging.WARNING) - # turn off httplib debug - httplib.HTTPConnection.debuglevel = 0 - - @property - def logging_format(self): - return self.__logging_format - - @logging_format.setter - def logging_format(self, value): - self.__logging_format = value - self.logging_formatter = logging.Formatter(self.__logging_format) + self.logger.setLevel(logging.WARNING) def get_api_key_with_prefix(self, identifier): """ From a26cf60a22e17d957340cbb6e52e4197360c43ba Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 24 Sep 2015 10:08:16 +0800 Subject: [PATCH 127/219] Revert "Revert "[Python] Fix issue in python client"" This reverts commit c59e2b88b18193bc6a0ea85aebc64dcb97b73cdb. --- .../main/resources/python/api_client.mustache | 1 + .../resources/python/configuration.mustache | 72 +++++++++++-------- .../python/swagger_client/api_client.py | 8 ++- .../python/swagger_client/configuration.py | 72 +++++++++++-------- 4 files changed, 93 insertions(+), 60 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 4b10f96a73e2..62048f4b29f3 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -25,6 +25,7 @@ from .rest import ApiException import os import re +import sys import urllib import json import mimetypes diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 07625c67e484..f2691c0528ec 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -15,7 +15,7 @@ Copyright 2015 SmartBear Software See the License for the specific language governing permissions and limitations under the License. - ref: https://github.com/swagger-api/swagger-codegen + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -27,10 +27,11 @@ try: except ImportError: # for python3 import http.client as httplib - + import sys import logging +from six import iteritems def singleton(cls, *args, **kw): instances = {} @@ -72,36 +73,23 @@ class Configuration(object): self.password = "" # Logging Settings + self.logger = {} + self.logger["package_logger"] = logging.getLogger("{{packageName}}") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + # Log format self.logging_format = '%(asctime)s %(levelname)s %(message)s' # Debug file location - self.__logging_file = None + self.logging_stream_handler = None + self.logging_file_handler = None + self.logging_file = None # Debug switch - self.__debug = False - self.init_logger() + self.debug = False # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None - - def init_logger(self): - """ - Initializes logger settings. - """ - self.logger = logging.getLogger() - formatter = logging.Formatter(self.logging_format) - stream_handler = logging.StreamHandler() - stream_handler.setFormatter(formatter) - self.logger.addHandler(stream_handler) - if self.__debug: - self.logger.setLevel(logging.DEBUG) - else: - self.logger.setLevel(logging.WARNING) - if self.__logging_file: - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formatter) - self.logger.addFilter(file_handler) @property def logging_file(self): @@ -111,10 +99,23 @@ class Configuration(object): def logging_file(self, value): self.__logging_file = value if self.__logging_file: - formater = logging.Formatter(self.logging_format) - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formater) - self.logger.addHandler(file_handler) + # If set logging file, + # then add file handler and remove stream handler. + self.logging_file_handler = logging.FileHandler(self.__logging_file) + self.logging_file_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_file_handler) + if self.logging_stream_handler: + logger.removeHandler(self.logging_stream_handler) + else: + # If not set logging file, + # then add stream handler and remove file handler. + self.logging_stream_handler = logging.StreamHandler() + self.logging_stream_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_stream_handler) + if self.logging_file_handler: + logger.removeHandler(self.logging_file_handler) @property def debug(self): @@ -125,13 +126,26 @@ class Configuration(object): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - self.logger.setLevel(logging.DEBUG) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - self.logger.setLevel(logging.WARNING) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logging_format(self): + return self.__logging_format + + @logging_format.setter + def logging_format(self, value): + self.__logging_format = value + self.logging_formatter = logging.Formatter(self.__logging_format) def get_api_key_with_prefix(self, identifier): """ diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index b44c4a321a66..86c4a1611107 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -25,6 +25,7 @@ import os import re +import sys import urllib import json import mimetypes @@ -180,16 +181,19 @@ def sanitize_for_serialization(self, obj): If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. - If obj is list, santize each element in the list. + If obj is list, sanitize each element in the list. If obj is dict, return the dict. If obj is swagger model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. """ + types = (str, int, float, bool, tuple) + if sys.version_info < (3,0): + types = types + (unicode,) if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, float, bool, tuple)): + elif isinstance(obj, types): return obj elif isinstance(obj, list): return [self.sanitize_for_serialization(sub_obj) diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 4ca9342c0571..4b5ed06f27ef 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -15,7 +15,7 @@ See the License for the specific language governing permissions and limitations under the License. - ref: https://github.com/swagger-api/swagger-codegen + ref: https://github.com/swagger-api/swagger-codegen """ from __future__ import absolute_import @@ -27,10 +27,11 @@ except ImportError: # for python3 import http.client as httplib - + import sys import logging +from six import iteritems def singleton(cls, *args, **kw): instances = {} @@ -72,36 +73,23 @@ def __init__(self): self.password = "" # Logging Settings + self.logger = {} + self.logger["package_logger"] = logging.getLogger("swagger_client") + self.logger["urllib3_logger"] = logging.getLogger("urllib3") + # Log format self.logging_format = '%(asctime)s %(levelname)s %(message)s' # Debug file location - self.__logging_file = None + self.logging_stream_handler = None + self.logging_file_handler = None + self.logging_file = None # Debug switch - self.__debug = False - self.init_logger() + self.debug = False # SSL/TLS verification # Set this to false to skip verifying SSL certificate when calling API from https server. self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None - - def init_logger(self): - """ - Initializes logger settings. - """ - self.logger = logging.getLogger() - formatter = logging.Formatter(self.logging_format) - stream_handler = logging.StreamHandler() - stream_handler.setFormatter(formatter) - self.logger.addHandler(stream_handler) - if self.__debug: - self.logger.setLevel(logging.DEBUG) - else: - self.logger.setLevel(logging.WARNING) - if self.__logging_file: - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formatter) - self.logger.addFilter(file_handler) @property def logging_file(self): @@ -111,10 +99,23 @@ def logging_file(self): def logging_file(self, value): self.__logging_file = value if self.__logging_file: - formater = logging.Formatter(self.logging_format) - file_handler = logging.FileHandler(self.__logging_file) - file_handler.setFormatter(formater) - self.logger.addHandler(file_handler) + # If set logging file, + # then add file handler and remove stream handler. + self.logging_file_handler = logging.FileHandler(self.__logging_file) + self.logging_file_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_file_handler) + if self.logging_stream_handler: + logger.removeHandler(self.logging_stream_handler) + else: + # If not set logging file, + # then add stream handler and remove file handler. + self.logging_stream_handler = logging.StreamHandler() + self.logging_stream_handler.setFormatter(self.logging_formatter) + for _, logger in iteritems(self.logger): + logger.addHandler(self.logging_stream_handler) + if self.logging_file_handler: + logger.removeHandler(self.logging_file_handler) @property def debug(self): @@ -125,13 +126,26 @@ def debug(self, value): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - self.logger.setLevel(logging.DEBUG) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - self.logger.setLevel(logging.WARNING) + for _, logger in iteritems(self.logger): + logger.setLevel(logging.WARNING) + # turn off httplib debug + httplib.HTTPConnection.debuglevel = 0 + + @property + def logging_format(self): + return self.__logging_format + + @logging_format.setter + def logging_format(self, value): + self.__logging_format = value + self.logging_formatter = logging.Formatter(self.__logging_format) def get_api_key_with_prefix(self, identifier): """ From e32272aedb6c6780a07cbabc4d52b219a97bc57f Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 24 Sep 2015 10:54:24 +0800 Subject: [PATCH 128/219] Update log in python client --- .../resources/python/configuration.mustache | 86 +++++++++++++------ .../python/swagger_client/configuration.py | 86 +++++++++++++------ 2 files changed, 120 insertions(+), 52 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index f2691c0528ec..78efddc74de3 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -77,11 +77,13 @@ class Configuration(object): self.logger["package_logger"] = logging.getLogger("{{packageName}}") self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Log format - self.logging_format = '%(asctime)s %(levelname)s %(message)s' + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + # Log stream handler + self.logger_stream_handler = None + # Log file handler + self.logger_file_handler = None # Debug file location - self.logging_stream_handler = None - self.logging_file_handler = None - self.logging_file = None + self.logger_file = None # Debug switch self.debug = False @@ -92,37 +94,58 @@ class Configuration(object): self.ssl_ca_cert = None @property - def logging_file(self): - return self.__logging_file + def logger_file(self): + """ + Gets the logger_file. + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """ + Sets the logger_file. + + If the logger_file is None, then add stream handler and remove file handler. + Otherwise, add file handler and remove stream handler. - @logging_file.setter - def logging_file(self, value): - self.__logging_file = value - if self.__logging_file: + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: # If set logging file, # then add file handler and remove stream handler. - self.logging_file_handler = logging.FileHandler(self.__logging_file) - self.logging_file_handler.setFormatter(self.logging_formatter) + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_file_handler) - if self.logging_stream_handler: - logger.removeHandler(self.logging_stream_handler) + logger.addHandler(self.logger_file_handler) + if self.logger_stream_handler: + logger.removeHandler(self.logger_stream_handler) else: # If not set logging file, # then add stream handler and remove file handler. - self.logging_stream_handler = logging.StreamHandler() - self.logging_stream_handler.setFormatter(self.logging_formatter) + self.logger_stream_handler = logging.StreamHandler() + self.logger_stream_handler.setFormatter(self.logger_formatter) for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_stream_handler) - if self.logging_file_handler: - logger.removeHandler(self.logging_file_handler) + logger.addHandler(self.logger_stream_handler) + if self.logger_file_handler: + logger.removeHandler(self.logger_file_handler) @property def debug(self): + """ + Gets the debug status. + """ return self.__debug @debug.setter def debug(self, value): + """ + Sets the debug status. + + :param value: The debug status, True or False. + :type: bool + """ self.__debug = value if self.__debug: # if debug status is True, turn on debug logging @@ -139,13 +162,24 @@ class Configuration(object): httplib.HTTPConnection.debuglevel = 0 @property - def logging_format(self): - return self.__logging_format + def logger_format(self): + """ + Gets the logger_format. + """ + return self.__logger_format - @logging_format.setter - def logging_format(self, value): - self.__logging_format = value - self.logging_formatter = logging.Formatter(self.__logging_format) + @logger_format.setter + def logger_format(self, value): + """ + Sets the logger_format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): """ diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 4b5ed06f27ef..8773141f188d 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -77,11 +77,13 @@ def __init__(self): self.logger["package_logger"] = logging.getLogger("swagger_client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") # Log format - self.logging_format = '%(asctime)s %(levelname)s %(message)s' + self.logger_format = '%(asctime)s %(levelname)s %(message)s' + # Log stream handler + self.logger_stream_handler = None + # Log file handler + self.logger_file_handler = None # Debug file location - self.logging_stream_handler = None - self.logging_file_handler = None - self.logging_file = None + self.logger_file = None # Debug switch self.debug = False @@ -92,37 +94,58 @@ def __init__(self): self.ssl_ca_cert = None @property - def logging_file(self): - return self.__logging_file + def logger_file(self): + """ + Gets the logger_file. + """ + return self.__logger_file + + @logger_file.setter + def logger_file(self, value): + """ + Sets the logger_file. + + If the logger_file is None, then add stream handler and remove file handler. + Otherwise, add file handler and remove stream handler. - @logging_file.setter - def logging_file(self, value): - self.__logging_file = value - if self.__logging_file: + :param value: The logger_file path. + :type: str + """ + self.__logger_file = value + if self.__logger_file: # If set logging file, # then add file handler and remove stream handler. - self.logging_file_handler = logging.FileHandler(self.__logging_file) - self.logging_file_handler.setFormatter(self.logging_formatter) + self.logger_file_handler = logging.FileHandler(self.__logger_file) + self.logger_file_handler.setFormatter(self.logger_formatter) for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_file_handler) - if self.logging_stream_handler: - logger.removeHandler(self.logging_stream_handler) + logger.addHandler(self.logger_file_handler) + if self.logger_stream_handler: + logger.removeHandler(self.logger_stream_handler) else: # If not set logging file, # then add stream handler and remove file handler. - self.logging_stream_handler = logging.StreamHandler() - self.logging_stream_handler.setFormatter(self.logging_formatter) + self.logger_stream_handler = logging.StreamHandler() + self.logger_stream_handler.setFormatter(self.logger_formatter) for _, logger in iteritems(self.logger): - logger.addHandler(self.logging_stream_handler) - if self.logging_file_handler: - logger.removeHandler(self.logging_file_handler) + logger.addHandler(self.logger_stream_handler) + if self.logger_file_handler: + logger.removeHandler(self.logger_file_handler) @property def debug(self): + """ + Gets the debug status. + """ return self.__debug @debug.setter def debug(self, value): + """ + Sets the debug status. + + :param value: The debug status, True or False. + :type: bool + """ self.__debug = value if self.__debug: # if debug status is True, turn on debug logging @@ -139,13 +162,24 @@ def debug(self, value): httplib.HTTPConnection.debuglevel = 0 @property - def logging_format(self): - return self.__logging_format + def logger_format(self): + """ + Gets the logger_format. + """ + return self.__logger_format - @logging_format.setter - def logging_format(self, value): - self.__logging_format = value - self.logging_formatter = logging.Formatter(self.__logging_format) + @logger_format.setter + def logger_format(self, value): + """ + Sets the logger_format. + + The logger_formatter will be updated when sets logger_format. + + :param value: The format string. + :type: str + """ + self.__logger_format = value + self.logger_formatter = logging.Formatter(self.__logger_format) def get_api_key_with_prefix(self, identifier): """ From 84e0df6115702d7e07638b049d49ca89b5242981 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 24 Sep 2015 15:53:55 +0800 Subject: [PATCH 129/219] Fixed issue that model name not camelized in python client and ruby client --- .../java/io/swagger/codegen/languages/PythonClientCodegen.java | 2 ++ .../java/io/swagger/codegen/languages/RubyClientCodegen.java | 2 ++ samples/client/petstore/python/swagger_client/apis/user_api.py | 2 +- 3 files changed, 5 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index a2960c512b56..2f364695a348 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -199,6 +199,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { + name = name.replaceAll("\\W", "_"); + // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); 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 f608c4b8d0f3..bbb290c8613c 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 @@ -224,6 +224,8 @@ public String toParamName(String name) { @Override public String toModelName(String name) { + name = name.replaceAll("\\W", "_"); + // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); diff --git a/samples/client/petstore/python/swagger_client/apis/user_api.py b/samples/client/petstore/python/swagger_client/apis/user_api.py index 1c96e1e923ee..aa35e6db53aa 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -435,7 +435,7 @@ def get_user_by_name(self, username, **kwargs): :param callback function: The callback function for asynchronous request. (optional) - :param str username: The name that needs to be fetched. Use user1 for testing. (required) + :param str username: The name that needs to be fetched. Use user1 for testing. (required) :return: User If the method is called asynchronously, returns the request thread. From 2943f41cdd131c50ceb7dd090cd8fbd37936e435 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 24 Sep 2015 16:29:20 +0800 Subject: [PATCH 130/219] Update python and ruby clients. Use `sanitizeName` to sanitize model name. --- .../java/io/swagger/codegen/languages/PythonClientCodegen.java | 2 +- .../java/io/swagger/codegen/languages/RubyClientCodegen.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 2f364695a348..6d9982cf78c0 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -199,7 +199,7 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - name = name.replaceAll("\\W", "_"); + name = sanitizeName(name); // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { 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 bbb290c8613c..4aac683b6ef8 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 @@ -224,7 +224,7 @@ public String toParamName(String name) { @Override public String toModelName(String name) { - name = name.replaceAll("\\W", "_"); + name = sanitizeName(name); // model name cannot use reserved keyword, e.g. return if (reservedWords.contains(name)) { From 597282742b1a08fe0feb5ae30d72b145792297b0 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 24 Sep 2015 21:56:50 +0800 Subject: [PATCH 131/219] Fix ApiClient.setDateFormat in Java jersey2 client --- .../main/resources/Java/libraries/jersey2/ApiClient.mustache | 2 +- .../default/src/main/java/io/swagger/client/ApiClient.java | 4 ++-- .../jersey2/src/main/java/io/swagger/client/ApiClient.java | 4 ++-- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache index 6a7189e9d338..fffd5fc824f4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/ApiClient.mustache @@ -216,7 +216,7 @@ public class ApiClient { /** * Set the date format used to parse/format date parameters. */ - public ApiClient getDateFormat(DateFormat dateFormat) { + public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; return this; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index ffbd78cc1ce8..0942d0bd0dd5 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-23T12:52:56.012+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-24T21:52:56.159+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -211,7 +211,7 @@ public DateFormat getDateFormat() { /** * Set the date format used to parse/format date parameters. */ - public ApiClient getDateFormat(DateFormat dateFormat) { + public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; return this; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java index be8414c91131..87838cb85699 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/ApiClient.java @@ -43,7 +43,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-23T12:52:46.364+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-24T21:52:47.417+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); @@ -215,7 +215,7 @@ public DateFormat getDateFormat() { /** * Set the date format used to parse/format date parameters. */ - public ApiClient getDateFormat(DateFormat dateFormat) { + public ApiClient setDateFormat(DateFormat dateFormat) { this.dateFormat = dateFormat; return this; } From 9b148be57e17fc832c79136f92052f448abbe504 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 25 Sep 2015 15:10:32 +0800 Subject: [PATCH 132/219] Fix issue in python client. If upload only file it will not send file content. --- .../main/resources/python/api_client.mustache | 2 +- .../python/swagger_client/api_client.py | 2 +- .../petstore/python/tests/test_pet_api.py | 22 ++++++++++--------- 3 files changed, 14 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 62048f4b29f3..969eb4e7992b 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -126,7 +126,7 @@ class ApiClient(object): for k, v in iteritems(query_params)} # post parameters - if post_params: + if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 86c4a1611107..fdc92cae77f6 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -126,7 +126,7 @@ def __call_api(self, resource_path, method, for k, v in iteritems(query_params)} # post parameters - if post_params: + if post_params or files: post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) diff --git a/samples/client/petstore/python/tests/test_pet_api.py b/samples/client/petstore/python/tests/test_pet_api.py index 6994ddbd6491..300a7bee7833 100644 --- a/samples/client/petstore/python/tests/test_pet_api.py +++ b/samples/client/petstore/python/tests/test_pet_api.py @@ -68,7 +68,7 @@ def test_create_api_instance(self): self.assertNotEqual(pet_api3.api_client, swagger_client.configuration.api_client) # customized pet api not using the old pet api's api client self.assertNotEqual(pet_api3.api_client, pet_api2.api_client) - + def test_async_request(self): self.pet_api.add_pet(body=self.pet) @@ -110,7 +110,7 @@ def test_update_pet(self): def test_find_pets_by_status(self): self.pet_api.add_pet(body=self.pet) - + self.assertIn( self.pet.id, list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status]))) @@ -118,7 +118,7 @@ def test_find_pets_by_status(self): def test_find_pets_by_tags(self): self.pet_api.add_pet(body=self.pet) - + self.assertIn( self.pet.id, list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_tags(tags=[self.tag.name]))) @@ -126,7 +126,7 @@ def test_find_pets_by_tags(self): def test_update_pet_with_form(self): self.pet_api.add_pet(body=self.pet) - + name = "hello kity with form updated" status = "pending" self.pet_api.update_pet_with_form(pet_id=self.pet.id, name=name, status=status) @@ -137,6 +137,7 @@ def test_update_pet_with_form(self): self.assertEqual(status, fetched.status) def test_upload_file(self): + # upload file with form parameter try: additional_metadata = "special" self.pet_api.upload_file( @@ -147,10 +148,16 @@ def test_upload_file(self): except ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + # upload only file + try: + self.pet_api.upload_file(pet_id=self.pet.id, file=self.foo) + except ApiException as e: + self.fail("upload_file() raised {0} unexpectedly".format(type(e))) + def test_delete_pet(self): self.pet_api.add_pet(body=self.pet) self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") - + try: self.pet_api.get_pet_by_id(pet_id=self.pet.id) raise "expected an error" @@ -159,8 +166,3 @@ def test_delete_pet(self): if __name__ == '__main__': unittest.main() - - - - - From e5a4ef3ba0607fefa487a407699620e842cc266d Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 25 Sep 2015 15:52:52 +0800 Subject: [PATCH 133/219] Fix hard-coded constructor name of enum class in Java okhttp-gson client --- .../resources/Java/libraries/okhttp-gson/enumClass.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache index cc00e9d392ee..bb1109c27cad 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/enumClass.mustache @@ -6,7 +6,7 @@ public enum {{datatypeWithEnum}} { private String value; - StatusEnum(String value) { + {{datatypeWithEnum}}(String value) { this.value = value; } From 6bdfb8810c13784fe914404c43c0e22299a77484 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 25 Sep 2015 16:48:19 +0800 Subject: [PATCH 134/219] Add test case in objc client --- .../SwaggerClient/SwaggerClient-Info.plist | 5 +++++ .../SwaggerClientTests/Tests/PetApiTest.m | 21 +++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist index d2cd320c27d6..d617744f3f41 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist +++ b/samples/client/petstore/objc/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist @@ -2,6 +2,11 @@ + NSAppTransportSecurity + + NSAllowsArbitraryLoads + + CFBundleDevelopmentRegion en CFBundleDisplayName diff --git a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m index f861cb0605e3..68add577ac1a 100644 --- a/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m +++ b/samples/client/petstore/objc/SwaggerClientTests/Tests/PetApiTest.m @@ -218,8 +218,8 @@ - (void)testDeletePet { [self waitForExpectationsWithTimeout:10.0 handler:nil]; } -- (void)testUploadFile { - XCTestExpectation *expectation = [self expectationWithDescription:@"testUploadWithFile"]; +- (void)testUploadFileWithFormParameter { + XCTestExpectation *expectation = [self expectationWithDescription:@"testUploadWithFileWithFormParameter"]; NSURL *fileURL = [self createTempFile]; @@ -236,6 +236,23 @@ - (void)testUploadFile { [self waitForExpectationsWithTimeout:10.0 handler:nil]; } +- (void)testUploadFile { + XCTestExpectation *expectation = [self expectationWithDescription:@"testUploadFile"]; + + NSURL *fileURL = [self createTempFile]; + + [api uploadFileWithCompletionBlock:@1 additionalMetadata:nil file:fileURL completionHandler:^(NSError *error) { + if (error) { + XCTFail(@"expected a failure"); + } + else { + [expectation fulfill]; + } + }]; + + [self waitForExpectationsWithTimeout:10.0 handler:nil]; +} + - (void)TestUploadWithoutFile { XCTestExpectation *expectation = [self expectationWithDescription:@"testUploadWithoutFile"]; From c70ca9d572341c89641c7fa0f732340835b58f62 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 25 Sep 2015 17:33:39 +0800 Subject: [PATCH 135/219] Add test case in ruby client --- samples/client/petstore/ruby/spec/pet_spec.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 5d379bf49215..c9858eca37ab 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -116,5 +116,14 @@ # nothing is returned result.should be_nil end + + it "should upload a file with form parameter to a pet" do + pet = Petstore::Pet.new('id' => 10002, 'name' => 'RUBY UNIT TESTING') + result = @pet_api.add_pet(body: pet) + result.should be_nil + + result = @pet_api.upload_file(10002, file: File.new('hello.txt'), additional_metadata: 'metadata') + result.should be_nil + end end end From cf1f113852f47dd2e3370641ef45d9761980fbdd Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 26 Sep 2015 16:16:59 +0800 Subject: [PATCH 136/219] Support client certificate file and client key file in TLS/SSL in python client --- .../resources/python/configuration.mustache | 4 ++++ .../src/main/resources/python/rest.mustache | 18 +++++++++++++++++- .../python/swagger_client/configuration.py | 4 ++++ .../petstore/python/swagger_client/rest.py | 18 +++++++++++++++++- 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 78efddc74de3..78fa8fb6d3c1 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -92,6 +92,10 @@ class Configuration(object): self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None + # client certificate file + self.cert_file = None + # client key file + self.key_file = None @property def logger_file(self): diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 07be648373ac..0d1f4ce1da8c 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -72,22 +72,38 @@ class RESTResponse(io.IOBase): class RESTClientObject(object): def __init__(self, pools_size=4): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 + # ca_certs vs cert_file vs key_file + # http://stackoverflow.com/a/23957365/2985775 + + # cert_reqs if Configuration().verify_ssl: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE + # ca_certs if Configuration().ssl_ca_cert: ca_certs = Configuration().ssl_ca_cert else: # if not set certificate file, use Mozilla's root certificates. ca_certs = certifi.where() + # cert_file + cert_file = Configuration().cert_file + + # key file + key_file = Configuration().key_file + # https pool manager self.pool_manager = urllib3.PoolManager( num_pools=pools_size, cert_reqs=cert_reqs, - ca_certs=ca_certs + ca_certs=ca_certs, + cert_file=cert_file, + key_file=key_file ) def request(self, method, url, query_params=None, headers=None, diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index 8773141f188d..3e00acbe252b 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -92,6 +92,10 @@ def __init__(self): self.verify_ssl = True # Set this to customize the certificate file to verify the peer. self.ssl_ca_cert = None + # client certificate file + self.cert_file = None + # client key file + self.key_file = None @property def logger_file(self): diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 07be648373ac..0d1f4ce1da8c 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -72,22 +72,38 @@ def getheader(self, name, default=None): class RESTClientObject(object): def __init__(self, pools_size=4): + # urllib3.PoolManager will pass all kw parameters to connectionpool + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 + # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 + # ca_certs vs cert_file vs key_file + # http://stackoverflow.com/a/23957365/2985775 + + # cert_reqs if Configuration().verify_ssl: cert_reqs = ssl.CERT_REQUIRED else: cert_reqs = ssl.CERT_NONE + # ca_certs if Configuration().ssl_ca_cert: ca_certs = Configuration().ssl_ca_cert else: # if not set certificate file, use Mozilla's root certificates. ca_certs = certifi.where() + # cert_file + cert_file = Configuration().cert_file + + # key file + key_file = Configuration().key_file + # https pool manager self.pool_manager = urllib3.PoolManager( num_pools=pools_size, cert_reqs=cert_reqs, - ca_certs=ca_certs + ca_certs=ca_certs, + cert_file=cert_file, + key_file=key_file ) def request(self, method, url, query_params=None, headers=None, From 6a3108a6bf676a975eb85aff0808e1331064b0db Mon Sep 17 00:00:00 2001 From: geekerzp Date: Mon, 28 Sep 2015 16:31:47 +0800 Subject: [PATCH 137/219] Support client ceritficate in ruby client --- .../src/main/resources/ruby/api_client.mustache | 2 ++ .../src/main/resources/ruby/configuration.mustache | 9 +++++++++ samples/client/petstore/ruby/lib/petstore/api_client.rb | 2 ++ .../client/petstore/ruby/lib/petstore/configuration.rb | 9 +++++++++ 4 files changed, 22 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache index 0c7641a6b04c..2bdcf6dc7be9 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api_client.mustache @@ -70,6 +70,8 @@ module {{moduleName}} :headers => header_params, :params => query_params, :ssl_verifypeer => Configuration.verify_ssl, + :sslcert => Configuration.cert_file, + :sslkey => Configuration.key_file, :cainfo => Configuration.ssl_ca_cert, :verbose => Configuration.debugging } diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index 600f9b7bafb8..e74cc17573cc 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -64,6 +64,7 @@ module {{moduleName}} # @return [String] attr_accessor :temp_folder_path + ### TLS/SSL # Set this to false to skip verifying SSL certificate when calling API from https server. # Default to true. # @@ -80,6 +81,12 @@ module {{moduleName}} # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 attr_accessor :ssl_ca_cert + # Client certificate file (for client certificate) + attr_accessor :cert_file + + # Client private key file (for client certificate) + attr_accessor :key_file + attr_accessor :inject_format attr_accessor :force_ending_format @@ -102,6 +109,8 @@ module {{moduleName}} @api_key = {} @api_key_prefix = {} @verify_ssl = true + @cert_file = nil + @key_file = nil @debugging = false @inject_format = false @force_ending_format = false diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 6eda344b2d80..4f747bcd6a11 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -70,6 +70,8 @@ def build_request(http_method, path, opts = {}) :headers => header_params, :params => query_params, :ssl_verifypeer => Configuration.verify_ssl, + :sslcert => Configuration.cert_file, + :sslkey => Configuration.key_file, :cainfo => Configuration.ssl_ca_cert, :verbose => Configuration.debugging } diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 83df41b5e05a..008be48ee4da 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -64,6 +64,7 @@ class Configuration # @return [String] attr_accessor :temp_folder_path + ### TLS/SSL # Set this to false to skip verifying SSL certificate when calling API from https server. # Default to true. # @@ -80,6 +81,12 @@ class Configuration # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 attr_accessor :ssl_ca_cert + # Client certificate file (for client certificate) + attr_accessor :cert_file + + # Client private key file (for client certificate) + attr_accessor :key_file + attr_accessor :inject_format attr_accessor :force_ending_format @@ -102,6 +109,8 @@ def initialize @api_key = {} @api_key_prefix = {} @verify_ssl = true + @cert_file = nil + @key_file = nil @debugging = false @inject_format = false @force_ending_format = false From d5cf2b6cfe7cf55cdeedb1bc74291b1dcd262007 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Mon, 28 Sep 2015 08:51:39 -0700 Subject: [PATCH 138/219] made host dynamic for link generation --- .../swagger/generator/resource/SwaggerResource.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index 808501380107..4b4494977ebf 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -12,6 +12,7 @@ import io.swagger.generator.model.ResponseCode; import io.swagger.generator.online.Generator; +import javax.ws.rs.core.Context; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; @@ -19,6 +20,7 @@ import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; +import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -61,11 +63,13 @@ public Response downloadFile(@PathParam("fileId") String fileId) throws Exceptio response = ResponseCode.class, tags = "clients") public Response generateClient( + @Context HttpServletRequest request, @ApiParam(value = "The target language for the client library", allowableValues = "android,java,php,objc,docs", required = true) @PathParam("language") String language, @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { String filename = Generator.generateClient(language, opts); + String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); if (filename != null) { String code = String.valueOf(System.currentTimeMillis()); Generated g = new Generated(); @@ -73,7 +77,7 @@ public Response generateClient( g.setFriendlyName(language + "-client"); fileMap.put(code, g); System.out.println(code + ", " + filename); - String link = "http://generator.swagger.io/api/gen/download/" + code; + String link = host + "/api/gen/download/" + code; return Response.ok().entity(new ResponseCode(code, link)).build(); } else { return Response.status(500).build(); @@ -110,6 +114,7 @@ public Response serverOptions() { response = ResponseCode.class, tags = "servers") public Response generateServerForLanguage( + @Context HttpServletRequest request, @ApiParam(value = "framework", allowableValues = "jaxrs,nodejs", required = true) @PathParam("framework") String framework, @ApiParam(value = "parameters", required = true) GeneratorInput opts) throws Exception { @@ -119,6 +124,8 @@ public Response generateServerForLanguage( String filename = Generator.generateServer(framework, opts); System.out.println("generated name: " + filename); + String host = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort(); + if (filename != null) { String code = String.valueOf(System.currentTimeMillis()); Generated g = new Generated(); @@ -126,7 +133,7 @@ public Response generateServerForLanguage( g.setFriendlyName(framework + "-server"); fileMap.put(code, g); System.out.println(code + ", " + filename); - String link = "http://generator.swagger.io/api/gen/download/" + code; + String link = host + "/api/gen/download/" + code; return Response.ok().entity(new ResponseCode(code, link)).build(); } else { return Response.status(500).build(); From 4db86003f51305313e2460060ce0b36c6d4d82fe Mon Sep 17 00:00:00 2001 From: Ivan Ushankin Date: Mon, 28 Sep 2015 18:55:06 +0300 Subject: [PATCH 139/219] Fixed #1304: Migrate tests from the Scala to the plain Java. Part 1 --- .../swagger/codegen/ClientAuthInputTest.java | 41 ++ .../swagger/codegen/SwaggerMigratorTest.java | 15 + .../codegen/java/JavaInheritanceTest.java | 31 ++ .../codegen/java/JavaModelEnumTest.java | 96 ++++ .../swagger/codegen/java/JavaModelTest.java | 456 ++++++++++++++++++ .../src/test/scala/ClientAuthInputTest.scala | 38 -- .../test/scala/Java/JavaInheritanceTest.scala | 25 - .../test/scala/Java/JavaModelEnumTest.scala | 85 ---- .../src/test/scala/Java/JavaModelTest.scala | 445 ----------------- .../src/test/scala/SwaggerMigratorTest.scala | 14 - modules/swagger-generator/pom.xml | 62 +-- .../swagger/generator/GeneratorInputTest.java | 14 + .../src/test/scala/GeneratorInputTest.scala | 12 - 13 files changed, 655 insertions(+), 679 deletions(-) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java delete mode 100644 modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala create mode 100644 modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java delete mode 100644 modules/swagger-generator/src/test/scala/GeneratorInputTest.scala diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java new file mode 100644 index 000000000000..59552bba1486 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ClientAuthInputTest.java @@ -0,0 +1,41 @@ +package io.swagger.codegen; + +import io.swagger.models.auth.AuthorizationValue; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.List; + +public class ClientAuthInputTest { + + @Test(description = "read a file upload param from a 2.0 spec") + public void clientAuthInputTest() { + final ClientOptInput input = new ClientOptInput(); + + final String header = "api_key:special-key,api_key:hello,X-AUTHORIZATION:0e6c11d79a,Authorization:Basic 1jz0"; + input.setAuth(header); + final List authValues = input.getAuthorizationValues(); + Assert.assertEquals(authValues.size(), 4); + + final AuthorizationValue a1 = authValues.get(0); + Assert.assertEquals(a1.getKeyName(), "api_key"); + Assert.assertEquals(a1.getValue(), "special-key"); + Assert.assertEquals(a1.getType(), "header"); + + final AuthorizationValue a2 = authValues.get(1); + Assert.assertEquals(a2.getKeyName(), "api_key"); + Assert.assertEquals(a2.getValue(), "hello"); + Assert.assertEquals(a2.getType(), "header"); + + final AuthorizationValue a3 = authValues.get(2); + Assert.assertEquals(a3.getKeyName(), "X-AUTHORIZATION"); + Assert.assertEquals(a3.getValue(), "0e6c11d79a"); + Assert.assertEquals(a3.getType(), "header"); + + final AuthorizationValue a4 = authValues.get(3); + Assert.assertEquals(a4.getKeyName(), "Authorization"); + Assert.assertEquals(a4.getValue(), "Basic 1jz0"); + Assert.assertEquals(a4.getType(), "header"); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java new file mode 100644 index 000000000000..2a7e9ec532a5 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/SwaggerMigratorTest.java @@ -0,0 +1,15 @@ +package io.swagger.codegen; + +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; + +import org.testng.annotations.Test; + +public class SwaggerMigratorTest { + + @Test(description = "read a 1.2 spec") + public void swaggerMigratorTest() { + final SwaggerParser loader = new SwaggerParser(); + final Swagger swagger = loader.read("src/test/resources/1_2/petstore-1.2/api-docs"); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java new file mode 100644 index 000000000000..66b48cd6b89f --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaInheritanceTest.java @@ -0,0 +1,31 @@ +package io.swagger.codegen.java; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.RefModel; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class JavaInheritanceTest { + + @Test(description = "convert a composed model") + public void javaInheritanceTest() { + final Model model = new ComposedModel().parent(new RefModel("Base")) + .child(new ModelImpl().additionalProperties(new StringProperty())); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "Base"); + Assert.assertEquals(cm.imports, Sets.newHashSet("Base")); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java new file mode 100644 index 000000000000..46828a1f805f --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelEnumTest.java @@ -0,0 +1,96 @@ +package io.swagger.codegen.java; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.models.ComposedModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.RefModel; +import io.swagger.models.properties.Property; +import io.swagger.models.properties.StringProperty; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class JavaModelEnumTest { + + @Test(description = "convert a java model with an enum") + public void converterTest() { + final StringProperty enumProperty = new StringProperty(); + enumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + final ModelImpl model = new ModelImpl().property("name", enumProperty); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "name"); + Assert.assertEquals(enumVar.datatype, "String"); + Assert.assertEquals(enumVar.datatypeWithEnum, "NameEnum"); + Assert.assertEquals(enumVar.name, "name"); + Assert.assertEquals(enumVar.defaultValue, "null"); + Assert.assertEquals(enumVar.baseType, "String"); + Assert.assertTrue(enumVar.isEnum); + } + + @Test(description = "not override identical parent enums") + public void overrideEnumTest() { + final StringProperty identicalEnumProperty = new StringProperty(); + identicalEnumProperty.setEnum(Arrays.asList("VALUE1", "VALUE2", "VALUE3")); + + final StringProperty subEnumProperty = new StringProperty(); + subEnumProperty.setEnum(Arrays.asList("SUB1", "SUB2", "SUB3")); + + // Add one enum property to the parent + final Map parentProperties = new HashMap(); + parentProperties.put("sharedThing", identicalEnumProperty); + + // Add TWO enums to the subType model; one of which is identical to the one in parent class + final Map subProperties = new HashMap(); + subProperties.put("sharedThing", identicalEnumProperty); + subProperties.put("unsharedThing", identicalEnumProperty); + + final ModelImpl parentModel = new ModelImpl(); + parentModel.setProperties(parentProperties); + parentModel.name("parentModel"); + + final ModelImpl subModel = new ModelImpl(); + subModel.setProperties(subProperties); + subModel.name("subModel"); + + final ComposedModel model = new ComposedModel() + .parent(new RefModel(parentModel.getName())) + .child(subModel) + .interfaces(new ArrayList()); + + final DefaultCodegen codegen = new JavaClientCodegen(); + final Map allModels = new HashMap(); + allModels.put(codegen.toModelName(parentModel.getName()), parentModel); + allModels.put(codegen.toModelName(subModel.getName()), subModel); + + final CodegenModel cm = codegen.fromModel("sample", model, allModels); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.parent, "ParentModel"); + Assert.assertEquals(cm.imports, Collections.singletonList("ParentModel")); + + // Assert that only the unshared/uninherited enum remains + Assert.assertEquals(cm.vars.size(), 1); + final CodegenProperty enumVar = cm.vars.get(0); + Assert.assertEquals(enumVar.baseName, "unsharedThing"); + Assert.assertEquals(enumVar.datatype, "String"); + Assert.assertEquals(enumVar.datatypeWithEnum, "UnsharedThingEnum"); + Assert.assertTrue(enumVar.isEnum); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java new file mode 100644 index 000000000000..49641701f62d --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -0,0 +1,456 @@ +package io.swagger.codegen.java; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.JavaClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.parameters.QueryParameter; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.ByteArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.IntegerProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.List; + +public class JavaModelTest { + + @Test(description = "convert a simple java model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final List vars = cm.vars; + + final CodegenProperty property1 = vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.getter, "getId"); + Assert.assertEquals(property1.setter, "setId"); + Assert.assertEquals(property1.datatype, "Long"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "Long"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.getter, "getName"); + Assert.assertEquals(property2.setter, "setName"); + Assert.assertEquals(property2.datatype, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.getter, "getCreatedAt"); + Assert.assertEquals(property3.setter, "setCreatedAt"); + Assert.assertEquals(property3.datatype, "Date"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.baseType, "Date"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property = cm.vars.get(1); + Assert.assertEquals(property.baseName, "urls"); + Assert.assertEquals(property.getter, "getUrls"); + Assert.assertEquals(property.setter, "setUrls"); + Assert.assertEquals(property.datatype, "List"); + Assert.assertEquals(property.name, "urls"); + Assert.assertEquals(property.defaultValue, "new ArrayList()"); + Assert.assertEquals(property.baseType, "List"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "translations"); + Assert.assertEquals(property.getter, "getTranslations"); + Assert.assertEquals(property.setter, "setTranslations"); + Assert.assertEquals(property.datatype, "Map"); + Assert.assertEquals(property.name, "translations"); + Assert.assertEquals(property.defaultValue, "new HashMap()"); + Assert.assertEquals(property.baseType, "Map"); + Assert.assertEquals(property.containerType, "map"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with a map with complex list property") + public void mapWithListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", + new MapProperty().additionalProperties(new ArrayProperty().items(new RefProperty("Pet")))) + .required("id"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "translations"); + Assert.assertEquals(property.getter, "getTranslations"); + Assert.assertEquals(property.setter, "setTranslations"); + Assert.assertEquals(property.datatype, "Map>"); + Assert.assertEquals(property.name, "translations"); + Assert.assertEquals(property.defaultValue, "new HashMap>()"); + Assert.assertEquals(property.baseType, "Map"); + Assert.assertEquals(property.containerType, "map"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with a 2D list property") + public void list2DPropertyTest() { + final Model model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( + new ArrayProperty().items(new RefProperty("Pet")))); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "list2D"); + Assert.assertEquals(property.getter, "getList2D"); + Assert.assertEquals(property.setter, "setList2D"); + Assert.assertEquals(property.datatype, "List>"); + Assert.assertEquals(property.name, "list2D"); + Assert.assertEquals(property.defaultValue, "new ArrayList>()"); + Assert.assertEquals(property.baseType, "List"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with complex properties") + public void complexPropertiesTest() { + final Model model = new ModelImpl().description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "children"); + Assert.assertEquals(property.getter, "getChildren"); + Assert.assertEquals(property.setter, "setChildren"); + Assert.assertEquals(property.datatype, "Children"); + Assert.assertEquals(property.name, "children"); + Assert.assertEquals(property.defaultValue, "null"); + Assert.assertEquals(property.baseType, "Children"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty().items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "children"); + Assert.assertEquals(property.complexType, "Children"); + Assert.assertEquals(property.getter, "getChildren"); + Assert.assertEquals(property.setter, "setChildren"); + Assert.assertEquals(property.datatype, "List"); + Assert.assertEquals(property.name, "children"); + Assert.assertEquals(property.defaultValue, "new ArrayList()"); + Assert.assertEquals(property.baseType, "List"); + Assert.assertEquals(property.containerType, "array"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty().additionalProperties(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(Sets.union(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "children"); + Assert.assertEquals(property.complexType, "Children"); + Assert.assertEquals(property.getter, "getChildren"); + Assert.assertEquals(property.setter, "setChildren"); + Assert.assertEquals(property.datatype, "Map"); + Assert.assertEquals(property.name, "children"); + Assert.assertEquals(property.defaultValue, "new HashMap()"); + Assert.assertEquals(property.baseType, "Map"); + Assert.assertEquals(property.containerType, "map"); + Assert.assertNull(property.required); + Assert.assertTrue(property.isContainer); + Assert.assertNull(property.isNotContainer); + + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "ArrayList"); + Assert.assertEquals(cm.imports.size(), 3); + Assert.assertEquals(Sets.union(cm.imports, Sets.newHashSet("List", "ArrayList", "Children")).size(), 3); + } + + @Test(description = "convert an map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("an map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "HashMap"); + Assert.assertEquals(cm.imports.size(), 3); + Assert.assertEquals(Sets.union(cm.imports, Sets.newHashSet("Map", "HashMap", "Children")).size(), 3); + } + + @Test(description = "convert a model with upper-case property names") + public void upperCaseNamesTest() { + final Model model = new ModelImpl() + .description("a model with upper-case property names") + .property("NAME", new StringProperty()) + .required("NAME"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "NAME"); + Assert.assertEquals(property.getter, "getNAME"); + Assert.assertEquals(property.setter, "setNAME"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "NAME"); + Assert.assertEquals(property.defaultValue, "null"); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert a model with a 2nd char upper-case property names") + public void secondCharUpperCaseNamesTest() { + final Model model = new ModelImpl() + .description("a model with a 2nd char upper-case property names") + .property("pId", new StringProperty()) + .required("pId"); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "pId"); + Assert.assertEquals(property.getter, "getPId"); + Assert.assertEquals(property.setter, "setPId"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "pId"); + Assert.assertEquals(property.defaultValue, "null"); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert hyphens per issue 503") + public void hyphensTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("created-at", new DateTimeProperty()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "created-at"); + Assert.assertEquals(property.getter, "getCreatedAt"); + Assert.assertEquals(property.setter, "setCreatedAt"); + Assert.assertEquals(property.name, "createdAt"); + } + + @Test(description = "convert query[password] to queryPassword") + public void squareBracketsTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("query[password]", new StringProperty()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "query[password]"); + Assert.assertEquals(property.getter, "getQueryPassword"); + Assert.assertEquals(property.setter, "setQueryPassword"); + Assert.assertEquals(property.name, "queryPassword"); + } + + @Test(description = "properly escape names per 567") + public void escapeNamesTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("created-at", new DateTimeProperty()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("with.dots", model); + + Assert.assertEquals(cm.classname, "WithDots"); + } + + @Test(description = "convert a model with binary data") + public void binaryDataTest() { + final Model model = new ModelImpl() + .description("model with binary") + .property("inputBinaryData", new ByteArrayProperty()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "inputBinaryData"); + Assert.assertEquals(property.getter, "getInputBinaryData"); + Assert.assertEquals(property.setter, "setInputBinaryData"); + Assert.assertEquals(property.datatype, "byte[]"); + Assert.assertEquals(property.name, "inputBinaryData"); + Assert.assertEquals(property.defaultValue, "null"); + Assert.assertEquals(property.baseType, "byte[]"); + Assert.assertNull(property.hasMore); + Assert.assertNull(property.required); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "translate an invalid param name") + public void invalidParamNameTest() { + final Model model = new ModelImpl() + .description("a model with a 2nd char upper-case property names") + .property("_", new StringProperty()); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property = cm.vars.get(0); + Assert.assertEquals(property.baseName, "_"); + Assert.assertEquals(property.getter, "getU"); + Assert.assertEquals(property.setter, "setU"); + Assert.assertEquals(property.datatype, "String"); + Assert.assertEquals(property.name, "u"); + Assert.assertEquals(property.defaultValue, "null"); + Assert.assertEquals(property.baseType, "String"); + Assert.assertNull(property.hasMore); + Assert.assertTrue(property.isNotContainer); + } + + @Test(description = "convert a parameter") + public void convertParameterTest() { + final QueryParameter parameter = new QueryParameter() + .property(new IntegerProperty()) + .name("limit") + .required(true); + final DefaultCodegen codegen = new JavaClientCodegen(); + final CodegenParameter cm = codegen.fromParameter(parameter, null); + + Assert.assertNull(cm.allowableValues); + } +} diff --git a/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala b/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala deleted file mode 100644 index 959a62569fd2..000000000000 --- a/modules/swagger-codegen/src/test/scala/ClientAuthInputTest.scala +++ /dev/null @@ -1,38 +0,0 @@ -import io.swagger.codegen._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -@RunWith(classOf[JUnitRunner]) -class ClientAuthInputTest extends FlatSpec with Matchers { - behavior of "ClientAuthInput" - - it should "read a file upload param from a 2.0 spec" in { - val input = new ClientOptInput() - - val header = "api_key:special-key,api_key:hello,X-AUTHORIZATION:0e6c11d79a,Authorization:Basic 1jz0" - input.setAuth(header) - val authValues = input.getAuthorizationValues() - authValues.size() should be(4) - - val a1 = authValues.get(0) - a1.getKeyName should be("api_key") - a1.getValue should be("special-key") - a1.getType should be("header") - - val a2 = authValues.get(1) - a2.getKeyName should be("api_key") - a2.getValue should be("hello") - a2.getType should be("header") - - val a3 = authValues.get(2) - a3.getKeyName should be("X-AUTHORIZATION") - a3.getValue should be("0e6c11d79a") - a3.getType should be("header") - - val a4 = authValues.get(3) - a4.getKeyName should be("Authorization") - a4.getValue should be("Basic 1jz0") - a4.getType should be("header") - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala deleted file mode 100644 index 577234bac392..000000000000 --- a/modules/swagger-codegen/src/test/scala/Java/JavaInheritanceTest.scala +++ /dev/null @@ -1,25 +0,0 @@ -package Java - -import io.swagger.codegen.languages.JavaClientCodegen -import io.swagger.models.{ComposedModel, ModelImpl, RefModel} -import io.swagger.models.properties.StringProperty -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class JavaInheritanceTest extends FlatSpec with Matchers { - it should "convert a composed model" in { - val model = new ComposedModel().parent(new RefModel("Base")).child(new ModelImpl().additionalProperties(new StringProperty())) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.parent should be("Base") - cm.imports.asScala should be(Set("Base")) - } -} diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala deleted file mode 100644 index 30a70ca6dfbc..000000000000 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelEnumTest.scala +++ /dev/null @@ -1,85 +0,0 @@ -package Java - -import io.swagger.codegen.languages.JavaClientCodegen -import io.swagger.models._ -import io.swagger.models.properties._ -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.{FlatSpec, Matchers} - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class JavaModelEnumTest extends FlatSpec with Matchers { - - it should "convert a java model with an enum" in { - val enumProperty = new StringProperty() - enumProperty.setEnum(List("VALUE1", "VALUE2", "VALUE3").asJava) - val model = new ModelImpl() - .property("name", enumProperty) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.vars.size should be(1) - val enumVar = cm.vars.get(0) - enumVar.baseName should be("name") - enumVar.datatype should be("String") - enumVar.datatypeWithEnum should be("NameEnum") - enumVar.name should be("name") - enumVar.defaultValue should be("null") - enumVar.baseType should be("String") - enumVar.isEnum should equal(true) - } - - it should "not override identical parent enums" in { - - val identicalEnumProperty = new StringProperty() - identicalEnumProperty.setEnum(List("VALUE1", "VALUE2", "VALUE3").asJava) - - val subEnumProperty = new StringProperty() - subEnumProperty.setEnum(List("SUB1", "SUB2", "SUB3").asJava) - - // Add one enum ptoperty to the parent - val parentProperties = new java.util.HashMap[String, Property]() - parentProperties.put("sharedThing", identicalEnumProperty) - - // Add TWO enums to the subType model; one of which is identical to the one in parent class - val subProperties = new java.util.HashMap[String, Property]() - subProperties.put("sharedThing", identicalEnumProperty) - subProperties.put("unsharedThing", identicalEnumProperty) - - val parentModel = new ModelImpl(); - parentModel.setProperties(parentProperties); - parentModel.name("parentModel"); - - val subModel = new ModelImpl(); - subModel.setProperties(subProperties); - subModel.name("subModel"); - - val model = new ComposedModel() - .parent(new RefModel(parentModel.getName())) - .child(subModel) - .interfaces(new java.util.ArrayList[RefModel]()) - - val codegen = new JavaClientCodegen() - val allModels = new java.util.HashMap[String, Model]() - allModels.put(codegen.toModelName(parentModel.getName()), parentModel) - allModels.put(codegen.toModelName(subModel.getName()), subModel) - - val cm = codegen.fromModel("sample", model, allModels) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.parent should be("ParentModel") - cm.imports.asScala should be(Set("ParentModel")) - - // Assert that only the unshared/uninherited enum remains - cm.vars.size should be (1) - val enumVar = cm.vars.get(0) - enumVar.baseName should be("unsharedThing") - enumVar.datatype should be("String") - enumVar.datatypeWithEnum should be("UnsharedThingEnum") - enumVar.isEnum should equal(true) - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala b/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala deleted file mode 100644 index 1d044fbfdbec..000000000000 --- a/modules/swagger-codegen/src/test/scala/Java/JavaModelTest.scala +++ /dev/null @@ -1,445 +0,0 @@ -package Java - -import io.swagger.codegen.languages.JavaClientCodegen -import io.swagger.models._ -import io.swagger.models.parameters._ -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 - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class JavaModelTest extends FlatSpec with Matchers { - it should "convert a simple java model" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).getter should be("getId") - vars.get(0).setter should be("setId") - vars.get(0).datatype should be("Long") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("Long") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("name") - vars.get(1).getter should be("getName") - vars.get(1).setter should be("setName") - vars.get(1).datatype should be("String") - vars.get(1).name should be("name") - vars.get(1).defaultValue should be("null") - vars.get(1).baseType should be("String") - vars.get(1).hasMore should equal(true) - vars.get(1).required should equal(true) - vars.get(1).isNotContainer should equal(true) - - vars.get(2).baseName should be("createdAt") - vars.get(2).getter should be("getCreatedAt") - vars.get(2).setter should be("setCreatedAt") - vars.get(2).datatype should be("Date") - vars.get(2).name should be("createdAt") - vars.get(2).defaultValue should be("null") - vars.get(2).baseType should be("Date") - vars.get(2).hasMore should equal(null) - vars.get(2).required should equal(null) - vars.get(2).isNotContainer should equal(true) - } - - it should "convert a model with list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id") - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(2) - - val vars = cm.vars - vars.get(1).baseName should be("urls") - vars.get(1).getter should be("getUrls") - vars.get(1).setter should be("setUrls") - vars.get(1).datatype should be("List") - vars.get(1).name should be("urls") - vars.get(1).defaultValue should be("new ArrayList()") - vars.get(1).baseType should be("List") - vars.get(1).containerType should be("array") - vars.get(1).required should equal(null) - vars.get(1).isContainer should equal(true) - } - - it should "convert a model with a map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id") - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("translations") - vars.get(0).getter should be("getTranslations") - vars.get(0).setter should be("setTranslations") - vars.get(0).datatype should be("Map") - vars.get(0).name should be("translations") - vars.get(0).defaultValue should be("new HashMap()") - vars.get(0).baseType should be("Map") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - - it should "convert a model with a map with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties( - new ArrayProperty().items(new RefProperty("Pet"))) - ) - .required("id") - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("translations") - vars.get(0).getter should be("getTranslations") - vars.get(0).setter should be("setTranslations") - vars.get(0).datatype should be("Map>") - vars.get(0).name should be("translations") - vars.get(0).defaultValue should be("new HashMap>()") - vars.get(0).baseType should be("Map") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert a model with a 2D list property" in { - val model = new ModelImpl().name("sample").property("list2D", new ArrayProperty().items( - new ArrayProperty().items(new RefProperty("Pet")))) - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - val vars = cm.vars - vars.size should be (1) - val list = vars.get(0) - list.baseName should be("list2D") - list.getter should be("getList2D") - list.setter should be("setList2D") - list.datatype should be("List>") - list.name should be("list2D") - list.defaultValue should be ("new ArrayList>()") - list.baseType should be("List") - list.containerType should be("array") - list.required should equal(null) - list.isContainer should equal(true) - } - - it should "convert a model with complex properties" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).getter should be("getChildren") - vars.get(0).setter should be("setChildren") - vars.get(0).datatype should be("Children") - vars.get(0).name should be("children") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("Children") - vars.get(0).required should equal(null) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).complexType should be("Children") - vars.get(0).getter should be("getChildren") - vars.get(0).setter should be("setChildren") - vars.get(0).datatype should be("List") - vars.get(0).name should be("children") - vars.get(0).defaultValue should be("new ArrayList()") - vars.get(0).baseType should be("List") - vars.get(0).containerType should be("array") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert a model with complex map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - (cm.imports.asScala.toSet & Set("Map", "List", "Children")).size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).complexType should be("Children") - vars.get(0).getter should be("getChildren") - vars.get(0).setter should be("setChildren") - vars.get(0).datatype should be("Map") - vars.get(0).name should be("children") - vars.get(0).defaultValue should be("new HashMap()") - vars.get(0).baseType should be("Map") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - vars.get(0).isNotContainer should be(null) - } - - it should "convert an array model" in { - val model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")) - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an array model") - cm.vars.size should be(0) - cm.parent should be("ArrayList") - cm.imports.size should be(3) - (cm.imports.asScala.toSet & Set("List", "ArrayList", "Children")).size should be(3) - } - - it should "convert an map model" in { - val model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an map model") - cm.vars.size should be(0) - cm.parent should be("HashMap") - cm.imports.size should be(3) - (cm.imports.asScala.toSet & Set("Map", "HashMap", "Children")).size should be(3) - } - - it should "convert a model with upper-case property names" in { - val model = new ModelImpl() - .description("a model with upper-case property names") - .property("NAME", new StringProperty()) - .required("NAME") - - 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 - vars.get(0).baseName should be("NAME") - vars.get(0).getter should be("getNAME") - vars.get(0).setter should be("setNAME") - vars.get(0).datatype should be("String") - vars.get(0).name should be("NAME") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("String") - vars.get(0).hasMore should equal(null) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with a 2nd char upper-case property names" in { - val model = new ModelImpl() - .description("a model with a 2nd char upper-case property names") - .property("pId", new StringProperty()) - .required("pId") - - 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 - vars.get(0).baseName should be("pId") - vars.get(0).getter should be("getPId") - vars.get(0).setter should be("setPId") - vars.get(0).datatype should be("String") - vars.get(0).name should be("pId") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("String") - vars.get(0).hasMore should equal(null) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert hyphens per issue 503" in { - val model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - val vars = cm.vars - vars.get(0).baseName should be("created-at") - vars.get(0).getter should be("getCreatedAt") - vars.get(0).setter should be("setCreatedAt") - vars.get(0).name should be("createdAt") - } - - it should "convert query[password] to queryPassword" in { - val model = new ModelImpl() - .description("a sample model") - .property("query[password]", new StringProperty()) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - val vars = cm.vars - vars.get(0).baseName should be("query[password]") - vars.get(0).getter should be("getQueryPassword") - vars.get(0).setter should be("setQueryPassword") - vars.get(0).name should be("queryPassword") - } - - it should "properly escape names per 567" in { - val model = new ModelImpl() - .description("a sample model") - .property("created-at", new DateTimeProperty()) - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("with.dots", model) - val vars = cm.vars - cm.classname should be("WithDots") - } - - it should "convert a modelwith binary data" in { - val model = new ModelImpl() - .description("model with binary") - .property("inputBinaryData", new ByteArrayProperty()); - - val codegen = new JavaClientCodegen() - val cm = codegen.fromModel("sample", model) - val vars = cm.vars - - vars.get(0).baseName should be ("inputBinaryData") - vars.get(0).getter should be ("getInputBinaryData") - vars.get(0).setter should be ("setInputBinaryData") - vars.get(0).datatype should be ("byte[]") - vars.get(0).name should be ("inputBinaryData") - vars.get(0).defaultValue should be ("null") - vars.get(0).baseType should be ("byte[]") - vars.get(0).hasMore should equal (null) - vars.get(0).required should equal (null) - vars.get(0).isNotContainer should equal (true) - - } -} - - -@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 - 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) - } - - it should "convert a parameter" in { - val parameter = new QueryParameter() - .property( - new IntegerProperty()) - .name("limit") - .required(true) - - val codegen = new JavaClientCodegen() - val cp = codegen.fromParameter(parameter, null) - - cp.allowableValues should be (null) - } -} diff --git a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala b/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala deleted file mode 100644 index 21b62b29d785..000000000000 --- a/modules/swagger-codegen/src/test/scala/SwaggerMigratorTest.scala +++ /dev/null @@ -1,14 +0,0 @@ -import io.swagger.parser._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -@RunWith(classOf[JUnitRunner]) -class SwaggerMigratorTest extends FlatSpec with Matchers { - behavior of "SwaggerMigrator" - - it should "read a 1.2 spec" in { - val loader = new SwaggerParser() - val swagger = loader.read("src/test/resources/1_2/petstore-1.2/api-docs") - } -} \ No newline at end of file diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index dbb092e98163..5576bf1891aa 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -35,44 +35,6 @@ - - net.alchim31.maven - scala-maven-plugin - - - scala-test-compile - process-test-resources - - testCompile - - - - - - incremental - - - -Xmx384m - - - -target:jvm-1.6 - -deprecation - - - - run-scalatest - org.scalatest.tools.Runner - - -p - ${project.build.testOutputDirectory} - - - -Xmx512m - - - - - org.apache.maven.plugins maven-war-plugin @@ -241,28 +203,8 @@ - org.scalatest - scalatest_2.11 - ${scala-test-version} - test - - - junit - junit - ${junit-version} - test - - - org.scala-lang - scala-library - ${scala-version} - test - - - org.scala-lang - scala-compiler - ${scala-version} - test + org.testng + testng diff --git a/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java b/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java new file mode 100644 index 000000000000..c5cc99461f30 --- /dev/null +++ b/modules/swagger-generator/src/test/java/io/swagger/generator/GeneratorInputTest.java @@ -0,0 +1,14 @@ +package io.swagger.generator; + +import io.swagger.generator.model.GeneratorInput; + +import org.testng.annotations.Test; + +public class GeneratorInputTest { + + @Test(description = "write an object") + public void writeObjectTest() { + final GeneratorInput generatorInput = new GeneratorInput(); + generatorInput.setSwaggerUrl("http://petstore.swagger.io/v2/swagger.json"); + } +} diff --git a/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala b/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala deleted file mode 100644 index e71849db42bd..000000000000 --- a/modules/swagger-generator/src/test/scala/GeneratorInputTest.scala +++ /dev/null @@ -1,12 +0,0 @@ -import io.swagger.generator.model._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -@RunWith(classOf[JUnitRunner]) -class GeneratorInputTest extends FlatSpec with Matchers { - it should "write an object" in { - val obj = new GeneratorInput() - obj.setSwaggerUrl("http://petstore.swagger.io/v2/swagger.json") - } -} \ No newline at end of file From 19d8766363631a685a53fed6b91cc495234fb95f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Bala=CC=81zs=20Varga?= Date: Tue, 29 Sep 2015 10:07:51 +0200 Subject: [PATCH 140/219] Fix model inheritance. --- .../src/main/resources/objc/model-header.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache index c3f3c8654240..f9a330424912 100644 --- a/modules/swagger-codegen/src/main/resources/objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/model-header.mustache @@ -16,7 +16,7 @@ @protocol {{classname}} @end -@interface {{classname}} : {{classPrefix}}Object +@interface {{classname}} : {{#parent}}{{{parent}}}{{/parent}}{{^parent}}{{classPrefix}}Object{{/parent}} {{#vars}} {{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} From 17bdd738919b96d433391f485ebe1d0d5b599b1c Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 30 Sep 2015 16:28:17 +0800 Subject: [PATCH 141/219] fix springmvc by removing import of Object --- .../languages/SpringMVCServerCodegen.java | 13 +++++++++ .../java/io/swagger/client/ApiClient.java | 2 +- .../java/io/swagger/client/ApiException.java | 2 +- .../java/io/swagger/client/Configuration.java | 2 +- .../src/main/java/io/swagger/client/JSON.java | 2 +- .../src/main/java/io/swagger/client/Pair.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../main/java/io/swagger/client/TypeRef.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 4 +-- .../java/io/swagger/client/api/StoreApi.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 2 +- .../io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../swagger/client/auth/Authentication.java | 2 +- .../io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 2 +- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 4 +-- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- .../java/io/swagger/api/ApiException.java | 2 +- .../java/io/swagger/api/ApiOriginFilter.java | 2 +- .../io/swagger/api/ApiResponseMessage.java | 2 +- .../io/swagger/api/NotFoundException.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 27 ++++++++++++++----- .../main/java/io/swagger/api/StoreApi.java | 7 +++-- .../src/main/java/io/swagger/api/UserApi.java | 21 ++++++++++----- .../swagger/configuration/SwaggerConfig.java | 2 +- .../configuration/SwaggerUiConfiguration.java | 2 +- .../swagger/configuration/WebApplication.java | 2 +- .../configuration/WebMvcConfiguration.java | 2 +- .../main/java/io/swagger/model/Category.java | 2 +- .../src/main/java/io/swagger/model/Order.java | 2 +- .../src/main/java/io/swagger/model/Pet.java | 2 +- .../src/main/java/io/swagger/model/Tag.java | 2 +- .../src/main/java/io/swagger/model/User.java | 2 +- 36 files changed, 87 insertions(+), 49 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 863a1aef2e70..6bd64b0e4f68 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -12,6 +12,7 @@ import java.util.HashSet; import java.util.List; import java.util.Map; +import java.util.Iterator; public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.api"; @@ -187,5 +188,17 @@ public String toApiName(String name) { public void setConfigPackage(String configPackage) { this.configPackage = configPackage; } + + @Override + public Map postProcessModels(Map objs) { + // remove the import of "Object" to avoid compilation error + List> imports = (List>) objs.get("imports"); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.endsWith(".Object")) iterator.remove(); + } + return objs; + } } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index 0942d0bd0dd5..c4b1153dcd28 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-24T21:52:56.159+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index 88761f16e9cb..649e4132cb04 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index 47acca1b8ea0..e7837fa47a5c 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java index dd716e6fd90a..19c2420656ad 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java @@ -6,7 +6,7 @@ import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class JSON { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 0bff951077c6..78c15c6c2a01 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index df5670a8b0d3..2348914456a9 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java index 12a842d84048..a0ebe355071e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 3a14b07dc259..ca9111f41764 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class PetApi { private ApiClient apiClient; @@ -272,7 +272,7 @@ public Pet getPetById (Long petId) throws ApiException { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key", "petstore_auth" }; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index a7c73b93fa7b..f0628c595c98 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index dd798e3e7974..3412c565b376 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 84461023650e..69d80c755b84 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index efb1fc172ea8..0c254861af47 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 1c3b905baeda..19dfa96e9f20 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index a5d6fa740404..ef89432a3598 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java index f3ba53b985dc..ea615a58e98b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index 35757b9101be..b51be0c52e03 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -10,7 +10,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-21T17:24:54.566+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index f346800528d5..aca4848ff988 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -2,8 +2,8 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; +import java.util.*; @@ -12,7 +12,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-21T17:24:54.566+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java index 4fd62f39a6be..98ff0c44e177 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java index df035a093e14..f4a80143b91f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:58.351+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") public class User { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java index d5cc468f9183..f761d3871daf 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java index 4e9fe92b80ca..432c49d5d5cd 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java index 5b1085f05d46..c606c9398f49 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java index 04c8e861b3af..9c93b025ef93 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index ae26430d13e8..ae731880a173 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -30,7 +30,7 @@ @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class PetApi { @@ -45,7 +45,8 @@ public class PetApi { method = RequestMethod.PUT) public ResponseEntity updatePet( -@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) +@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -62,7 +63,8 @@ public ResponseEntity updatePet( method = RequestMethod.POST) public ResponseEntity addPet( -@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) +@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -80,6 +82,7 @@ public ResponseEntity addPet( method = RequestMethod.GET) public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + ) throws NotFoundException { // do some magic! @@ -98,6 +101,7 @@ public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status valu method = RequestMethod.GET) public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + ) throws NotFoundException { // do some magic! @@ -117,6 +121,7 @@ public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filte method = RequestMethod.GET) public ResponseEntity getPetById( @ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId + ) throws NotFoundException { // do some magic! @@ -134,15 +139,18 @@ public ResponseEntity getPetById( method = RequestMethod.POST) public ResponseEntity updatePetWithForm( @ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId + , -@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name +, -@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -159,9 +167,11 @@ public ResponseEntity updatePetWithForm( method = RequestMethod.DELETE) public ResponseEntity deletePet( @ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + , @ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey + ) throws NotFoundException { // do some magic! @@ -179,14 +189,17 @@ public ResponseEntity deletePet( method = RequestMethod.POST) public ResponseEntity uploadFile( @ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + , -@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata +, -@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail) +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile file +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 1da00f9bfa72..577052883c0e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -30,7 +30,7 @@ @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class StoreApi { @@ -59,7 +59,8 @@ public ResponseEntity> getInventory() method = RequestMethod.POST) public ResponseEntity placeOrder( -@ApiParam(value = "order placed for purchasing the pet" ) Order body) +@ApiParam(value = "order placed for purchasing the pet" ) Order body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -78,6 +79,7 @@ public ResponseEntity placeOrder( method = RequestMethod.GET) public ResponseEntity getOrderById( @ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId + ) throws NotFoundException { // do some magic! @@ -96,6 +98,7 @@ public ResponseEntity getOrderById( method = RequestMethod.DELETE) public ResponseEntity deleteOrder( @ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 13ef255488bb..6a68c27ae39f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -30,7 +30,7 @@ @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class UserApi { @@ -43,7 +43,8 @@ public class UserApi { method = RequestMethod.POST) public ResponseEntity createUser( -@ApiParam(value = "Created user object" ) User body) +@ApiParam(value = "Created user object" ) User body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -60,7 +61,8 @@ public ResponseEntity createUser( method = RequestMethod.POST) public ResponseEntity createUsersWithArrayInput( -@ApiParam(value = "List of user object" ) List body) +@ApiParam(value = "List of user object" ) List body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -77,7 +79,8 @@ public ResponseEntity createUsersWithArrayInput( method = RequestMethod.POST) public ResponseEntity createUsersWithListInput( -@ApiParam(value = "List of user object" ) List body) +@ApiParam(value = "List of user object" ) List body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -95,9 +98,11 @@ public ResponseEntity createUsersWithListInput( method = RequestMethod.GET) public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + , @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + ) throws NotFoundException { // do some magic! @@ -131,7 +136,8 @@ public ResponseEntity logoutUser() method = RequestMethod.GET) public ResponseEntity getUserByName( -@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true ) @PathVariable("username") String username + ) throws NotFoundException { // do some magic! @@ -150,10 +156,12 @@ public ResponseEntity getUserByName( method = RequestMethod.PUT) public ResponseEntity updateUser( @ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + , -@ApiParam(value = "Updated user object" ) User body) +@ApiParam(value = "Updated user object" ) User body +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -171,6 +179,7 @@ public ResponseEntity updateUser( method = RequestMethod.DELETE) public ResponseEntity deleteUser( @ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java index d15249c8d74f..58564e526261 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -18,7 +18,7 @@ @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index 2732a7c04917..ead813573312 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java index 1799d0da80aa..3c42b3f838ae 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 629e5580e64b..4c973c218889 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index 734f3b75e79a..d023688b5e50 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index d58ff96620d1..87b8633767a5 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index a86d7296ec7d..5f4de45616e0 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index d87fc671fbb7..6b2b0e6c1163 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 1ef45c4bc669..97044d2a1e7b 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-08-23T14:20:14.172-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") public class User { private Long id = null; From d2d6ff661ae4c3f85674cf0806ee87e787f3c220 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 30 Sep 2015 17:24:11 +0800 Subject: [PATCH 142/219] fix parameter name in dynamic html --- .../swagger-static/operation.mustache | 2 +- samples/dynamic-html/docs/index.html | 36 +++++++++---------- .../dynamic-html/docs/operations/PetApi.html | 16 ++++----- .../dynamic-html/docs/operations/UserApi.html | 2 +- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache index c2c70aa906de..bd7b7444c8fc 100644 --- a/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache +++ b/modules/swagger-codegen/src/main/resources/swagger-static/operation.mustache @@ -23,7 +23,7 @@ {{#isPathParam}}Path: {{/isPathParam}} {{#isHeaderParam}}Header: {{/isHeaderParam}} {{#isBodyParam}}Body: {{/isBodyParam}} - {{paramName}} + {{baseName}} {{dataType}}{{#baseType}}({{baseType}}){{/baseType}} {{#optional}}(optional){{/optional}}

{{description}}

diff --git a/samples/dynamic-html/docs/index.html b/samples/dynamic-html/docs/index.html index 1b7ba98febb8..22ed5d50b68d 100644 --- a/samples/dynamic-html/docs/index.html +++ b/samples/dynamic-html/docs/index.html @@ -60,18 +60,26 @@

@@ -79,26 +87,18 @@

diff --git a/samples/dynamic-html/docs/operations/PetApi.html b/samples/dynamic-html/docs/operations/PetApi.html index 0c7bb8bd1898..08e1cd1d42c6 100644 --- a/samples/dynamic-html/docs/operations/PetApi.html +++ b/samples/dynamic-html/docs/operations/PetApi.html @@ -206,25 +206,25 @@

Parameters

  • + Path: - Header: - apiKey - String + petId + Long -

    +

    Pet id to delete

  • - Path: + Header: - petId - Long + api_key + String -

    Pet id to delete

    +

  • diff --git a/samples/dynamic-html/docs/operations/UserApi.html b/samples/dynamic-html/docs/operations/UserApi.html index f3af4dcaa769..8639fdfbf9f8 100644 --- a/samples/dynamic-html/docs/operations/UserApi.html +++ b/samples/dynamic-html/docs/operations/UserApi.html @@ -161,7 +161,7 @@

    Parameters

    username String -

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

    +

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

    From f483f934d8db8d0f17874b2ae273ceedd9990630 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 30 Sep 2015 19:45:45 +0800 Subject: [PATCH 143/219] Add some SSL options Java okhttp-gson client * Add the `verifyingSsl` option to allow skipping verifying SSL certificate and host name (default to verify) * Add `sslCaCert` to allow customizing the CA certificates --- .../io/swagger/codegen/DefaultCodegen.java | 4 +- .../libraries/okhttp-gson/ApiClient.mustache | 119 +++++++++++++++++- .../java/io/swagger/client/ApiClient.java | 119 +++++++++++++++++- 3 files changed, 239 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 7681d0cc3c6f..6a65c6c4add6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1299,7 +1299,9 @@ public List fromSecurity(Map sec.flow = oauth2Definition.getFlow(); sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); sec.tokenUrl = oauth2Definition.getTokenUrl(); - sec.scopes = oauth2Definition.getScopes().keySet(); + if (oauth2Definition.getScopes() != null) { + sec.scopes = oauth2Definition.getScopes().keySet(); + } } sec.hasMore = it.hasNext(); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index c1a3ea44c373..df36a8b5483a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -30,13 +30,31 @@ import java.net.URLEncoder; import java.net.URLConnection; import java.io.File; +import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + import okio.BufferedSink; import okio.Okio; @@ -64,12 +82,17 @@ public class ApiClient { private String datetimeFormat; private DateFormat datetimeFormatter; + private InputStream sslCaCert; + private boolean verifyingSsl; + private OkHttpClient httpClient; private JSON json; public ApiClient() { httpClient = new OkHttpClient(); + verifyingSsl = true; + json = new JSON(this); // Use ISO 8601 format for date and datetime. @@ -134,6 +157,35 @@ public class ApiClient { return responseHeaders; } + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + public String getDateFormat() { return dateFormat; } @@ -501,7 +553,7 @@ public class ApiClient { } /** - * Deserialize response body to Java object, according the Content-Type + * Deserialize response body to Java object, according to the Content-Type * response header. * * @param response HTTP response @@ -840,4 +892,69 @@ public class ApiClient { return contentType; } } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java index e68d6ab3cb26..52a414252c51 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/ApiClient.java @@ -30,13 +30,31 @@ import java.net.URLConnection; import java.io.File; +import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; + import java.text.DateFormat; import java.text.SimpleDateFormat; import java.text.ParseException; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.KeyManager; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + import okio.BufferedSink; import okio.Okio; @@ -64,12 +82,17 @@ public class ApiClient { private String datetimeFormat; private DateFormat datetimeFormatter; + private InputStream sslCaCert; + private boolean verifyingSsl; + private OkHttpClient httpClient; private JSON json; public ApiClient() { httpClient = new OkHttpClient(); + verifyingSsl = true; + json = new JSON(this); // Use ISO 8601 format for date and datetime. @@ -133,6 +156,35 @@ public Map> getResponseHeaders() { return responseHeaders; } + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + public String getDateFormat() { return dateFormat; } @@ -500,7 +552,7 @@ public String escapeString(String str) { } /** - * Deserialize response body to Java object, according the Content-Type + * Deserialize response body to Java object, according to the Content-Type * response header. * * @param response HTTP response @@ -839,4 +891,69 @@ public String guessContentTypeFromFile(File file) { return contentType; } } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + KeyManager[] keyManagers = null; + TrustManager[] trustManagers = null; + HostnameVerifier hostnameVerifier = null; + if (!verifyingSsl) { + TrustManager trustAll = new X509TrustManager() { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} + @Override + public X509Certificate[] getAcceptedIssuers() { return null; } + }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + trustManagers = new TrustManager[]{ trustAll }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { return true; } + }; + } else if (sslCaCert != null) { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + trustManagerFactory.init(caKeyStore); + trustManagers = trustManagerFactory.getTrustManagers(); + } + + if (keyManagers != null || trustManagers != null) { + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient.setSslSocketFactory(sslContext.getSocketFactory()); + } else { + httpClient.setSslSocketFactory(null); + } + httpClient.setHostnameVerifier(hostnameVerifier); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } } From 3c98e32765b017e9ccd37fbfe2171d0da6b6172e Mon Sep 17 00:00:00 2001 From: Ivan Ushankin Date: Wed, 30 Sep 2015 17:33:04 +0300 Subject: [PATCH 144/219] Issue #1304: Migrate tests from the Scala to the plain Java. Part 2 --- .../swagger/codegen/java/JavaModelTest.java | 6 +- .../swagger/codegen/objc/ObjcModelTest.java | 275 ++++++++++++++++++ .../io/swagger/codegen/php/PhpModelTest.java | 243 ++++++++++++++++ .../io/swagger/codegen/python/PythonTest.java | 37 +++ .../src/test/scala/Objc/ObjcModelTest.scala | 255 ---------------- .../src/test/scala/php/PhpModelTest.scala | 257 ---------------- .../src/test/scala/python/PythonTest.scala | 32 -- 7 files changed, 558 insertions(+), 547 deletions(-) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java delete mode 100644 modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/python/PythonTest.scala diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java index 49641701f62d..dc815e351aa9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/java/JavaModelTest.java @@ -252,7 +252,7 @@ public void complexMapPropertyTest() { Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a sample model"); Assert.assertEquals(cm.vars.size(), 1); - Assert.assertEquals(Sets.union(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "List", "Children")).size(), 3); final CodegenProperty property = cm.vars.get(0); Assert.assertEquals(property.baseName, "children"); @@ -284,7 +284,7 @@ public void arrayModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "ArrayList"); Assert.assertEquals(cm.imports.size(), 3); - Assert.assertEquals(Sets.union(cm.imports, Sets.newHashSet("List", "ArrayList", "Children")).size(), 3); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("List", "ArrayList", "Children")).size(), 3); } @Test(description = "convert an map model") @@ -301,7 +301,7 @@ public void mapModelTest() { Assert.assertEquals(cm.vars.size(), 0); Assert.assertEquals(cm.parent, "HashMap"); Assert.assertEquals(cm.imports.size(), 3); - Assert.assertEquals(Sets.union(cm.imports, Sets.newHashSet("Map", "HashMap", "Children")).size(), 3); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Map", "HashMap", "Children")).size(), 3); } @Test(description = "convert a model with upper-case property names") diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java new file mode 100644 index 000000000000..f48f20ce1191 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/objc/ObjcModelTest.java @@ -0,0 +1,275 @@ +package io.swagger.codegen.objc; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.ObjcClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Path; +import io.swagger.models.Swagger; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; +import io.swagger.parser.SwaggerParser; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.Map; + +public class ObjcModelTest { + + @Test(description = "convert a simple java model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "NSNumber*"); + Assert.assertEquals(property1.name, "_id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "NSNumber"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "NSString*"); + Assert.assertEquals(property2.name, "name"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "NSString"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.datatype, "NSDate*"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertNull(property3.defaultValue); + Assert.assertEquals(property3.baseType, "NSDate"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "NSNumber*"); + Assert.assertEquals(property1.name, "_id"); + Assert.assertNull(property1.defaultValue); + Assert.assertEquals(property1.baseType, "NSNumber"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.datatype, "NSArray* /* NSString */"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertNull(property2.defaultValue); + Assert.assertEquals(property2.baseType, "NSArray"); + Assert.assertNull(property2.hasMore); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertNull(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "translations"); + Assert.assertEquals(property1.datatype, "NSDictionary* /* NSString, NSString */"); + Assert.assertEquals(property1.name, "translations"); + Assert.assertEquals(property1.baseType, "NSDictionary"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertTrue(property1.isPrimitiveType); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.datatype, "SWGChildren*"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "SWGChildren"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "SWGChildren"); + Assert.assertEquals(property1.datatype, "NSArray*"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "NSArray"); + Assert.assertEquals(property1.containerType, "array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("SWGChildren")).size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "SWGChildren"); + Assert.assertEquals(property1.datatype, "NSDictionary* /* NSString, SWGChildren */"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "NSDictionary"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertNull(property1.isNotContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "NSMutableArray"); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("SWGChildren")).size(), 1); + } + + @Test(description = "convert an map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("a map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new ObjcClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "SWGSample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "NSMutableDictionary"); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("SWGChildren")).size(), 1); + } + + @Test(description = "create proper imports per #316") + public void issue316Test() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/postBodyTest.json"); + final DefaultCodegen codegen = new ObjcClientCodegen(); + + final Map animalPaths = model.getPaths(); + + final Path animalOps = animalPaths.get("/animals"); + Assert.assertNotNull(animalOps.getPost()); + + final CodegenOperation animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()); + Assert.assertEquals(animalCo.imports.size(), 1); + Assert.assertTrue(animalCo.imports.contains("SWGAnimal")); + + final Map insectPaths = model.getPaths(); + final Path insectOps = insectPaths.get("/insects"); + Assert.assertNotNull(insectOps.getPost()); + + final CodegenOperation insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()); + Assert.assertEquals(insectCo.imports.size(), 1); + Assert.assertTrue(insectCo.imports.contains("SWGInsect")); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java new file mode 100644 index 000000000000..52ca64f2f596 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/php/PhpModelTest.java @@ -0,0 +1,243 @@ +package io.swagger.codegen.php; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.PhpClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class PhpModelTest { + + @Test(description = "convert a simple php model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + Assert.assertEquals(cm.imports.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "string"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "string"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, "\\DateTime"); + Assert.assertEquals(property3.datatype, "\\DateTime"); + Assert.assertEquals(property3.name, "created_at"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.baseType, "\\DateTime"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "int"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "int"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isPrimitiveType); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.datatype, "string[]"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertEquals(property2.baseType, "array"); + Assert.assertNull(property2.hasMore); + Assert.assertEquals(property2.containerType, "array"); + Assert.assertNull(property2.required); + Assert.assertTrue(property2.isPrimitiveType); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "translations"); + Assert.assertEquals(property1.datatype, "map[string,string]"); + Assert.assertEquals(property1.name, "translations"); + Assert.assertEquals(property1.baseType, "map"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertTrue(property1.isPrimitiveType); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.datatype, "\\Swagger\\Client\\Model\\Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListProperty() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.datatype, "\\Swagger\\Client\\Model\\Children[]"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "array"); + Assert.assertEquals(property1.containerType, "array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapProperty() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.datatype, "map[string,\\Swagger\\Client\\Model\\Children]"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "map"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertNull(property1.isNotContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + // skip import test as import is not used by PHP codegen + } + + @Test(description = "convert an map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("a map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new PhpClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.imports.size(), 2); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java new file mode 100644 index 000000000000..07c4bc76b030 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/python/PythonTest.java @@ -0,0 +1,37 @@ +package io.swagger.codegen.python; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenOperation; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.PythonClientCodegen; +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.parser.SwaggerParser; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class PythonTest { + + @Test(description = "convert a python model with dots") + public void modelTest() { + final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/v1beta3.json"); + final DefaultCodegen codegen = new PythonClientCodegen(); + + final CodegenModel simpleName = codegen.fromModel("v1beta3.Binding", swagger.getDefinitions().get("v1beta3.Binding")); + Assert.assertEquals(simpleName.name, "v1beta3.Binding"); + Assert.assertEquals(simpleName.classname, "V1beta3Binding"); + Assert.assertEquals(simpleName.classVarName, "v1beta3_binding"); + + final CodegenModel compoundName = codegen.fromModel("v1beta3.ComponentStatus", swagger.getDefinitions().get("v1beta3.ComponentStatus")); + Assert.assertEquals(compoundName.name, "v1beta3.ComponentStatus"); + Assert.assertEquals(compoundName.classname, "V1beta3ComponentStatus"); + Assert.assertEquals(compoundName.classVarName, "v1beta3_component_status"); + + final String path = "/api/v1beta3/namespaces/{namespaces}/bindings"; + final Operation operation = swagger.getPaths().get(path).getPost(); + final CodegenOperation codegenOperation = codegen.fromOperation(path, "get", operation, swagger.getDefinitions()); + Assert.assertEquals(codegenOperation.returnType, "V1beta3Binding"); + Assert.assertEquals(codegenOperation.returnBaseType, "V1beta3Binding"); + } +} diff --git a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala b/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala deleted file mode 100644 index 3d509ca1a2d8..000000000000 --- a/modules/swagger-codegen/src/test/scala/Objc/ObjcModelTest.scala +++ /dev/null @@ -1,255 +0,0 @@ -package Objc - -import io.swagger.codegen.languages.ObjcClientCodegen -import io.swagger.models._ -import io.swagger.models.properties._ -import io.swagger.parser.SwaggerParser -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class ObjcModelTest extends FlatSpec with Matchers { - - it should "convert a simple java model" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("a sample model") - cm.vars.size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("NSNumber*") - vars.get(0).name should be("_id") - vars.get(0).defaultValue should be(null) - vars.get(0).baseType should be("NSNumber") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isPrimitiveType should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("name") - vars.get(1).datatype should be("NSString*") - vars.get(1).name should be("name") - vars.get(1).defaultValue should be(null) - vars.get(1).baseType should be("NSString") - vars.get(1).hasMore should equal(true) - vars.get(1).required should equal(true) - vars.get(0).isPrimitiveType should equal(true) - vars.get(1).isNotContainer should equal(true) - - vars.get(2).baseName should be("createdAt") - vars.get(2).datatype should be("NSDate*") - vars.get(2).name should be("createdAt") - vars.get(2).defaultValue should be(null) - vars.get(2).baseType should be("NSDate") - vars.get(2).hasMore should equal(null) - vars.get(2).required should equal(null) - vars.get(2).isNotContainer should equal(true) - - } - - it should "convert a model with list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id") - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("a sample model") - cm.vars.size should be(2) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("NSNumber*") - vars.get(0).name should be("_id") - vars.get(0).defaultValue should be(null) - vars.get(0).baseType should be("NSNumber") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isPrimitiveType should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("urls") - vars.get(1).datatype should be("NSArray* /* NSString */") - vars.get(1).name should be("urls") - // vars.get(1).defaultValue should be ("null") - vars.get(1).baseType should be("NSArray") - vars.get(1).hasMore should be(null) - vars.get(1).containerType should equal("array") - vars.get(1).required should equal(null) - vars.get(1).isPrimitiveType should equal(true) - vars.get(1).isContainer should equal(true) - } - - it should "convert a model with a map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id") - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("translations") - 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") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - vars.get(0).isPrimitiveType should equal(true) - } - - it should "convert a model with complex property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")) - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).datatype should be("SWGChildren*") - vars.get(0).name should be("children") - vars.get(0).baseType should be("SWGChildren") - vars.get(0).required should equal(null) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))) - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).complexType should be("SWGChildren") - vars.get(0).datatype should be("NSArray*") - vars.get(0).name should be("children") - vars.get(0).baseType should be("NSArray") - vars.get(0).containerType should be("array") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert a model with complex map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))) - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("a sample model") - cm.vars.size should be(1) - (cm.imports.asScala.toSet & Set("SWGChildren")).size should be(1) - - 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* /* NSString, SWGChildren */") - vars.get(0).name should be("children") - vars.get(0).baseType should be("NSDictionary") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - vars.get(0).isNotContainer should be(null) - } - - it should "convert an array model" in { - val model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")) - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("an array model") - cm.vars.size should be(0) - cm.parent should be("NSMutableArray") - cm.imports.size should be(1) - (cm.imports.asScala.toSet & Set("SWGChildren")).size should be(1) - } - - it should "convert an map model" in { - val model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")) - - val codegen = new ObjcClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("SWGSample") - cm.description should be("an map model") - cm.vars.size should be(0) - cm.parent should be("NSMutableDictionary") - cm.imports.size should be(1) - (cm.imports.asScala.toSet & Set("SWGChildren")).size should be(1) - } - - it should "create proper imports per #316" in { - val model = new SwaggerParser().read("src/test/resources/2_0/postBodyTest.json") - val codegen = new ObjcClientCodegen() - - val animalPaths = model.getPaths() - val animalOps = animalPaths.get("/animals") - animalOps.getPost() should not be (null) - val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()) - animalCo.imports.size should be(1) - animalCo.imports.contains("SWGAnimal") should equal(true) - - val insectPaths = model.getPaths() - val insectOps = insectPaths.get("/insects") - insectOps.getPost() should not be (null) - val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()) - insectCo.imports.size should be(1) - insectCo.imports.contains("SWGInsect") should equal(true) - } -} diff --git a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala b/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala deleted file mode 100644 index ffb9c8683dbe..000000000000 --- a/modules/swagger-codegen/src/test/scala/php/PhpModelTest.scala +++ /dev/null @@ -1,257 +0,0 @@ -package php - -import io.swagger.codegen.languages.PhpClientCodegen -import io.swagger.models._ -import io.swagger.models.properties._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class PhpModelTest extends FlatSpec with Matchers { - - it should "convert a simple php model" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("int") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("int") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isPrimitiveType should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("name") - vars.get(1).datatype should be("string") - vars.get(1).name should be("name") - vars.get(1).defaultValue should be("null") - vars.get(1).baseType should be("string") - vars.get(1).hasMore should equal(true) - vars.get(1).required should equal(true) - vars.get(0).isPrimitiveType should equal(true) - vars.get(1).isNotContainer should equal(true) - - vars.get(2).baseName should be("createdAt") - vars.get(2).complexType should be("\\DateTime") - vars.get(2).datatype should be("\\DateTime") - vars.get(2).name should be("created_at") - vars.get(2).defaultValue should be("null") - 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(1) - } - - it should "convert a model with list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id") - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(2) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("int") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("int") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isPrimitiveType should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("urls") - 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) - vars.get(1).containerType should equal("array") - vars.get(1).required should equal(null) - vars.get(1).isPrimitiveType should equal(true) - vars.get(1).isContainer should equal(true) - } - - it should "convert a model with a map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id") - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("translations") - vars.get(0).datatype should be("map[string,string]") - vars.get(0).name should be("translations") - vars.get(0).baseType should be("map") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - vars.get(0).isPrimitiveType should equal(true) - } - - it should "convert a model with complex property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")) - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName 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) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))) - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).complexType 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("array") - vars.get(0).containerType should be("array") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert a model with complex map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))) - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - (cm.imports.asScala.toSet & Set("Children")).size should be(1) - - 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,\\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") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - vars.get(0).isNotContainer should be(null) - } - - it should "convert an array model" in { - val model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")) - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an array model") - cm.vars.size should be(0) - // skip import test as import is not used by PHP codegen - //cm.imports.size should be (1) - //(cm.imports.asScala.toSet & Set("Children")).size should be (1) - } - - it should "convert an map model" in { - val model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")) - - val codegen = new PhpClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an map model") - cm.vars.size should be(0) - cm.imports.size should be(2) - (cm.imports.asScala.toSet & Set("Children")).size should be(1) - } - - // skip import test as import is not used by PHP codegen - //it should "create proper imports per #316" in { - // val model = new SwaggerParser() - // .read("src/test/resources/2_0/postBodyTest.json") - // val codegen = new PhpClientCodegen() - - // val animalPaths = model.getPaths() - // val animalOps = animalPaths.get("/animals") - // animalOps.getPost() should not be (null) - // val animalCo = codegen.fromOperation("/animals", "POST", animalOps.getPost(), model.getDefinitions()) - // animalCo.imports should be (1) - // animalCo.imports.size should be (1) - // animalCo.imports.contains("Animal") should equal (true) - - // val insectPaths = model.getPaths() - // val insectOps = insectPaths.get("/insects") - // insectOps.getPost() should not be (null) - // val insectCo = codegen.fromOperation("/insects", "POST", insectOps.getPost(), model.getDefinitions()) - // insectCo.imports.size should be (1) - // insectCo.imports.contains("Insect") should equal (true) - //} -} diff --git a/modules/swagger-codegen/src/test/scala/python/PythonTest.scala b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala deleted file mode 100644 index 9f9570a3e79b..000000000000 --- a/modules/swagger-codegen/src/test/scala/python/PythonTest.scala +++ /dev/null @@ -1,32 +0,0 @@ -package python - -import io.swagger.codegen.languages.PythonClientCodegen -import io.swagger.parser.SwaggerParser -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -@RunWith(classOf[JUnitRunner]) -class PythonTest extends FlatSpec with Matchers { - it should "convert a python model with dots" in { - val swagger = new SwaggerParser() - .read("src/test/resources/2_0/v1beta3.json") - - val codegen = new PythonClientCodegen() - val simpleName = codegen.fromModel("v1beta3.Binding", swagger.getDefinitions().get("v1beta3.Binding")) - simpleName.name should be("v1beta3.Binding") - simpleName.classname should be("V1beta3Binding") - simpleName.classVarName should be("v1beta3_binding") - - val compoundName = codegen.fromModel("v1beta3.ComponentStatus", swagger.getDefinitions().get("v1beta3.ComponentStatus")) - compoundName.name should be("v1beta3.ComponentStatus") - compoundName.classname should be("V1beta3ComponentStatus") - compoundName.classVarName should be("v1beta3_component_status") - - val path = "/api/v1beta3/namespaces/{namespaces}/bindings" - val operation = swagger.getPaths().get(path).getPost() - val codegenOperation = codegen.fromOperation(path, "get", operation, swagger.getDefinitions()) - codegenOperation.returnType should be("V1beta3Binding") - codegenOperation.returnBaseType should be("V1beta3Binding") - } -} From 7c431a8e11ab857393fcd2bc96f18140cfb09c50 Mon Sep 17 00:00:00 2001 From: cbornet Date: Thu, 1 Oct 2015 01:03:22 +0200 Subject: [PATCH 145/219] dynamically fill swagger enum from codegen client names --- .../java/io/swagger/generator/DynamicSwaggerConfig.java | 6 ++++-- .../java/io/swagger/generator/resource/SwaggerResource.java | 4 ++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java index 4ffea72995d8..ee5792850c5a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/DynamicSwaggerConfig.java @@ -34,6 +34,7 @@ public Swagger configure(Swagger swagger) { b.append(client); } param.setDescription("available clients: " + b.toString()); + param.setEnum(clients); } } @@ -51,7 +52,8 @@ public Swagger configure(Swagger swagger) { } b.append(server); } - param.setDescription("available clients: " + b.toString()); + param.setDescription("available servers: " + b.toString()); + param.setEnum(servers); } } @@ -70,4 +72,4 @@ public Swagger configure(Swagger swagger) { } } } -} \ No newline at end of file +} diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java index 4b4494977ebf..ddfd6fa39502 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/resource/SwaggerResource.java @@ -64,7 +64,7 @@ public Response downloadFile(@PathParam("fileId") String fileId) throws Exceptio tags = "clients") public Response generateClient( @Context HttpServletRequest request, - @ApiParam(value = "The target language for the client library", allowableValues = "android,java,php,objc,docs", required = true) @PathParam("language") String language, + @ApiParam(value = "The target language for the client library", required = true) @PathParam("language") String language, @ApiParam(value = "Configuration for building the client library", required = true) GeneratorInput opts) throws Exception { String filename = Generator.generateClient(language, opts); @@ -115,7 +115,7 @@ public Response serverOptions() { tags = "servers") public Response generateServerForLanguage( @Context HttpServletRequest request, - @ApiParam(value = "framework", allowableValues = "jaxrs,nodejs", required = true) @PathParam("framework") String framework, + @ApiParam(value = "framework", required = true) @PathParam("framework") String framework, @ApiParam(value = "parameters", required = true) GeneratorInput opts) throws Exception { if (framework == null) { From 984b645ea191ce65f65dc430bdbdfdaf54fe75ec Mon Sep 17 00:00:00 2001 From: cbornet Date: Thu, 1 Oct 2015 11:09:25 +0200 Subject: [PATCH 146/219] add options to online generator Fix #1313 --- .../swagger/generator/online/Generator.java | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java index 2faef30744ba..775c96cda2ea 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/online/Generator.java @@ -5,6 +5,7 @@ import io.swagger.codegen.ClientOpts; import io.swagger.codegen.Codegen; import io.swagger.codegen.CodegenConfig; +import io.swagger.codegen.CodegenConfigLoader; import io.swagger.generator.exception.ApiException; import io.swagger.generator.exception.BadRequestException; import io.swagger.generator.model.GeneratorInput; @@ -16,6 +17,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + import java.io.File; import java.util.ArrayList; import java.util.List; @@ -52,10 +55,24 @@ public static String generateClient(String language, GeneratorInput opts) throws .opts(clientOpts) .swagger(swagger); - CodegenConfig codegenConfig = Codegen.getConfig(language); - if (codegenConfig == null) { + CodegenConfig codegenConfig=null; + try { + codegenConfig = CodegenConfigLoader.forName(language); + } catch(RuntimeException e) { throw new BadRequestException(400, "Unsupported target " + language + " supplied"); } + + if (opts.getOptions() != null) { + for(String key : new String[]{"apiPackage", "modelPackage", "invokerPackage", "groupId", "artifactId", "artifactVersion"}) { + if(isNotEmpty(opts.getOptions().get(key))) { + codegenConfig.additionalProperties().put(key , opts.getOptions().get(key)); + } + } + + if (isNotEmpty(opts.getOptions().get("library"))) { + codegenConfig.setLibrary(opts.getOptions().get("library")); + } + } codegenConfig.setOutputDir(outputFolder); From 25abc152334de7ed33f044bd982689343e8e1118 Mon Sep 17 00:00:00 2001 From: cbornet Date: Thu, 1 Oct 2015 14:00:19 +0200 Subject: [PATCH 147/219] add version to swagger.json from pom's version Fix #1314 --- modules/swagger-generator/pom.xml | 4 ++++ .../java/io/swagger/generator/Bootstrap.java | 17 ++++++++++++++++- .../src/main/resources/version.prop | 1 + 3 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 modules/swagger-generator/src/main/resources/version.prop diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 5576bf1891aa..b42a51a86af0 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -15,9 +15,13 @@ src/main/resources + true logback.xml + + **/version.prop + diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java index 0e71119e67a1..a81113ab76a1 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/Bootstrap.java @@ -16,11 +16,16 @@ package io.swagger.generator; +import java.io.IOException; +import java.io.InputStream; + import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; +import org.apache.commons.io.IOUtils; + public class Bootstrap extends HttpServlet { public void init(ServletConfig config) throws ServletException { ServletContext context = config.getServletContext(); @@ -33,7 +38,17 @@ public void init(ServletConfig config) throws ServletException { bc.setTermsOfServiceUrl("http://swagger.io/terms/"); bc.setContact("apiteam@swagger.io"); bc.setLicense("Apache 2.0"); - bc.setVersion("1.0.0"); + InputStream stream = getClass().getResourceAsStream("/version.prop"); + if(stream == null) { + bc.setVersion("0.0.0"); + } else { + try { + bc.setVersion(IOUtils.toString(stream, "UTF-8")); + stream.close(); + } catch (IOException e) { + bc.setVersion("0.0.0"); + } + } bc.setHost("generator.swagger.io"); bc.setLicenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html"); bc.setResourcePackage("io.swagger.generator.resource"); diff --git a/modules/swagger-generator/src/main/resources/version.prop b/modules/swagger-generator/src/main/resources/version.prop new file mode 100644 index 000000000000..f2ab45c3b0ef --- /dev/null +++ b/modules/swagger-generator/src/main/resources/version.prop @@ -0,0 +1 @@ +${project.version} \ No newline at end of file From 5744bb405388943766b52a0b025c2ded129abec0 Mon Sep 17 00:00:00 2001 From: cbornet Date: Thu, 1 Oct 2015 17:35:07 +0200 Subject: [PATCH 148/219] fix npe in empty operation scopes Fix #1322 --- .../io/swagger/codegen/DefaultGenerator.java | 31 ++++++++++--------- 1 file changed, 16 insertions(+), 15 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index b69f9ae56afc..990a7ffa0077 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -489,21 +489,22 @@ public void processOperation(String resourcePath, String httpMethod, Operation o SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); if (securityDefinition != null) { if(securityDefinition instanceof OAuth2Definition) { - OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; - OAuth2Definition oauth2Operation = new OAuth2Definition(); - oauth2Operation.setType(oauth2Definition.getType()); - oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); - oauth2Operation.setFlow(oauth2Definition.getFlow()); - oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); - for (String scope : security.values().iterator().next()) { - if (oauth2Definition.getScopes().containsKey(scope)) { - oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); - } - } - authMethods.put(securityName, oauth2Operation); - } else { - authMethods.put(securityName, securityDefinition); - } + OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; + OAuth2Definition oauth2Operation = new OAuth2Definition(); + oauth2Operation.setType(oauth2Definition.getType()); + oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); + oauth2Operation.setFlow(oauth2Definition.getFlow()); + oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); + oauth2Operation.setScopes(new HashMap()); + for (String scope : security.values().iterator().next()) { + if (oauth2Definition.getScopes().containsKey(scope)) { + oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); + } + } + authMethods.put(securityName, oauth2Operation); + } else { + authMethods.put(securityName, securityDefinition); + } } } if (!authMethods.isEmpty()) { From c1c3439b86fc06ff9b424e2f51eb114404608452 Mon Sep 17 00:00:00 2001 From: cbornet Date: Thu, 1 Oct 2015 17:42:33 +0200 Subject: [PATCH 149/219] fix some wrong indentations --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 990a7ffa0077..a785f45bdf21 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -488,8 +488,8 @@ public void processOperation(String resourcePath, String httpMethod, Operation o String securityName = security.keySet().iterator().next(); SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); if (securityDefinition != null) { - if(securityDefinition instanceof OAuth2Definition) { - OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; + if(securityDefinition instanceof OAuth2Definition) { + OAuth2Definition oauth2Definition = (OAuth2Definition) securityDefinition; OAuth2Definition oauth2Operation = new OAuth2Definition(); oauth2Operation.setType(oauth2Definition.getType()); oauth2Operation.setAuthorizationUrl(oauth2Definition.getAuthorizationUrl()); @@ -517,7 +517,7 @@ public void processOperation(String resourcePath, String httpMethod, Operation o + " Operation: " + operation.getOperationId() + "\n" // + " Resource: " + httpMethod + " " + resourcePath + "\n"// + " Definitions: " + swagger.getDefinitions(); - throw new RuntimeException(msg, ex); + throw new RuntimeException(msg, ex); } } } From acaf1b1cd08752fb5047cb00f6e9ca87ca676c30 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Thu, 1 Oct 2015 23:14:34 +0200 Subject: [PATCH 150/219] added Table of Contents Initial version of table of contents - showing all headers in the current shape. --- README.md | 39 +++++++++++++++++++++++++++++++++++---- 1 file changed, 35 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f7ee2b9667fd..efddb078e1fa 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,36 @@ This is the swagger codegen project, which allows generation of client libraries Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. +# Table of contents + + - [Swagger Code Generator](#swagger-code-generator) + - [Overview](#overview) + - [Table of Contents](#table-of-contents) + - [Build and run using docker](#build-and-run-using-docker) + - [Build a nodejs server stub](#build-a-nodejs-server-stub) + - [Compatibility](#compatibility) + - [Prerequisites](#prerequisites) + - [OS X Users](#os-x-users) + - [Building](#building) + - [To generate a sample client library](#to-generate-a-sample-client-library) + - [Generating libraries from your server](#generating-libraries-from-your-server) + - [Modifying the client library format](#modifying-the-client-library-format) + - [Making your own codegen modules](#making-your-own-codegen-modules) + - [Where is Javascript???](#where-is-javascript) + - [Generating a client from local files](#generating-a-client-from-local-files) + - [Customizing the generator](#customizing-the-generator) + - [Validating your swagger spec](#validating-your-swagger-spec) + - [Generating dynamic html api documentation](#generating-dynamic-html-api-documentation) + - [Generating static html api documentation](#generating-static-html-api-documentation) + - [To build a server stub](#to-build-a-server-stub) + - [node.js](#nodejs) + - [rails-grape](#rails-grape) + - [scala scalatra](#scala-scalatra) + - [java jax-rs](#java-jax-rs) + - [java spring-mvc](#java-spring-mvc) + - [To build the codegen library](#to-build-the-codegen-library) + - [License](#license) + ## Build and run using docker ``` @@ -17,7 +47,7 @@ cd swagger-codegen ./run-in-docker.sh mvn package ``` -Build a nodejs server stub: +## Build a nodejs server stub ``` ./run-in-docker.sh generate \ @@ -31,7 +61,7 @@ The Swagger Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- -2.1.4-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) +2.1.4-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) 2.1.3 (**current stable**) | 2015-08-24 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.3](https://github.com/swagger-api/swagger-codegen/tree/v2.1.3) 2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) 1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) @@ -169,7 +199,7 @@ static code generation. There is a third-party component called [swagger-js-codegen](https://github.com/wcandillon/swagger-js-codegen) that can generate angularjs or nodejs source code from a swagger specification. -#### Generating a client from flat files (i.e. no remote server calls) +#### Generating a client from local files If you don't want to call your server, you can save the swagger spec files into a directory and pass an argument to the code generator like this: @@ -336,6 +366,7 @@ open index.html You can also use the codegen to generate a server for a couple different frameworks. Take a look here: ### node.js + ``` java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ @@ -344,8 +375,8 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ ``` ### rails-grape -#### Not yet migrated to this branch +*Not yet migrated to this branch* ### scala scalatra ``` From 12d8f97aee1641e44bafd06ad6054dac96c4fa00 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Thu, 1 Oct 2015 23:26:24 +0200 Subject: [PATCH 151/219] improving ToC --- README.md | 48 +++++++++++++++++++++++++----------------------- 1 file changed, 25 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index efddb078e1fa..cf0f3a3b15f0 100644 --- a/README.md +++ b/README.md @@ -12,29 +12,31 @@ Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additi - [Swagger Code Generator](#swagger-code-generator) - [Overview](#overview) - [Table of Contents](#table-of-contents) - - [Build and run using docker](#build-and-run-using-docker) - - [Build a nodejs server stub](#build-a-nodejs-server-stub) - - [Compatibility](#compatibility) - - [Prerequisites](#prerequisites) - - [OS X Users](#os-x-users) - - [Building](#building) - - [To generate a sample client library](#to-generate-a-sample-client-library) - - [Generating libraries from your server](#generating-libraries-from-your-server) - - [Modifying the client library format](#modifying-the-client-library-format) - - [Making your own codegen modules](#making-your-own-codegen-modules) - - [Where is Javascript???](#where-is-javascript) - - [Generating a client from local files](#generating-a-client-from-local-files) - - [Customizing the generator](#customizing-the-generator) - - [Validating your swagger spec](#validating-your-swagger-spec) - - [Generating dynamic html api documentation](#generating-dynamic-html-api-documentation) - - [Generating static html api documentation](#generating-static-html-api-documentation) - - [To build a server stub](#to-build-a-server-stub) - - [node.js](#nodejs) - - [rails-grape](#rails-grape) - - [scala scalatra](#scala-scalatra) - - [java jax-rs](#java-jax-rs) - - [java spring-mvc](#java-spring-mvc) - - [To build the codegen library](#to-build-the-codegen-library) + - Installation + - [Build and run using docker](#build-and-run-using-docker) + - [Build a nodejs server stub](#build-a-nodejs-server-stub) + - [Compatibility](#compatibility) + - [Prerequisites](#prerequisites) + - [OS X Users](#os-x-users) + - [Building](#building) + - Generators + - [To generate a sample client library](#to-generate-a-sample-client-library) + - [Generating libraries from your server](#generating-libraries-from-your-server) + - [Modifying the client library format](#modifying-the-client-library-format) + - [Making your own codegen modules](#making-your-own-codegen-modules) + - [Where is Javascript???](#where-is-javascript) + - [Generating a client from local files](#generating-a-client-from-local-files) + - [Customizing the generator](#customizing-the-generator) + - [Validating your swagger spec](#validating-your-swagger-spec) + - [Generating dynamic html api documentation](#generating-dynamic-html-api-documentation) + - [Generating static html api documentation](#generating-static-html-api-documentation) + - [To build a server stub](#to-build-a-server-stub) + - [node.js](#nodejs) + - [rails-grape](#rails-grape) + - [scala scalatra](#scala-scalatra) + - [java jax-rs](#java-jax-rs) + - [java spring-mvc](#java-spring-mvc) + - [To build the codegen library](#to-build-the-codegen-library) - [License](#license) ## Build and run using docker From 4b62a943503186b8f0768627088b8ac976ac6675 Mon Sep 17 00:00:00 2001 From: Ivan Ushankin Date: Fri, 2 Oct 2015 16:18:13 +0300 Subject: [PATCH 152/219] Fixed #1304: Migrate tests from the Scala to the plain Java. Part 3 --- modules/swagger-codegen/pom.xml | 99 ------- .../java/io/swagger/codegen/CodegenTest.java | 142 ++++++++++ .../swagger/codegen/ExampleGeneratorTest.java | 72 +++++ .../swagger/codegen/scala/ScalaModelTest.java | 250 ++++++++++++++++++ .../staticDocs/StaticOperationTest.java | 61 +++++ .../TypeScriptAngularModelTest.java | 181 +++++++++++++ .../TypeScriptNodeModelTest.java | 180 +++++++++++++ .../src/test/scala/CodegenTest.scala | 157 ----------- .../src/test/scala/ExampleGeneratorTest.scala | 59 ----- .../src/test/scala/scala/ScalaModelTest.scala | 238 ----------------- .../staticDocs/StaticOperationTest.scala | 59 ----- .../TypeScriptAngularModelTest.scala | 170 ------------ .../TypeScriptNodeModelTest.scala | 170 ------------ 13 files changed, 886 insertions(+), 952 deletions(-) create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java create mode 100644 modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java delete mode 100644 modules/swagger-codegen/src/test/scala/CodegenTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala delete mode 100644 modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index c62bf655b578..3ca7295a3c90 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -70,42 +70,6 @@ - - net.alchim31.maven - scala-maven-plugin - - - - add-source - compile - testCompile - - - - - incremental - - -Xmx384m - - - -target:jvm-1.6 - -deprecation - - - - run-scalatest - org.scalatest.tools.Runner - - -p - ${project.build.testOutputDirectory} - - - -Xmx512m - - - - - maven-compiler-plugin 3.0 @@ -140,15 +104,6 @@ 2.1 - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - @@ -156,43 +111,6 @@ true - - - - net.alchim31.maven - scala-maven-plugin - - - - compile - testCompile - - - - - ${scala-version} - - - - org.codehaus.mojo - build-helper-maven-plugin - - - add-source - prepare-package - - add-source - - - - src/main/scala - - - - - - - release-sign-artifacts @@ -238,11 +156,6 @@ - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - org.apache.maven.plugins maven-jxr-plugin @@ -327,18 +240,6 @@ commons-cli ${commons-cli-version} - - org.scalatest - scalatest_2.11 - ${scala-test-version} - test - - - org.scala-lang - scala-library - ${scala-version} - test - org.testng testng diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java new file mode 100644 index 000000000000..ee70b427bfdf --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -0,0 +1,142 @@ +package io.swagger.codegen; + +import io.swagger.models.Operation; +import io.swagger.models.Swagger; +import io.swagger.models.properties.Property; +import io.swagger.parser.SwaggerParser; + +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.List; + +public class CodegenTest { + + @Test(description = "read a file upload param from a 2.0 spec") + public void fileUploadParamTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/pet/{petId}/uploadImage"; + final Operation p = model.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + + Assert.assertEquals(op.operationId, "uploadFile"); + Assert.assertEquals(op.httpMethod, "POST"); + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "multipart/form-data"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.allParams.size(), 3); + Assert.assertEquals(op.formParams.size(), 2); + + final CodegenParameter file = op.formParams.get(1); + Assert.assertTrue(file.isFormParam); + Assert.assertEquals(file.dataType, "file"); + Assert.assertNull(file.required); + Assert.assertTrue(file.isFile); + Assert.assertNull(file.hasMore); + } + + @Test(description = "read formParam values from a 2.0 spec") + public void formParamTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/pet/{petId}"; + final Operation p = model.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + + Assert.assertEquals(op.operationId, "updatePetWithForm"); + Assert.assertEquals(op.httpMethod, "POST"); + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/x-www-form-urlencoded"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 2); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); + Assert.assertEquals(op.produces.get(0).get("hasMore"), "true"); + Assert.assertEquals(op.produces.get(1).get("mediaType"), "application/xml"); + Assert.assertEquals(op.pathParams.size(), 1); + + final CodegenParameter idParam = op.pathParams.get(0); + Assert.assertTrue(idParam.isPathParam); + Assert.assertEquals(idParam.dataType, "String"); + Assert.assertTrue(idParam.required); + Assert.assertNull(idParam.hasMore); + + Assert.assertEquals(op.allParams.size(), 3); + Assert.assertEquals(op.formParams.size(), 2); + + final CodegenParameter nameParam = op.formParams.get(0); + Assert.assertTrue(nameParam.isFormParam); + Assert.assertTrue(nameParam.notFile); + Assert.assertEquals(nameParam.dataType, "String"); + Assert.assertNull(nameParam.required); + Assert.assertTrue(nameParam.hasMore); + + final CodegenParameter statusParam = op.formParams.get(1); + Assert.assertTrue(statusParam.isFormParam); + Assert.assertTrue(statusParam.notFile); + Assert.assertEquals(statusParam.dataType, "String"); + Assert.assertNull(statusParam.required); + Assert.assertNull(statusParam.hasMore); + } + + @Test(description = "handle required parameters from a 2.0 spec as required when figuring out Swagger types") + public void requiredParametersTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/requiredTest.json"); + + final DefaultCodegen codegen = new DefaultCodegen() { + public String getSwaggerType(Property p) { + if (p != null && !p.getRequired()) { + return "Optional<" + super.getSwaggerType(p) + ">"; + } + return super.getSwaggerType(p); + } + }; + final String path = "/tests/requiredParams"; + final Operation p = model.getPaths().get(path).getGet(); + final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); + + final List formParams = op.formParams; + Assert.assertEquals(formParams.size(), 2); + Assert.assertEquals(formParams.get(0).dataType, "Long"); + Assert.assertEquals(formParams.get(1).dataType, "Optional"); + Assert.assertEquals(op.returnType, "Long"); + } + + @Test(description = "select main response from a 2.0 spec using the lowest 2XX code") + public void responseSelectionTest1() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/responseSelectionTest.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/withTwoHundredAndDefault"; + final Operation p = model.getPaths().get(path).getGet(); + final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "String"); + } + + @Test(description = "select main response from a 2.0 spec using the default keyword when no 2XX code") + public void responseSelectionTest2() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/responseSelectionTest.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/withoutTwoHundredButDefault"; + final Operation p = model.getPaths().get(path).getGet(); + final CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "String"); + } + + @Test(description = "return byte array when response format is byte") + public void binaryDataTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/binaryDataTest.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/binaryResponse"; + final Operation p = model.getPaths().get(path).getPost(); + final CodegenOperation op = codegen.fromOperation(path, "post", p, model.getDefinitions()); + + Assert.assertEquals(op.returnType, "byte[]"); + Assert.assertEquals(op.bodyParam.dataType, "byte[]"); + Assert.assertTrue(op.bodyParam.isBinary); + Assert.assertTrue(op.responses.get(0).isBinary); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java new file mode 100644 index 000000000000..339b77badbd4 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ExampleGeneratorTest.java @@ -0,0 +1,72 @@ +package io.swagger.codegen; + +import io.swagger.codegen.examples.ExampleGenerator; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.Xml; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; + +public class ExampleGeneratorTest { + + @Test(description = "check handling of recursive models") + public void recursiveModelsTest() { + final String JSON = "application/json"; + final String XML = "application/xml"; + final String nodeType = "Node"; + final RefProperty ref = new RefProperty(nodeType); + final Model node = new ModelImpl().name(nodeType).property("name", new StringProperty()) + .property("parent", ref) + .property("children", new ArrayProperty(ref)) + .property("wrappedChildren", new ArrayProperty(ref).xml(new Xml().wrapped(true))); + final String pairType = "Pair"; + final ModelImpl pair = new ModelImpl().name(pairType); + for (Map.Entry item : ImmutableMap.of("first", "First", "second", "Second").entrySet()) { + final RefProperty property = new RefProperty(nodeType); + property.setXml(new Xml().name(item.getValue())); + pair.property(item.getKey(), property); + + } + final Set types = Sets.newHashSet(); + final List expectedTypes = Arrays.asList(JSON, XML); + + final ExampleGenerator eg = new ExampleGenerator(ImmutableMap.of(nodeType, node, pairType, pair)); + for (Map item : eg.generate(null, expectedTypes, new RefProperty(pairType))) { + final String example = item.get("example"); + final String contentType = item.get("contentType"); + if (XML.equals(contentType)) { + types.add(XML); + Assert.assertEquals(example, "\n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + + ""); + } else if (JSON.equals(contentType)) { + types.add(JSON); + // TODO - add JSON validation + Assert.assertNotNull(example); + } + } + + Assert.assertEqualsNoOrder(types.toArray(new String[types.size()]), + expectedTypes.toArray(new String[expectedTypes.size()])); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java new file mode 100644 index 000000000000..81290c473872 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/scala/ScalaModelTest.java @@ -0,0 +1,250 @@ +package io.swagger.codegen.scala; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.ScalaClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class ScalaModelTest { + + @Test(description = "convert a simple scala model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.getter, "getId"); + Assert.assertEquals(property1.setter, "setId"); + Assert.assertEquals(property1.datatype, "Long"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "Long"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.getter, "getName"); + Assert.assertEquals(property2.setter, "setName"); + Assert.assertEquals(property2.datatype, "String"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "String"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.getter, "getCreatedAt"); + Assert.assertEquals(property3.setter, "setCreatedAt"); + Assert.assertEquals(property3.datatype, "DateTime"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertEquals(property3.baseType, "DateTime"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty() + .items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(1); + Assert.assertEquals(property1.baseName, "urls"); + Assert.assertEquals(property1.getter, "getUrls"); + Assert.assertEquals(property1.setter, "setUrls"); + Assert.assertEquals(property1.datatype, "List[String]"); + Assert.assertEquals(property1.name, "urls"); + Assert.assertEquals(property1.defaultValue, "new ListBuffer[String]() "); + Assert.assertEquals(property1.baseType, "List"); + Assert.assertEquals(property1.containerType, "array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with a map property") + public void mapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("translations", new MapProperty() + .additionalProperties(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "translations"); + Assert.assertEquals(property1.getter, "getTranslations"); + Assert.assertEquals(property1.setter, "setTranslations"); + Assert.assertEquals(property1.datatype, "Map[String, String]"); + Assert.assertEquals(property1.name, "translations"); + Assert.assertEquals(property1.defaultValue, "new HashMap[String, String]() "); + Assert.assertEquals(property1.baseType, "Map"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with complex properties") + public void complexPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.getter, "getChildren"); + Assert.assertEquals(property1.setter, "setChildren"); + Assert.assertEquals(property1.datatype, "Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.getter, "getChildren"); + Assert.assertEquals(property1.setter, "setChildren"); + Assert.assertEquals(property1.datatype, "List[Children]"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.defaultValue, "new ListBuffer[Children]() "); + Assert.assertEquals(property1.baseType, "List"); + Assert.assertEquals(property1.containerType, "array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert a model with complex map property") + public void complexMapPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new MapProperty() + .additionalProperties(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.getter, "getChildren"); + Assert.assertEquals(property1.setter, "setChildren"); + Assert.assertEquals(property1.datatype, "Map[String, Children]"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.defaultValue, "new HashMap[String, Children]() "); + Assert.assertEquals(property1.baseType, "Map"); + Assert.assertEquals(property1.containerType, "map"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + Assert.assertNull(property1.isNotContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "ListBuffer[Children]"); + Assert.assertEquals(cm.imports.size(), 2); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("ListBuffer", "Children")).size(), 2); + } + + @Test(description = "convert an map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("a map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new ScalaClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.parent, "HashMap[String, Children]"); + Assert.assertEquals(cm.imports.size(), 2); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("HashMap", "Children")).size(), 2); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java new file mode 100644 index 000000000000..f3e08e805417 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/staticDocs/StaticOperationTest.java @@ -0,0 +1,61 @@ +package io.swagger.codegen.staticDocs; + +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.StaticDocCodegen; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import org.testng.Assert; +import org.testng.annotations.Test; + +public class StaticOperationTest { + + @Test(description = "convert a string parameter") + public void stringParameterTest() { + final StringProperty property = new StringProperty(); + final DefaultCodegen codegen = new StaticDocCodegen(); + final CodegenProperty cp = codegen.fromProperty("property", property); + + Assert.assertEquals(cp.baseName, "property"); + Assert.assertEquals(cp.datatype, "String"); + Assert.assertEquals(cp.name, "property"); + Assert.assertEquals(cp.baseType, "string"); + Assert.assertTrue(cp.isNotContainer); + } + + @Test(description = "convert a complex parameter") + public void complexParameterTest() { + final RefProperty property = new RefProperty("Children"); + final DefaultCodegen codegen = new StaticDocCodegen(); + final CodegenProperty cp = codegen.fromProperty("property", property); + + Assert.assertEquals(cp.baseName, "property"); + Assert.assertEquals(cp.complexType, "Children"); + Assert.assertEquals(cp.getter, "getProperty"); + Assert.assertEquals(cp.setter, "setProperty"); + Assert.assertEquals(cp.datatype, "Children"); + Assert.assertEquals(cp.name, "property"); + Assert.assertEquals(cp.defaultValue, "null"); + Assert.assertEquals(cp.baseType, "Children"); + Assert.assertTrue(cp.isNotContainer); + } + + @Test(description = "convert a complex list parameter") + public void listParameterTest() { + final ArrayProperty property = new ArrayProperty().items(new RefProperty("Children")); + final DefaultCodegen codegen = new StaticDocCodegen(); + final CodegenProperty cp = codegen.fromProperty("property", property); + + Assert.assertEquals(cp.baseName, "property"); + Assert.assertEquals(cp.complexType, "Children"); + Assert.assertEquals(cp.getter, "getProperty"); + Assert.assertEquals(cp.setter, "setProperty"); + Assert.assertEquals(cp.datatype, "List"); + Assert.assertEquals(cp.name, "property"); + Assert.assertEquals(cp.baseType, "array"); + Assert.assertEquals(cp.containerType, "array"); + Assert.assertTrue(cp.isContainer); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java new file mode 100644 index 000000000000..55bbbeffdba4 --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptangular/TypeScriptAngularModelTest.java @@ -0,0 +1,181 @@ +package io.swagger.codegen.typescriptangular; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.TypeScriptAngularClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class TypeScriptAngularModelTest { + + @Test(description = "convert a simple TypeScript Angular model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "string"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "string"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, "Date"); + Assert.assertEquals(property3.datatype, "Date"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty().items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.datatype, "Array"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertEquals(property2.baseType, "Array"); + Assert.assertNull(property2.hasMore); + Assert.assertNull(property2.required); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.datatype, "Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.datatype, "Array"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + } + + @Test(description = "convert a map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("a map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptAngularClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } +} diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java new file mode 100644 index 000000000000..a932ac2b5aea --- /dev/null +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/typescriptnode/TypeScriptNodeModelTest.java @@ -0,0 +1,180 @@ +package io.swagger.codegen.typescriptnode; + +import io.swagger.codegen.CodegenModel; +import io.swagger.codegen.CodegenProperty; +import io.swagger.codegen.DefaultCodegen; +import io.swagger.codegen.languages.TypeScriptNodeClientCodegen; +import io.swagger.models.ArrayModel; +import io.swagger.models.Model; +import io.swagger.models.ModelImpl; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.DateTimeProperty; +import io.swagger.models.properties.LongProperty; +import io.swagger.models.properties.RefProperty; +import io.swagger.models.properties.StringProperty; + +import com.google.common.collect.Sets; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class TypeScriptNodeModelTest { + + @Test(description = "convert a simple TypeScript Node model") + public void simpleModelTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("name", new StringProperty()) + .property("createdAt", new DateTimeProperty()) + .required("id") + .required("name"); + final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 3); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "name"); + Assert.assertEquals(property2.datatype, "string"); + Assert.assertEquals(property2.name, "name"); + Assert.assertEquals(property2.defaultValue, "null"); + Assert.assertEquals(property2.baseType, "string"); + Assert.assertTrue(property2.hasMore); + Assert.assertTrue(property2.required); + Assert.assertTrue(property2.isNotContainer); + + final CodegenProperty property3 = cm.vars.get(2); + Assert.assertEquals(property3.baseName, "createdAt"); + Assert.assertEquals(property3.complexType, "Date"); + Assert.assertEquals(property3.datatype, "Date"); + Assert.assertEquals(property3.name, "createdAt"); + Assert.assertEquals(property3.defaultValue, "null"); + Assert.assertNull(property3.hasMore); + Assert.assertNull(property3.required); + Assert.assertTrue(property3.isNotContainer); + } + + @Test(description = "convert a model with list property") + public void listPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("id", new LongProperty()) + .property("urls", new ArrayProperty().items(new StringProperty())) + .required("id"); + final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 2); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "id"); + Assert.assertEquals(property1.datatype, "number"); + Assert.assertEquals(property1.name, "id"); + Assert.assertEquals(property1.defaultValue, "null"); + Assert.assertEquals(property1.baseType, "number"); + Assert.assertTrue(property1.hasMore); + Assert.assertTrue(property1.required); + Assert.assertTrue(property1.isNotContainer); + + final CodegenProperty property2 = cm.vars.get(1); + Assert.assertEquals(property2.baseName, "urls"); + Assert.assertEquals(property2.datatype, "Array"); + Assert.assertEquals(property2.name, "urls"); + Assert.assertEquals(property2.baseType, "Array"); + Assert.assertNull(property2.hasMore); + Assert.assertNull(property2.required); + Assert.assertTrue(property2.isContainer); + } + + @Test(description = "convert a model with complex property") + public void complexPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.datatype, "Children"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Children"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isNotContainer); + } + + @Test(description = "convert a model with complex list property") + public void complexListPropertyTest() { + final Model model = new ModelImpl() + .description("a sample model") + .property("children", new ArrayProperty() + .items(new RefProperty("#/definitions/Children"))); + final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a sample model"); + Assert.assertEquals(cm.vars.size(), 1); + + final CodegenProperty property1 = cm.vars.get(0); + Assert.assertEquals(property1.baseName, "children"); + Assert.assertEquals(property1.complexType, "Children"); + Assert.assertEquals(property1.datatype, "Array"); + Assert.assertEquals(property1.name, "children"); + Assert.assertEquals(property1.baseType, "Array"); + Assert.assertNull(property1.required); + Assert.assertTrue(property1.isContainer); + } + + @Test(description = "convert an array model") + public void arrayModelTest() { + final Model model = new ArrayModel() + .description("an array model") + .items(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "an array model"); + Assert.assertEquals(cm.vars.size(), 0); + } + + @Test(description = "convert a map model") + public void mapModelTest() { + final Model model = new ModelImpl() + .description("a map model") + .additionalProperties(new RefProperty("#/definitions/Children")); + final DefaultCodegen codegen = new TypeScriptNodeClientCodegen(); + final CodegenModel cm = codegen.fromModel("sample", model); + + Assert.assertEquals(cm.name, "sample"); + Assert.assertEquals(cm.classname, "Sample"); + Assert.assertEquals(cm.description, "a map model"); + Assert.assertEquals(cm.vars.size(), 0); + Assert.assertEquals(cm.imports.size(), 1); + Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); + } +} diff --git a/modules/swagger-codegen/src/test/scala/CodegenTest.scala b/modules/swagger-codegen/src/test/scala/CodegenTest.scala deleted file mode 100644 index 015932948de6..000000000000 --- a/modules/swagger-codegen/src/test/scala/CodegenTest.scala +++ /dev/null @@ -1,157 +0,0 @@ -import io.swagger.codegen.DefaultCodegen -import io.swagger.models.properties.Property -import io.swagger.parser._ -import org.junit.runner.RunWith -import org.scalatest.junit.JUnitRunner -import org.scalatest.{FlatSpec, Matchers} - -@RunWith(classOf[JUnitRunner]) -class CodegenTest extends FlatSpec with Matchers { - behavior of "Codegen" - - it should "read a file upload param from a 2.0 spec" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/petstore.json") - - val codegen = new DefaultCodegen() - val path = "/pet/{petId}/uploadImage" - val p = model.getPaths().get(path).getPost() - val op = codegen.fromOperation(path, "post", p, model.getDefinitions()) - - op.operationId should be("uploadFile") - op.httpMethod should be("POST") - op.hasConsumes should equal(true) - op.consumes.size should be(1) - op.consumes.get(0).get("mediaType") should be("multipart/form-data") - - op.hasProduces should equal(true) - val allParams = op.allParams - allParams.size should be(3) - - val formParams = op.formParams - formParams.size should be(2) - - val file = formParams.get(1) - file.isFormParam should equal(true) - file.dataType should be("file") - file.required should equal(null) - file.isFile should equal(true) - file.hasMore should be(null) - } - - it should "read formParam values from a 2.0 spec" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/petstore.json") - - val codegen = new DefaultCodegen() - val path = "/pet/{petId}" - val p = model.getPaths().get(path).getPost() - val op = codegen.fromOperation(path, "post", p, model.getDefinitions()) - - op.operationId should be("updatePetWithForm") - op.httpMethod should be("POST") - op.hasConsumes should equal(true) - op.consumes.size should be(1) - op.consumes.get(0).get("mediaType") should be("application/x-www-form-urlencoded") - - op.hasProduces should equal(true) - op.produces.size should be(2) - op.produces.get(0).get("mediaType") should be("application/json") - op.produces.get(0).get("hasMore") should be("true") - op.produces.get(1).get("mediaType") should be("application/xml") - - val pathParams = op.pathParams - pathParams.size should be(1) - - val idParam = pathParams.get(0) - idParam.isPathParam should equal(true) - idParam.dataType should be("String") - idParam.required should equal(true) - idParam.hasMore should be(null) - - val allParams = op.allParams - allParams.size should be(3) - - val formParams = op.formParams - formParams.size should be(2) - val nameParam = formParams.get(0) - nameParam.isFormParam should equal(true) - nameParam.notFile should equal(true) - nameParam.dataType should be("String") - nameParam.required should equal(null) - nameParam.hasMore should equal(true) - - val statusParam = formParams.get(1) - statusParam.isFormParam should equal(true) - statusParam.notFile should equal(true) - statusParam.dataType should be("String") - statusParam.required should equal(null) - statusParam.hasMore should be(null) - } - - it should "handle required parameters from a 2.0 spec as required when figuring out Swagger types" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/requiredTest.json") - - val codegen = new DefaultCodegen() { - override def getSwaggerType(p: Property) = Option(p) match { - case Some(property) if !property.getRequired => - "Optional<" + super.getSwaggerType(p) + ">" - case other => super.getSwaggerType(p) - } - } - val path = "/tests/requiredParams" - val p = model.getPaths().get(path).getGet() - val op = codegen.fromOperation(path, "get", p, model.getDefinitions) - - val formParams = op.formParams - formParams.size should be(2) - val requiredParam = formParams.get(0) - requiredParam.dataType should be("Long") - - val optionalParam = formParams.get(1) - optionalParam.dataType should be("Optional") - - op.returnType should be("Long") - } - - it should "select main response from a 2.0 spec using the lowest 2XX code" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/responseSelectionTest.json") - - val codegen = new DefaultCodegen() - - val path = "/tests/withTwoHundredAndDefault" - val p = model.getPaths().get(path).getGet() - val op = codegen.fromOperation(path, "get", p, model.getDefinitions()) - op.returnType should be("String") - - } - - it should "select main response from a 2.0 spec using the default keyword when no 2XX code" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/responseSelectionTest.json") - - val codegen = new DefaultCodegen() - - val path = "/tests/withoutTwoHundredButDefault" - val p = model.getPaths().get(path).getGet() - val op = codegen.fromOperation(path, "get", p, model.getDefinitions()) - op.returnType should be("String") - } - - it should "return byte array when response format is byte" in { - val model = new SwaggerParser() - .read("src/test/resources/2_0/binaryDataTest.json") - System.err.println("model is " + model); - val codegen = new DefaultCodegen() - - val path = "/tests/binaryResponse" - val p = model.getPaths().get(path).getPost() - val op = codegen.fromOperation(path, "post", p, model.getDefinitions()) - op.returnType should be("byte[]") - op.bodyParam.dataType should be ("byte[]") - op.bodyParam.isBinary should equal (true); - op.responses.get(0).isBinary should equal(true); - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala deleted file mode 100644 index 51cc5978dda5..000000000000 --- a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala +++ /dev/null @@ -1,59 +0,0 @@ -import io.swagger.codegen.examples.ExampleGenerator -import io.swagger.models.{Model, ModelImpl, Xml} -import io.swagger.models.properties.{ArrayProperty, RefProperty, StringProperty} -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters.{asScalaBufferConverter, mapAsJavaMapConverter, seqAsJavaListConverter} - -@RunWith(classOf[JUnitRunner]) -class ExampleGeneratorTest extends FlatSpec with Matchers { - val json = "application/json" - val xml = "application/xml" - - it should "check handling of recursive models" in { - val nodeType = "Node" - val ref = new RefProperty(nodeType) - val node = new ModelImpl().name(nodeType).property("name", new StringProperty()) - node.property("parent", ref) - node.property("children", new ArrayProperty(ref)) - node.property("wrappedChildren", new ArrayProperty(ref).xml(new Xml().wrapped(true))) - val pairType = "Pair" - val pair = new ModelImpl().name(pairType) - for (item <- Map("first" -> "First", "second" -> "Second")) { - val property = new RefProperty(nodeType) - property.setXml(new Xml().name(item._2)) - pair.property(item._1, property); - } - val types = scala.collection.mutable.Buffer[String]() - val expectedTypes = List(json, xml) - val eg = new ExampleGenerator(Map[String, Model](nodeType -> node, pairType -> pair).asJava) - for (item <- eg.generate(null, expectedTypes.asJava, new RefProperty(pairType)).asScala) { - val example = item.get("example") - item.get("contentType") match { - case `xml` => { - types += xml - example should be("\n" + - " \n" + - " string\n" + - " \n" + - " \n" + - " \n" + - " \n" + - " string\n" + - " \n" + - " \n" + - " \n" + - "") - } - case `json` => { - types += json - // TODO - add JSON validation - example should not be (null) - } - } - } - types should be(expectedTypes) - } -} diff --git a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala b/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala deleted file mode 100644 index cf99149c49c1..000000000000 --- a/modules/swagger-codegen/src/test/scala/scala/ScalaModelTest.scala +++ /dev/null @@ -1,238 +0,0 @@ -package Scala - -import io.swagger.codegen.languages.ScalaClientCodegen -import io.swagger.models._ -import io.swagger.models.properties._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class ScalaModelTest extends FlatSpec with Matchers { - - it should "convert a simple scala model" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).getter should be("getId") - vars.get(0).setter should be("setId") - vars.get(0).datatype should be("Long") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("Long") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("name") - vars.get(1).getter should be("getName") - vars.get(1).setter should be("setName") - vars.get(1).datatype should be("String") - vars.get(1).name should be("name") - vars.get(1).defaultValue should be("null") - vars.get(1).baseType should be("String") - vars.get(1).hasMore should equal(true) - vars.get(1).required should equal(true) - vars.get(1).isNotContainer should equal(true) - - vars.get(2).baseName should be("createdAt") - vars.get(2).getter should be("getCreatedAt") - vars.get(2).setter should be("setCreatedAt") - vars.get(2).datatype should be("DateTime") - vars.get(2).name should be("createdAt") - vars.get(2).defaultValue should be("null") - 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) - } - - it should "convert a model with list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id") - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(2) - - val vars = cm.vars - vars.get(1).baseName should be("urls") - vars.get(1).getter should be("getUrls") - vars.get(1).setter should be("setUrls") - vars.get(1).datatype should be("List[String]") - vars.get(1).name should be("urls") - vars.get(1).defaultValue should be("new ListBuffer[String]() ") - vars.get(1).baseType should be("List") - vars.get(1).containerType should be("array") - vars.get(1).required should equal(null) - vars.get(1).isContainer should equal(true) - } - - it should "convert a model with a map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("translations", new MapProperty() - .additionalProperties(new StringProperty())) - .required("id") - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("translations") - vars.get(0).getter should be("getTranslations") - vars.get(0).setter should be("setTranslations") - vars.get(0).datatype should be("Map[String, String]") - vars.get(0).name should be("translations") - vars.get(0).defaultValue should be("new HashMap[String, String]() ") - vars.get(0).baseType should be("Map") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert a model with complex properties" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")) - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).getter should be("getChildren") - vars.get(0).setter should be("setChildren") - vars.get(0).datatype should be("Children") - vars.get(0).name should be("children") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("Children") - vars.get(0).required should equal(null) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))) - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).complexType should be("Children") - vars.get(0).getter should be("getChildren") - vars.get(0).setter should be("setChildren") - vars.get(0).datatype should be("List[Children]") - vars.get(0).name should be("children") - vars.get(0).defaultValue should be("new ListBuffer[Children]() ") - vars.get(0).baseType should be("List") - vars.get(0).containerType should be("array") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert a model with complex map property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new MapProperty() - .additionalProperties(new RefProperty("#/definitions/Children"))) - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - (cm.imports.asScala.toSet & Set("Children")).size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).complexType should be("Children") - vars.get(0).getter should be("getChildren") - vars.get(0).setter should be("setChildren") - vars.get(0).datatype should be("Map[String, Children]") - vars.get(0).name should be("children") - vars.get(0).defaultValue should be("new HashMap[String, Children]() ") - vars.get(0).baseType should be("Map") - vars.get(0).containerType should be("map") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - vars.get(0).isNotContainer should be(null) - } - - it should "convert an array model" in { - val model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")) - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an array model") - cm.vars.size should be(0) - cm.parent should be("ListBuffer[Children]") - cm.imports.size should be(2) - (cm.imports.asScala.toSet & Set("ListBuffer", "Children")).size should be(2) - } - - it should "convert an map model" in { - val model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")) - - val codegen = new ScalaClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an map model") - cm.vars.size should be(0) - cm.parent should be("HashMap[String, Children]") - cm.imports.size should be(2) - (cm.imports.asScala.toSet & Set("HashMap", "Children")).size should be(2) - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala b/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala deleted file mode 100644 index f755361a3d43..000000000000 --- a/modules/swagger-codegen/src/test/scala/staticDocs/StaticOperationTest.scala +++ /dev/null @@ -1,59 +0,0 @@ -package staticDocs - -import io.swagger.codegen.languages.StaticDocCodegen -import io.swagger.models.properties._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -@RunWith(classOf[JUnitRunner]) -class StaticOperationTest extends FlatSpec with Matchers { - it should "convert a string parameter" in { - val property = new StringProperty() - - val codegen = new StaticDocCodegen() - val cp = codegen.fromProperty("property", property) - - cp.baseName should be("property") - cp.datatype should be("String") - cp.name should be("property") - cp.baseType should be("string") - cp.isNotContainer should equal(true) - } - - it should "convert a complex parameter" in { - val property = new RefProperty("Children") - - val codegen = new StaticDocCodegen() - val cp = codegen.fromProperty("property", property) - - cp.baseName should be("property") - cp.complexType should be("Children") - cp.getter should be("getProperty") - cp.setter should be("setProperty") - cp.datatype should be("Children") - cp.name should be("property") - cp.defaultValue should be("null") - cp.baseType should be("Children") - cp.isNotContainer should equal(true) - } - - it should "convert a complex list parameter" in { - val property = new ArrayProperty(). - items(new RefProperty("Children")) - - val codegen = new StaticDocCodegen() - val cp = codegen.fromProperty("property", property) - - cp.baseName should be("property") - cp.complexType should be("Children") - cp.getter should be("getProperty") - cp.setter should be("setProperty") - cp.datatype should be("List") - cp.name should be("property") - cp.baseType should be("array") - cp.containerType should be("array") - cp.isContainer should equal(true) - - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala b/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala deleted file mode 100644 index f82215253382..000000000000 --- a/modules/swagger-codegen/src/test/scala/typescriptangular/TypeScriptAngularModelTest.scala +++ /dev/null @@ -1,170 +0,0 @@ -package typescriptangular - -import io.swagger.codegen.languages.TypeScriptAngularClientCodegen -import io.swagger.models._ -import io.swagger.models.properties._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class TypeScriptAngularModelTest extends FlatSpec with Matchers { - - it should "convert a simple TypeScript Angular model" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - - val codegen = new TypeScriptAngularClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("number") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("number") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("name") - vars.get(1).datatype should be("string") - vars.get(1).name should be("name") - vars.get(1).defaultValue should be("null") - vars.get(1).baseType should be("string") - vars.get(1).hasMore should equal(true) - vars.get(1).required should equal(true) - vars.get(1).isNotContainer should equal(true) - - vars.get(2).baseName should be("createdAt") - vars.get(2).complexType should be("Date") - vars.get(2).datatype should be("Date") - vars.get(2).name should be("createdAt") - vars.get(2).defaultValue should be("null") - vars.get(2).hasMore should equal(null) - vars.get(2).required should equal(null) - vars.get(2).isNotContainer should equal(true) - } - - it should "convert a model with list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id") - - val codegen = new TypeScriptAngularClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(2) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("number") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("number") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("urls") - vars.get(1).datatype should be("Array") - vars.get(1).name should be("urls") - vars.get(1).baseType should be("Array") - vars.get(1).hasMore should be(null) - vars.get(1).required should equal(null) - vars.get(1).isContainer should equal(true) - } - - it should "convert a model with complex property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")) - - val codegen = new TypeScriptAngularClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).datatype should be("Children") - vars.get(0).name should be("children") - vars.get(0).baseType should be("Children") - vars.get(0).required should equal(null) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))) - - val codegen = new TypeScriptAngularClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - 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") - vars.get(0).name should be("children") - vars.get(0).baseType should be("Array") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert an array model" in { - val model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")) - val codegen = new TypeScriptAngularClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an array model") - cm.vars.size should be(0) - } - - it should "convert an map model" in { - val model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")) - - val codegen = new TypeScriptAngularClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an map model") - cm.vars.size should be(0) - cm.imports.size should be(1) - (cm.imports.asScala.toSet & Set("Children")).size should be(1) - } -} diff --git a/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala b/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala deleted file mode 100644 index 3ab26be651be..000000000000 --- a/modules/swagger-codegen/src/test/scala/typescriptnode/TypeScriptNodeModelTest.scala +++ /dev/null @@ -1,170 +0,0 @@ -package typescriptnode - -import io.swagger.codegen.languages.TypeScriptNodeClientCodegen -import io.swagger.models._ -import io.swagger.models.properties._ -import org.junit.runner.RunWith -import org.scalatest.{FlatSpec, Matchers} -import org.scalatest.junit.JUnitRunner - -import scala.collection.JavaConverters._ - -@RunWith(classOf[JUnitRunner]) -class TypeScriptNodeModelTest extends FlatSpec with Matchers { - - it should "convert a simple TypeScript Node model" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("name", new StringProperty()) - .property("createdAt", new DateTimeProperty()) - .required("id") - .required("name") - - val codegen = new TypeScriptNodeClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(3) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("number") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("number") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("name") - vars.get(1).datatype should be("string") - vars.get(1).name should be("name") - vars.get(1).defaultValue should be("null") - vars.get(1).baseType should be("string") - vars.get(1).hasMore should equal(true) - vars.get(1).required should equal(true) - vars.get(1).isNotContainer should equal(true) - - vars.get(2).baseName should be("createdAt") - vars.get(2).complexType should be("Date") - vars.get(2).datatype should be("Date") - vars.get(2).name should be("createdAt") - vars.get(2).defaultValue should be("null") - vars.get(2).hasMore should equal(null) - vars.get(2).required should equal(null) - vars.get(2).isNotContainer should equal(true) - } - - it should "convert a model with list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("id", new LongProperty()) - .property("urls", new ArrayProperty() - .items(new StringProperty())) - .required("id") - - val codegen = new TypeScriptNodeClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(2) - - val vars = cm.vars - vars.get(0).baseName should be("id") - vars.get(0).datatype should be("number") - vars.get(0).name should be("id") - vars.get(0).defaultValue should be("null") - vars.get(0).baseType should be("number") - vars.get(0).hasMore should equal(true) - vars.get(0).required should equal(true) - vars.get(0).isNotContainer should equal(true) - - vars.get(1).baseName should be("urls") - vars.get(1).datatype should be("Array") - vars.get(1).name should be("urls") - vars.get(1).baseType should be("Array") - vars.get(1).hasMore should be(null) - vars.get(1).required should equal(null) - vars.get(1).isContainer should equal(true) - } - - it should "convert a model with complex property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new RefProperty("#/definitions/Children")) - - val codegen = new TypeScriptNodeClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - val vars = cm.vars - vars.get(0).baseName should be("children") - vars.get(0).datatype should be("Children") - vars.get(0).name should be("children") - vars.get(0).baseType should be("Children") - vars.get(0).required should equal(null) - vars.get(0).isNotContainer should equal(true) - } - - it should "convert a model with complex list property" in { - val model = new ModelImpl() - .description("a sample model") - .property("children", new ArrayProperty() - .items(new RefProperty("#/definitions/Children"))) - - val codegen = new TypeScriptNodeClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("a sample model") - cm.vars.size should be(1) - - 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") - vars.get(0).name should be("children") - vars.get(0).baseType should be("Array") - vars.get(0).required should equal(null) - vars.get(0).isContainer should equal(true) - } - - it should "convert an array model" in { - val model = new ArrayModel() - .description("an array model") - .items(new RefProperty("#/definitions/Children")) - val codegen = new TypeScriptNodeClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an array model") - cm.vars.size should be(0) - } - - it should "convert an map model" in { - val model = new ModelImpl() - .description("an map model") - .additionalProperties(new RefProperty("#/definitions/Children")) - - val codegen = new TypeScriptNodeClientCodegen() - val cm = codegen.fromModel("sample", model) - - cm.name should be("sample") - cm.classname should be("Sample") - cm.description should be("an map model") - cm.vars.size should be(0) - cm.imports.size should be(1) - (cm.imports.asScala.toSet & Set("Children")).size should be(1) - } -} From ff0b0c15a88f5669eda61a67d6031bae4b56c7fd Mon Sep 17 00:00:00 2001 From: Quenby Mitchell Date: Fri, 2 Oct 2015 12:14:41 -0500 Subject: [PATCH 153/219] fix build warnings on CSharp xml comments --- .../src/main/resources/csharp/ApiClient.mustache | 1 + .../src/main/resources/csharp/ApiException.mustache | 1 - .../swagger-codegen/src/main/resources/csharp/api.mustache | 5 ++++- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index f29e7cf6bf59..1730ca83b9af 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -216,6 +216,7 @@ namespace {{packageName}}.Client /// /// HTTP body (e.g. string, JSON). /// Object type. + /// /// Object representation of the JSON string. public object Deserialize(string content, Type type, IList headers=null) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache index 364e2e999120..68e3a0327652 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache @@ -20,7 +20,6 @@ namespace {{packageName}}.Client { /// /// Initializes a new instance of the class. /// - /// The base path. public ApiException() {} /// diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 8b958fd0c889..fd170b5ca8ed 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -9,6 +9,9 @@ using {{packageName}}.Client; namespace {{packageName}}.Api { {{#operations}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface I{{classname}} { {{#operation}} @@ -77,7 +80,7 @@ namespace {{packageName}}.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} {{#operation}} From 1018ca634da16f0a2aaad9cd2c6318a1dd33daef Mon Sep 17 00:00:00 2001 From: Quenby Mitchell Date: Fri, 2 Oct 2015 13:11:54 -0500 Subject: [PATCH 154/219] generic types need to be escaped for the xmldoc to work for return documentation. List should be List{Foo} for the c# compiler to generate the documentation for the generic type. since there is not a spare parameter on the CodegenOperation model to put this correctly formatted documentation, for right now, don't include the return type in the documentation. --- .../src/main/resources/csharp/api.mustache | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index fd170b5ca8ed..6b749c9a8972 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -19,14 +19,14 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); /// /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} } @@ -88,7 +88,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} @@ -135,7 +135,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}}// verify the required parameter '{{paramName}}' is set From 3c78e29a1205e93d4f74071b3c8fd0beecba2722 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 5 Oct 2015 13:19:58 +0800 Subject: [PATCH 155/219] better Accept header for C# --- .../main/resources/csharp/ApiClient.mustache | 15 +++ .../src/main/resources/csharp/api.mustache | 10 ++ .../src/main/csharp/IO/Swagger/Api/PetApi.cs | 101 ++++++++++++++++-- .../main/csharp/IO/Swagger/Api/StoreApi.cs | 53 ++++++++- .../src/main/csharp/IO/Swagger/Api/UserApi.cs | 85 ++++++++++++++- .../csharp/IO/Swagger/Client/ApiClient.cs | 16 +++ .../csharp/IO/Swagger/Client/ApiException.cs | 1 - .../csharp/SwaggerClientTest/TestPet.cs | 5 + .../bin/Debug/SwaggerClientTest.dll | Bin 57856 -> 59904 bytes .../bin/Debug/SwaggerClientTest.dll.mdb | Bin 17345 -> 18623 bytes .../obj/Debug/SwaggerClientTest.dll | Bin 57856 -> 59904 bytes .../obj/Debug/SwaggerClientTest.dll.mdb | Bin 17345 -> 18623 bytes 12 files changed, 270 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 1730ca83b9af..ae864113a9c5 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -326,6 +326,21 @@ namespace {{packageName}}.Client } } } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public String SelectHeaderAccept(String[] accepts) { + if (accepts.Length == 0) + return null; + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + return String.Join(",", accepts); + } /// /// Encode string in base64 format. diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 6b749c9a8972..00231bb67361 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -105,6 +105,16 @@ namespace {{packageName}}.Api var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter {{/pathParams}} diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 15dc644e4136..6b8c69dbe8b8 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -8,6 +8,9 @@ namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IPetApi { @@ -43,28 +46,28 @@ public interface IPetApi /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// List + /// List FindPetsByStatus (List status); /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// List + /// System.Threading.Tasks.Task> FindPetsByStatusAsync (List status); /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// List + /// List FindPetsByTags (List tags); /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// List + /// System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags); /// @@ -184,7 +187,7 @@ public String GetBasePath() /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} @@ -206,6 +209,16 @@ public void UpdatePet (Pet body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -284,6 +297,16 @@ public void AddPet (Pet body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -348,7 +371,7 @@ public async System.Threading.Tasks.Task AddPetAsync (Pet body) /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// List + /// public List FindPetsByStatus (List status) { @@ -362,6 +385,16 @@ public List FindPetsByStatus (List status) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter @@ -388,7 +421,7 @@ public List FindPetsByStatus (List status) /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// List + /// public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List status) { @@ -425,7 +458,7 @@ public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List< /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// List + /// public List FindPetsByTags (List tags) { @@ -439,6 +472,16 @@ public List FindPetsByTags (List tags) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter @@ -465,7 +508,7 @@ public List FindPetsByTags (List tags) /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// List + /// public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags) { @@ -519,6 +562,16 @@ public Pet GetPetById (long? petId) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter @@ -603,6 +656,16 @@ public void UpdatePetWithForm (string petId, string name, string status) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter @@ -693,6 +756,16 @@ public void DeletePet (long? petId, string apiKey) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter @@ -781,6 +854,16 @@ public void UploadFile (long? petId, string additionalMetadata, Stream file) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index 1d927a28cd24..ee004eeba47b 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -8,19 +8,22 @@ namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IStoreApi { /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary + /// Dictionary GetInventory (); /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary + /// System.Threading.Tasks.Task> GetInventoryAsync (); /// @@ -116,14 +119,14 @@ public String GetBasePath() /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary + /// public Dictionary GetInventory () { @@ -137,6 +140,16 @@ public String GetBasePath() var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -161,7 +174,7 @@ public String GetBasePath() /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// Dictionary + /// public async System.Threading.Tasks.Task> GetInventoryAsync () { @@ -211,6 +224,16 @@ public Order PlaceOrder (Order body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -291,6 +314,16 @@ public Order GetOrderById (string orderId) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter @@ -373,6 +406,16 @@ public void DeleteOrder (string orderId) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 719e6f2351bc..5339400309ea 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -8,6 +8,9 @@ namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IUserApi { @@ -176,7 +179,7 @@ public String GetBasePath() /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} @@ -198,6 +201,16 @@ public void CreateUser (User body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -276,6 +289,16 @@ public void CreateUsersWithArrayInput (List body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -354,6 +377,16 @@ public void CreateUsersWithListInput (List body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -433,6 +466,16 @@ public string LoginUser (string username, string password) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter @@ -512,6 +555,16 @@ public void LogoutUser () var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -590,6 +643,16 @@ public User GetUserByName (string username) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter @@ -673,6 +736,16 @@ public void UpdateUser (string username, User body) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter @@ -759,6 +832,16 @@ public void DeleteUser (string username) var fileParams = new Dictionary(); String postBody = null; + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs index 76841f428d4d..74b898be6260 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiClient.cs @@ -216,6 +216,7 @@ public string ParameterToString(object obj) /// /// HTTP body (e.g. string, JSON). /// Object type. + /// /// Object representation of the JSON string. public object Deserialize(string content, Type type, IList headers=null) { @@ -330,6 +331,21 @@ public void UpdateParamsForAuth(Dictionary queryParams, Dictiona } } } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public String SelectHeaderAccept(String[] accepts) { + if (accepts.Length == 0) + return null; + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + return String.Join(",", accepts); + } /// /// Encode string in base64 format. diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs index 20df8115c791..addfc8397167 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiException.cs @@ -20,7 +20,6 @@ public class ApiException : Exception { /// /// Initializes a new instance of the class. /// - /// The base path. public ApiException() {} /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index 98326a63ae77..5a42b8703c21 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -120,7 +120,12 @@ public void TestUploadFile () PetApi petApi = new PetApi (); //NOTE: please provide a valid file (full path) FileStream fileStream = new FileStream("/var/tmp/small.gif", FileMode.Open); + // test file upload with form parameters petApi.UploadFile(petId, "new form name", fileStream); + + // test file upload without any form parameters + petApi.UploadFile(petId, null, fileStream); + } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 7a68ae28dc29a620984dcc8ccb843a8166253a95..7fbacf3096b1f132af50ef0bc88607639316455b 100755 GIT binary patch delta 17701 zcmd5^33yaRwmx-x?@n*GJDr_$2#|)bBm$DKNCHH5S;8W#i6H|)prON}WTX?>g0ch( zQ9uzDM-&9cpopSG!3c^H5Cjns1_sAbM;wKbHz@B^-Rdm_oV+*BH~pE@=dZI=om1yl z)xEc|e7~yvn5yc@j(-9GE&k!BEf4@VGH(2a9EFzv)QH$8@C^kkkG8d(y$;ZyHKVp( zwKBz_&LI#*hkVw7jv{Hs4riGN|NcZDCaDHg;`SHlt0dWgnt+bsFZ2v)8fOF6A3z`c zlRyLNr2xlD0SG$lL`&&U-(8 zIrMgYb}YIw_y(dlLgv)~7;^p;6fJG6-mW#+)pm`}ZtzY+XETl1 zp~Gl5dND^vcNGq_dvo+H8hk6z9C;lIJ$fX9FZHACT%pvt0RxPK8@QMS1Byi!x`tK& zv`*FQHw!wZu|e-^Y|z5sSAt%p>18U$1Y@S{;QO9_C#4nqduJTS%_~5a9fNt+`=SZ0 z(j?Za0as(wkxCj_1HvGXjvkRUAPQC~syY=wg2$>jKi`~TPA$ap`)Bl(EfgB9Vw=LqX!1Mcp^HUETp@lJ*as$nvG(Ii*;1z`qC0wtR=QuzZ)|k zU=Y*T=`B^{eq2YytU8d^@&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s8_Ap(laMf%l;ofad~>px1#v1gfC-gSP{Vp-+Q<1eQSG0{;#yg?_d%K7bEE zL0~Un8MGN}1eQbh1jhm^ptHgKftAp&gRQ`a&{M#bz$)ku!1IBRpr30(v=RDa=uqf} zz-s77a64cPbTYUb@CkGdcmVJz^c&zIz*^|3;Bmk@=mX%zzFa2l`|`bY3!U?21i z@Grnu(C(qAPhdav6mT5yHS{L%2f#Pb-I@`df&LbHA9Nn@9dvkeqKnYqLl;7)0SBNj zfI1Ts#dL?)na2T3vf$a@_1X>II4DciL%V2NdDD-G> z1#k@dH}DkTIP@LxU%&}yOH2G}4>$=u1Y8Q7f<6x}2Y!P73;ZYWGxR_s_6y)NbP2c+ zI0OAN_;uhc^ffTv;G=WUiQ)JkDM0@MJpj5Na2|RyxB$2Sy&t?6_!YWcE5rf)8+145 zF2F_TmEbhs67**92H-NZzBRrJeFZuI+86j8dKkC`a22`|{1$Kx`X}(az;)=W;LE@t z(CKYZGthrR4~8xRZb0tOyQ# diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll index 7a68ae28dc29a620984dcc8ccb843a8166253a95..7fbacf3096b1f132af50ef0bc88607639316455b 100755 GIT binary patch delta 17701 zcmd5^33yaRwmx-x?@n*GJDr_$2#|)bBm$DKNCHH5S;8W#i6H|)prON}WTX?>g0ch( zQ9uzDM-&9cpopSG!3c^H5Cjns1_sAbM;wKbHz@B^-Rdm_oV+*BH~pE@=dZI=om1yl z)xEc|e7~yvn5yc@j(-9GE&k!BEf4@VGH(2a9EFzv)QH$8@C^kkkG8d(y$;ZyHKVp( zwKBz_&LI#*hkVw7jv{Hs4riGN|NcZDCaDHg;`SHlt0dWgnt+bsFZ2v)8fOF6A3z`c zlRyLNr2xlD0SG$lL`&&U-(8 zIrMgYb}YIw_y(dlLgv)~7;^p;6fJG6-mW#+)pm`}ZtzY+XETl1 zp~Gl5dND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%UYV(9wNb$}A+HsD}jFmx|)3{VRF26!M)2JMRC-2rWdz5@LkFa$ajh5Q`w zGIS|84R{6md+;paRp|TRUxA^}4N&ZAU>I~bxH0e=bOJaE_!o3GxDW6;G~S9OEAR&N z67Xc;P3Xx3j8l%67($aWCrLT!7G6&&^N%p08^n|F&Xf{G-xld9+(bo1UCWRg^mSx0N#V{ z4^9PUKwH82z)a{$@CaZQ^nCEUz-;KX;FZ7}=&!)rfVt2=gO337p#K720p>$L(+EFn z0v13I0s8_Ap(laMf%l;ofad~>px1#v1gfC-gSP{Vp-+Q<1eQSG0{;#yg?_d%K7bEE zL0~Un8MGN}1eQbh1jhm^ptHgKftAp&gRQ`a&{M#bz$)ku!1IBRpr30(v=RDa=uqf} zz-s77a64cPbTYUb@CkGdcmVJz^c&zIz*^|3;Bmk@=mX%zzFa2l`|`bY3!U?21i z@Grnu(C(qAPhdav6mT5yHS{L%2f#Pb-I@`df&LbHA9Nn@9dvkeqKnYqLl;7)0SBNj zfI1Ts#dL?)na2T3vf$a@_1X>II4DciL%V2NdDD-G> z1#k@dH}DkTIP@LxU%&}yOH2G}4>$=u1Y8Q7f<6x}2Y!P73;ZYWGxR_s_6y)NbP2c+ zI0OAN_;uhc^ffTv;G=WUiQ)JkDM0@MJpj5Na2|RyxB$2Sy&t?6_!YWcE5rf)8+145 zF2F_TmEbhs67**92H-NZzBRrJeFZuI+86j8dKkC`a22`|{1$Kx`X}(az;)=W;LE@t z(CKYZGthrR4~8xRZb0tOyQ# From d882e9fe0a0deb95359119c6ccc689b7ccfe212f Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 5 Oct 2015 22:33:25 +0800 Subject: [PATCH 156/219] remove site.css from html docs --- .../swagger-codegen/src/main/resources/htmlDocs/index.mustache | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 584db3b7a855..ac07a3fd9f55 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -4,7 +4,6 @@ {{{appName}}} - @@ -161,4 +160,4 @@ {{/model}} {{/models}} - \ No newline at end of file + From 6ed766346677aa2e769eac7723580881e9fdda2a Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Oct 2015 11:28:18 +0800 Subject: [PATCH 157/219] add remarks to csharp method --- .../src/main/resources/csharp/api.mustache | 10 ++- .../src/main/csharp/IO/Swagger/Api/PetApi.cs | 80 ++++++++++++++---- .../main/csharp/IO/Swagger/Api/StoreApi.cs | 40 +++++++-- .../src/main/csharp/IO/Swagger/Api/UserApi.cs | 80 ++++++++++++++---- .../bin/Debug/SwaggerClientTest.dll.mdb | Bin 18623 -> 18627 bytes .../obj/Debug/SwaggerClientTest.dll.mdb | Bin 18623 -> 18627 bytes 6 files changed, 168 insertions(+), 42 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 00231bb67361..4f65ba117bd7 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -16,15 +16,21 @@ namespace {{packageName}}.Api { {{#operation}} /// - /// {{summary}} {{notes}} + /// {{summary}} /// + /// + /// {{notes}} + /// {{#allParams}}/// {{description}} {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); /// - /// {{summary}} {{notes}} + /// {{summary}} /// + /// + /// {{notes}} + /// {{#allParams}}/// {{description}} {{/allParams}}/// {{#returnType}}{{^returnContainer}}{{{returnType}}}{{/returnContainer}}{{/returnType}} {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 6b8c69dbe8b8..67048cfd0431 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -15,78 +15,111 @@ public interface IPetApi { /// - /// Update an existing pet + /// Update an existing pet /// + /// + /// + /// /// Pet object that needs to be added to the store /// void UpdatePet (Pet body); /// - /// Update an existing pet + /// Update an existing pet /// + /// + /// + /// /// Pet object that needs to be added to the store /// System.Threading.Tasks.Task UpdatePetAsync (Pet body); /// - /// Add a new pet to the store + /// Add a new pet to the store /// + /// + /// + /// /// Pet object that needs to be added to the store /// void AddPet (Pet body); /// - /// Add a new pet to the store + /// Add a new pet to the store /// + /// + /// + /// /// Pet object that needs to be added to the store /// System.Threading.Tasks.Task AddPetAsync (Pet body); /// - /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// Finds Pets by status /// + /// + /// Multiple status values can be provided with comma seperated strings + /// /// Status values that need to be considered for filter /// List FindPetsByStatus (List status); /// - /// Finds Pets by status Multiple status values can be provided with comma seperated strings + /// Finds Pets by status /// + /// + /// Multiple status values can be provided with comma seperated strings + /// /// Status values that need to be considered for filter /// System.Threading.Tasks.Task> FindPetsByStatusAsync (List status); /// - /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Finds Pets by tags /// + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// /// Tags to filter by /// List FindPetsByTags (List tags); /// - /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// Finds Pets by tags /// + /// + /// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + /// /// Tags to filter by /// System.Threading.Tasks.Task> FindPetsByTagsAsync (List tags); /// - /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// Find pet by ID /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// /// ID of pet that needs to be fetched /// Pet Pet GetPetById (long? petId); /// - /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// Find pet by ID /// + /// + /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + /// /// ID of pet that needs to be fetched /// Pet System.Threading.Tasks.Task GetPetByIdAsync (long? petId); /// - /// Updates a pet in the store with form data + /// Updates a pet in the store with form data /// + /// + /// + /// /// ID of pet that needs to be updated /// Updated name of the pet /// Updated status of the pet @@ -94,8 +127,11 @@ public interface IPetApi void UpdatePetWithForm (string petId, string name, string status); /// - /// Updates a pet in the store with form data + /// Updates a pet in the store with form data /// + /// + /// + /// /// ID of pet that needs to be updated /// Updated name of the pet /// Updated status of the pet @@ -103,24 +139,33 @@ public interface IPetApi System.Threading.Tasks.Task UpdatePetWithFormAsync (string petId, string name, string status); /// - /// Deletes a pet + /// Deletes a pet /// + /// + /// + /// /// Pet id to delete /// /// void DeletePet (long? petId, string apiKey); /// - /// Deletes a pet + /// Deletes a pet /// + /// + /// + /// /// Pet id to delete /// /// System.Threading.Tasks.Task DeletePetAsync (long? petId, string apiKey); /// - /// uploads an image + /// uploads an image /// + /// + /// + /// /// ID of pet to update /// Additional data to pass to server /// file to upload @@ -128,8 +173,11 @@ public interface IPetApi void UploadFile (long? petId, string additionalMetadata, Stream file); /// - /// uploads an image + /// uploads an image /// + /// + /// + /// /// ID of pet to update /// Additional data to pass to server /// file to upload diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index ee004eeba47b..d106aa752d3c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -15,55 +15,79 @@ public interface IStoreApi { /// - /// Returns pet inventories by status Returns a map of status codes to quantities + /// Returns pet inventories by status /// + /// + /// Returns a map of status codes to quantities + /// /// Dictionary GetInventory (); /// - /// Returns pet inventories by status Returns a map of status codes to quantities + /// Returns pet inventories by status /// + /// + /// Returns a map of status codes to quantities + /// /// System.Threading.Tasks.Task> GetInventoryAsync (); /// - /// Place an order for a pet + /// Place an order for a pet /// + /// + /// + /// /// order placed for purchasing the pet /// Order Order PlaceOrder (Order body); /// - /// Place an order for a pet + /// Place an order for a pet /// + /// + /// + /// /// order placed for purchasing the pet /// Order System.Threading.Tasks.Task PlaceOrderAsync (Order body); /// - /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// Find purchase order by ID /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// /// ID of pet that needs to be fetched /// Order Order GetOrderById (string orderId); /// - /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// Find purchase order by ID /// + /// + /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + /// /// ID of pet that needs to be fetched /// Order System.Threading.Tasks.Task GetOrderByIdAsync (string orderId); /// - /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// Delete purchase order by ID /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// /// ID of the order that needs to be deleted /// void DeleteOrder (string orderId); /// - /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// Delete purchase order by ID /// + /// + /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + /// /// ID of the order that needs to be deleted /// System.Threading.Tasks.Task DeleteOrderAsync (string orderId); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 5339400309ea..5b839e7a8943 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -15,115 +15,163 @@ public interface IUserApi { /// - /// Create user This can only be done by the logged in user. + /// Create user /// + /// + /// This can only be done by the logged in user. + /// /// Created user object /// void CreateUser (User body); /// - /// Create user This can only be done by the logged in user. + /// Create user /// + /// + /// This can only be done by the logged in user. + /// /// Created user object /// System.Threading.Tasks.Task CreateUserAsync (User body); /// - /// Creates list of users with given input array + /// Creates list of users with given input array /// + /// + /// + /// /// List of user object /// void CreateUsersWithArrayInput (List body); /// - /// Creates list of users with given input array + /// Creates list of users with given input array /// + /// + /// + /// /// List of user object /// System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List body); /// - /// Creates list of users with given input array + /// Creates list of users with given input array /// + /// + /// + /// /// List of user object /// void CreateUsersWithListInput (List body); /// - /// Creates list of users with given input array + /// Creates list of users with given input array /// + /// + /// + /// /// List of user object /// System.Threading.Tasks.Task CreateUsersWithListInputAsync (List body); /// - /// Logs user into the system + /// Logs user into the system /// + /// + /// + /// /// The user name for login /// The password for login in clear text /// string string LoginUser (string username, string password); /// - /// Logs user into the system + /// Logs user into the system /// + /// + /// + /// /// The user name for login /// The password for login in clear text /// string System.Threading.Tasks.Task LoginUserAsync (string username, string password); /// - /// Logs out current logged in user session + /// Logs out current logged in user session /// + /// + /// + /// /// void LogoutUser (); /// - /// Logs out current logged in user session + /// Logs out current logged in user session /// + /// + /// + /// /// System.Threading.Tasks.Task LogoutUserAsync (); /// - /// Get user by user name + /// Get user by user name /// + /// + /// + /// /// The name that needs to be fetched. Use user1 for testing. /// User User GetUserByName (string username); /// - /// Get user by user name + /// Get user by user name /// + /// + /// + /// /// The name that needs to be fetched. Use user1 for testing. /// User System.Threading.Tasks.Task GetUserByNameAsync (string username); /// - /// Updated user This can only be done by the logged in user. + /// Updated user /// + /// + /// This can only be done by the logged in user. + /// /// name that need to be deleted /// Updated user object /// void UpdateUser (string username, User body); /// - /// Updated user This can only be done by the logged in user. + /// Updated user /// + /// + /// This can only be done by the logged in user. + /// /// name that need to be deleted /// Updated user object /// System.Threading.Tasks.Task UpdateUserAsync (string username, User body); /// - /// Delete user This can only be done by the logged in user. + /// Delete user /// + /// + /// This can only be done by the logged in user. + /// /// The name that needs to be deleted /// void DeleteUser (string username); /// - /// Delete user This can only be done by the logged in user. + /// Delete user /// + /// + /// This can only be done by the logged in user. + /// /// The name that needs to be deleted /// System.Threading.Tasks.Task DeleteUserAsync (string username); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index 4b588955d88891b51db69c6e737d1caf6c0a6d7b..b5012fc14daf30325e6c9721e0ceeca19cfb0255 100644 GIT binary patch delta 6603 zcmZ9Q2Uru?8ixN#LLfvepr8;sNKsLOAVpSJL08rSNRf^W6)dP=_hzwTUGdmmEA|G8 zyNWKlt71VBvG;}@MFGKr<$jYPbLILxFW-Cq^Us`Ticougui(6vjbMhCWR3iG- zpU4OqgYj@A@6|m8zYRZ%d2d5V{lAl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J=WJ{4{aHwM4My^u~|8ax!)8%&2!L=FY~POn7H;DP5NvmH=P z#h@62eIN~f6?qoSgjXRSf?4n{$d6z)+{lqg1?IpVkyc)|=bwO|AM0P=5;3CA~QbOLOIKW>Y=Qh`Ah2A`3yK{k9?JE9-JCb$MU z9^}B6A{T+p@Xg3|U<>>pau3)FFGrpPf5M+2Z-Z^{FUU7wJKU%}ZXd|S_2rHbE3g9- zU6F2JCp;9{7yJbug&YcY!Bde_z;1X3atZhw{uQ|m?17s)5vf5QybaPG!!-$z5ug}@xyb3@2z)(q1t@{%A-990@KWSqa14G2c?BGYzeQGp z6L57$A_+JNw?;MxrEqto6F3F$hxF};{V&7dBnGkIH2fj*GB^YOh^z%?;i=B}Z~^Dw z+mRXIJlx%d=mNYPj;|tV5I=@nyW*D^{31LS?h7u#ZzHq8Wq7qK-v2K!xPpOKC#)1) zg)c?+2G`)3$aUa4{55h1xB-`TChbS!P520SV{i*T1(^gY;1$T(;5NJp`5fGVhr8jH z!SCYw^5Gc#0`9?YAQQoT_;chF@Bkj{PE-ef2p6$AkCq6Ud|B z1H6+r?j!so+!x**e1dOB27%A;1IWGL3*5p74<-C7+zH+me1pd$y?ktO4>^)2V=xJD S@a4!kKmy;1%w#WnUHl&u23)`Z diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index 4b588955d88891b51db69c6e737d1caf6c0a6d7b..b5012fc14daf30325e6c9721e0ceeca19cfb0255 100644 GIT binary patch delta 6603 zcmZ9Q2Uru?8ixN#LLfvepr8;sNKsLOAVpSJL08rSNRf^W6)dP=_hzwTUGdmmEA|G8 zyNWKlt71VBvG;}@MFGKr<$jYPbLILxFW-Cq^Us`Ticougui(6vjbMhCWR3iG- zpU4OqgYj@A@6|m8zYRZ%d2d5V{lAl0Q3b~5?AL$2-!^losj*~5`IURyXhqi8h3p__ z(bVCD&zcTbA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P z#h@62eIN~f6?qoSgjXRSf?4n{$d6z)+{lqg1?IpVkyc)|=bwO|AM0P=5;3CA~QbOLOIKW>Y=Qh`Ah2A`3yK{k9?JE9-JCb$MU z9^}B6A{T+p@Xg3|U<>>pau3)FFGrpPf5M+2Z-Z^{FUU7wJKU%}ZXd|S_2rHbE3g9- zU6F2JCp;9{7yJbug&YcY!Bde_z;1X3atZhw{uQ|m?17s)5vf5QybaPG!!-$z5ug}@xyb3@2z)(q1t@{%A-990@KWSqa14G2c?BGYzeQGp z6L57$A_+JNw?;MxrEqto6F3F$hxF};{V&7dBnGkIH2fj*GB^YOh^z%?;i=B}Z~^Dw z+mRXIJlx%d=mNYPj;|tV5I=@nyW*D^{31LS?h7u#ZzHq8Wq7qK-v2K!xPpOKC#)1) zg)c?+2G`)3$aUa4{55h1xB-`TChbS!P520SV{i*T1(^gY;1$T(;5NJp`5fGVhr8jH z!SCYw^5Gc#0`9?YAQQoT_;chF@Bkj{PE-ef2p6$AkCq6Ud|B z1H6+r?j!so+!x**e1dOB27%A;1IWGL3*5p74<-C7+zH+me1pd$y?ktO4>^)2V=xJD S@a4!kKmy;1%w#WnUHl&u23)`Z From dbd89092f090b9673787fcfec71537c979564693 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Oct 2015 11:30:17 +0800 Subject: [PATCH 158/219] add accept header select to async method --- .../src/main/resources/csharp/api.mustache | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 4f65ba117bd7..f54f42d2eca6 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -166,7 +166,17 @@ namespace {{packageName}}.Api var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); {{#pathParams}}if ({{paramName}} != null) pathParams.Add("{{baseName}}", ApiClient.ParameterToString({{paramName}})); // path parameter {{/pathParams}} From 7b79abef63eb22b402d92fc6bcc6e14dec6249e6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Oct 2015 11:33:00 +0800 Subject: [PATCH 159/219] update c# sample --- .../src/main/csharp/IO/Swagger/Api/PetApi.cs | 96 ++++++++++++++++-- .../main/csharp/IO/Swagger/Api/StoreApi.cs | 48 ++++++++- .../src/main/csharp/IO/Swagger/Api/UserApi.cs | 96 ++++++++++++++++-- .../bin/Debug/SwaggerClientTest.dll | Bin 59904 -> 61952 bytes .../bin/Debug/SwaggerClientTest.dll.mdb | Bin 18627 -> 18987 bytes .../obj/Debug/SwaggerClientTest.dll | Bin 59904 -> 61952 bytes .../obj/Debug/SwaggerClientTest.dll.mdb | Bin 18627 -> 18987 bytes 7 files changed, 220 insertions(+), 20 deletions(-) diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs index 67048cfd0431..4e7e84fb7251 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/PetApi.cs @@ -306,7 +306,17 @@ public async System.Threading.Tasks.Task UpdatePetAsync (Pet body) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -394,7 +404,17 @@ public async System.Threading.Tasks.Task AddPetAsync (Pet body) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -482,7 +502,17 @@ public async System.Threading.Tasks.Task> FindPetsByStatusAsync (List< var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (status != null) queryParams.Add("status", ApiClient.ParameterToString(status)); // query parameter @@ -569,7 +599,17 @@ public async System.Threading.Tasks.Task> FindPetsByTagsAsync (List(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (tags != null) queryParams.Add("tags", ApiClient.ParameterToString(tags)); // query parameter @@ -661,7 +701,17 @@ public async System.Threading.Tasks.Task GetPetByIdAsync (long? petId) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter @@ -759,7 +809,17 @@ public async System.Threading.Tasks.Task UpdatePetWithFormAsync (string petId, s var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter @@ -857,7 +917,17 @@ public async System.Threading.Tasks.Task DeletePetAsync (long? petId, string api var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter @@ -957,7 +1027,17 @@ public async System.Threading.Tasks.Task UploadFileAsync (long? petId, string ad var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (petId != null) pathParams.Add("petId", ApiClient.ParameterToString(petId)); // path parameter diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs index d106aa752d3c..f96b773c76f9 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/StoreApi.cs @@ -211,7 +211,17 @@ public String GetBasePath() var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -297,7 +307,17 @@ public async System.Threading.Tasks.Task PlaceOrderAsync (Order body) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -389,7 +409,17 @@ public async System.Threading.Tasks.Task GetOrderByIdAsync (string orderI var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter @@ -481,7 +511,17 @@ public async System.Threading.Tasks.Task DeleteOrderAsync (string orderId) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (orderId != null) pathParams.Add("orderId", ApiClient.ParameterToString(orderId)); // path parameter diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs index 5b839e7a8943..f7c68cfbe35d 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Api/UserApi.cs @@ -298,7 +298,17 @@ public async System.Threading.Tasks.Task CreateUserAsync (User body) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -386,7 +396,17 @@ public async System.Threading.Tasks.Task CreateUsersWithArrayInputAsync (List(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -474,7 +494,17 @@ public async System.Threading.Tasks.Task CreateUsersWithListInputAsync (List(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -565,7 +595,17 @@ public async System.Threading.Tasks.Task LoginUserAsync (string username var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) queryParams.Add("username", ApiClient.ParameterToString(username)); // query parameter @@ -650,7 +690,17 @@ public async System.Threading.Tasks.Task LogoutUserAsync () var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); @@ -742,7 +792,17 @@ public async System.Threading.Tasks.Task GetUserByNameAsync (string userna var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter @@ -837,7 +897,17 @@ public async System.Threading.Tasks.Task UpdateUserAsync (string username, User var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter @@ -931,7 +1001,17 @@ public async System.Threading.Tasks.Task DeleteUserAsync (string username) var formParams = new Dictionary(); var fileParams = new Dictionary(); String postBody = null; - + + // to determine the Accept header + String[] http_header_accepts = new String[] { + "application/json", "application/xml" + }; + String http_header_accept = ApiClient.SelectHeaderAccept(http_header_accepts); + if (http_header_accept != null) + headerParams.Add("Accept", ApiClient.SelectHeaderAccept(http_header_accepts)); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json pathParams.Add("format", "json"); if (username != null) pathParams.Add("username", ApiClient.ParameterToString(username)); // path parameter diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll index 7fbacf3096b1f132af50ef0bc88607639316455b..74b5b6455e3f793db9f44be0d3daedbfed1a907d 100755 GIT binary patch delta 20674 zcmc(H36xaTwf4TZyQ{0JyQ{0KiyoL~3Q%N{85s?O%GfB#AZVk2Om??|p1Kr7Ku}~V zf@p}4NDLBVObSJjL{KD&qQOKFjhGmDC<-wqYBWz@{{8K9y6(Nu?>*PQ@~^+v>T~wD z_ddhk=R4;PRj~ZEoaLu-Hh!<@Lm~?BAAgpGHto4O(lun!6@V=*3g&ETRhn*PT^C+? z1{(hRFnzbx**cqk(&}LSHT{m&x^gBrz-J`?*_20pwh(<O=ui*y%5FvVUfH?lh|@Hx>^bnQQHFrS`Zob0BY<)pUySn5I2S(8qM`F+H<5 zpFQRoj|Co&h1z3brfulgR?`~eu}ph3LLVvZk;()M4p z%_1i^XZ~9FxYc&6pj>CC@qEbRxl4QQ${dcoW~Fu;&!0=3=VYX|ohPN%eeV-FiK-pv zAxP9YQN+{i#K~>awSfBBL=mDATMb~Bu-(W(9k`s;oO+@qycQ=bfb1F;7du_pY}e*+ z7wPhnzUlS3WfPoBp|cfMBf&Wc*b16OOIdV!!KP65ZI515Hx_HI;;tHQu!u(ur^l95 zbn|qF^Xoo|LJC~!vdQNh_1<_X6J7zth z(d#(^HigoxCptCj*-!&nPg@O6A8J~f^7V-=suxv;K5tP+VH}_TAl8)IY6uKUnkWfK zNi0gjP=m#a#vT%kfigLUCZERwjr$4D z#~H_Fv-sm(ae^yOtQRZ8PL;?)k4X^Y&efK6hNK-cP zC&GVMFe|3;pXZQ4q&bOp+82k6ORq(20=-cC={2sNU$Z$VXBOKHzpi)18(gv46=#bm z^tusZ+_?#rrq>*ZwpzfIp%*loUUOknC=I>Psi9X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fvrF&&|6?Zg?=Yo^VZh^R7N^K5G)zIyxaNT|DB zsM+>y{a5aveW3l+Uw^UZynCBB($3>83C05l&M_i1tq*TAiBAKtyM0+t4}m@6%k}X_ Y-wx2?!Q=n*=;h_{@VDP+%gQtU2kSYcWdHyG diff --git a/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/bin/Debug/SwaggerClientTest.dll.mdb index b5012fc14daf30325e6c9721e0ceeca19cfb0255..9700c554fbd4050223bb5d8522f3cfd3caa1be4c 100644 GIT binary patch delta 2649 zcmb7`c~BE)7{=e-1PPH<2nbP9A?i3xu z_Iw3-WHeEj62blojH`)1q-xxtTYqckflES8k&Bn6td44HGM2HuoS(<$n4s0hCGoY@ zc`T>SMdIJeV#vK z8`|RU$8ns+qSXxH_*!v5wdI3Xke`a#i{%Y}&Rt@~9vT*<_O&7Q`#a2xEf<&vClptaOrg?CwOWOZ*{`c+99mRw?6U z+>p7dSv`L*-uhwBt%6!mj}QbQz%z87(N}Qe>J#Zm;!z1h=z41sZA;poWXCr5gWV7^ z{xc`6He$+a5;&uj^A!T3=f3L3?MtHlNk2+7k-jsTzE9qjY^VP!@4IQxqn+sfp)r9H zJ-ygLKa@;|lYf$EBHfZgdsFtM*y(#1r}J{2!Xdhevz(9tVX<~(vdLE%rvG%58`qFR zKc^g*2qLjQm5!tyO|=s@4nV)&3Gq=cpXX{_FgxMl_mMccnTye-8+R&|PN$xc?iYFI z(&&8Jg)}?Q>?-oM^uaR+n^&5HLK3k2VQjN*MDOxPhpHoQr%_Yd9f>588`J4p`t@`> zxwBs~GlvGVkzRi6RH)MTVLG*>w@NpPptc3nzMx|PYYiPH^ll=vOu=3c89m!+{%o5l zwa{0X@Lmb0cjHSks5E17hOGmDcxwi=WwcARoL9)c<@;Q1b7*YB=c!Dq^I`QN?!6DX zDQt+gIFm{;OEY`1nbelqF4ZEoip|i!u*}wo5p1A-Fq^CPoFFcR*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XEzUpTer@;5h|ayy^W* zGOTrlegp6qlWc4^6-KaqwXi<6Z!`Td)5i-NBIjgb6KwS&YBRa5SJVvYk|LTx(v6uD zEoy_DilUC#c4lc+QTL?Ia_Eh;9Cb3Hu;gJ31m zYm8Gxk2YG9(O}&5Gp`vuapp|=3AfvrF&&|6?Zg?=Yo^VZh^R7N^K5G)zIyxaNT|DB zsM+>y{a5aveW3l+Uw^UZynCBB($3>83C05l&M_i1tq*TAiBAKtyM0+t4}m@6%k}X_ Y-wx2?!Q=n*=;h_{@VDP+%gQtU2kSYcWdHyG diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb index b5012fc14daf30325e6c9721e0ceeca19cfb0255..9700c554fbd4050223bb5d8522f3cfd3caa1be4c 100644 GIT binary patch delta 2649 zcmb7`c~BE)7{=e-1PPH<2nbP9A?i3xu z_Iw3-WHeEj62blojH`)1q-xxtTYqckflES8k&Bn6td44HGM2HuoS(<$n4s0hCGoY@ zc`T>SMdIJeV#vK z8`|RU$8ns+qSXxH_*!v5wdI3Xke`a#i{%Y}&Rt@~9vT*<_O&7Q`#a2xEf<&vClptaOrg?CwOWOZ*{`c+99mRw?6U z+>p7dSv`L*-uhwBt%6!mj}QbQz%z87(N}Qe>J#Zm;!z1h=z41sZA;poWXCr5gWV7^ z{xc`6He$+a5;&uj^A!T3=f3L3?MtHlNk2+7k-jsTzE9qjY^VP!@4IQxqn+sfp)r9H zJ-ygLKa@;|lYf$EBHfZgdsFtM*y(#1r}J{2!Xdhevz(9tVX<~(vdLE%rvG%58`qFR zKc^g*2qLjQm5!tyO|=s@4nV)&3Gq=cpXX{_FgxMl_mMccnTye-8+R&|PN$xc?iYFI z(&&8Jg)}?Q>?-oM^uaR+n^&5HLK3k2VQjN*MDOxPhpHoQr%_Yd9f>588`J4p`t@`> zxwBs~GlvGVkzRi6RH)MTVLG*>w@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||$8!LO2Q)guT#u(?!S2xbY8qPbSSS0bqV}8iB2b#OBG_m{$x6kT$F52xF{Z} z0SN(kUg7Wdo~rmSa5#mN$#g2YOsW;LcBjyul)WiZmdru6ec`P&)ix6`tTvVEQtPF*9IMo5Hgz)=zgF#|USjGo$ioWyTmDQixnmb6x>RGh`}box8}M7lky@|BOx z1fB0}t!m7a7$50qCal7eTqiGhLn*tEP8ZWJNdaQuu?#B7_$$L6c)<27^*>5Qx(WQD zZbabO3_6!_UK%Y{|7oWE<^yJX^>?+p@>P zcT5SGbv92}l?GaAnR1^W_DZ zv^{f2rqwgT$03Uc5Y2`z6DbPe1<)068+;#xe|L((fkbks5*!bAhOU7>hnu16;9B^4 zs0!Q+Z-T193xkMyz%^h!cm-4ou7YO-Q5Myq(S$}LR1cmPOw zfg8j==r%Yygy=E20X!G{A#?|9g)f2bf=l2>phobdP@*&7d*F!BETV99+()AjJ{xKR zTjBel2Vmu76oVgvUkAHD&EQ11H`D@N1z!oZf-k|pf*yfy!*4*3!Sln=2Yv!x4qghi z;r@yufC*{`m%&S+4sb{~z7}vNI0hUIb%FQ5=R!}x#qc7i8|;N&C1v0qupf95^bBl( eM?l0#u@Y{97&sq3BnKY?8o$B|b^N0lXa57~)H Date: Tue, 6 Oct 2015 10:58:48 +0700 Subject: [PATCH 160/219] [objc] Add casts that avoid method resolution errors Because the `data` that we're deserializing is of type `id` (essentially untyped), it's possible to have method resolution clashes without explicitly casting here once we've parsed a type. I had this issue with a pagination container model, for instance, which has a field named `count` that conflicts with the property of the same name on `NSArray` or `NSDictionary`. --- .../main/resources/objc/ApiClient-body.mustache | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index fb2bad76aa4e..d1908e5d2f11 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -311,9 +311,10 @@ static void (^reachabilityChangeBlock)(int); range:NSMakeRange(0, [class length])]; if (match) { + NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; } @@ -332,9 +333,10 @@ static void (^reachabilityChangeBlock)(int); range:NSMakeRange(0, [class length])]; if (match) { + NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; }]; @@ -352,9 +354,10 @@ static void (^reachabilityChangeBlock)(int); range:NSMakeRange(0, [class length])]; if (match) { + NSDictionary *dataDict = data; NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; }]; @@ -728,7 +731,8 @@ static void (^reachabilityChangeBlock)(int); return [object ISO8601String]; } else if ([object isKindOfClass:[NSArray class]]) { - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if (obj) { [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; @@ -737,7 +741,8 @@ static void (^reachabilityChangeBlock)(int); return sanitizedObjs; } else if ([object isKindOfClass:[NSDictionary class]]) { - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (obj) { [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; From eaddebe220d04134882f8c8d7b7010a7aceb70f1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Oct 2015 16:13:06 +0800 Subject: [PATCH 161/219] Update list of generator --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index cf0f3a3b15f0..5075a50c19e7 100644 --- a/README.md +++ b/README.md @@ -217,13 +217,14 @@ There are different aspects of customizing the code generator beyond just creati ``` $ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ +swagger-codegen|csharp_fix_accept⚡ ⇒ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ AbstractTypeScriptClientCodegen.java AkkaScalaClientCodegen.java AndroidClientCodegen.java AsyncScalaClientCodegen.java CSharpClientCodegen.java -CodeGenStatus.java CsharpDotNet2ClientCodegen.java +DartClientCodegen.java FlashClientCodegen.java JavaClientCodegen.java JavaInflectorServerCodegen.java @@ -232,7 +233,6 @@ NodeJSServerCodegen.java ObjcClientCodegen.java PerlClientCodegen.java PhpClientCodegen.java -Python3ClientCodegen.java PythonClientCodegen.java Qt5CPPGenerator.java RubyClientCodegen.java From b27663e1adf10160b107f3cd15c58ee941a5a91b Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Oct 2015 16:14:13 +0800 Subject: [PATCH 162/219] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 5075a50c19e7..42ee357746f2 100644 --- a/README.md +++ b/README.md @@ -217,7 +217,6 @@ There are different aspects of customizing the code generator beyond just creati ``` $ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ -swagger-codegen|csharp_fix_accept⚡ ⇒ ls -1 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ AbstractTypeScriptClientCodegen.java AkkaScalaClientCodegen.java AndroidClientCodegen.java From 3b36bbe97deb394d6f07d72cc4d56ee97716a6b1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 6 Oct 2015 18:39:44 +0800 Subject: [PATCH 163/219] Update README.mustache --- .../src/main/resources/JavaJaxRS/README.mustache | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache index 3ffa01fb2571..3f0809d4734d 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/README.mustache @@ -1,10 +1,8 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled scalatra server. +is an example of building a swagger-enabled JAX-RS server. -This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: - -[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. From 733e19c113b3cf77be28489ae9bc07b425cdd053 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 7 Oct 2015 17:11:52 -0700 Subject: [PATCH 164/219] fixed NPE for objc client --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 3 ++- .../src/main/resources/JavaInflector/inflector.mustache | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 6a65c6c4add6..efc0aa31dbc8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -815,7 +815,8 @@ public CodegenProperty fromProperty(String name, Property p) { if (property.items.isEnum) { property.datatypeWithEnum = property.datatypeWithEnum.replace(property.items.baseType, property.items.datatypeWithEnum); - property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); + if(property.defaultValue != null) + property.defaultValue = property.defaultValue.replace(property.items.baseType, property.items.datatypeWithEnum); } } } else if (p instanceof MapProperty) { diff --git a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache index d9d02ea93a82..99ace468103e 100644 --- a/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaInflector/inflector.mustache @@ -4,3 +4,7 @@ swaggerUrl: ./src/main/swagger/swagger.json modelMappings: {{#models}}{{#model}}{{classname}} : {{modelPackage}}.{{classname}}{{/model}} {{/models}} +entityProcessors: + - json + - xml + - yaml \ No newline at end of file From 3bd4502bbf1cf3a4feb9e378ae0d4b4f421e4a28 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Thu, 8 Oct 2015 11:25:43 +0200 Subject: [PATCH 165/219] Deserialize httpHeader. See #1354. Regenerated php-petstore sample. --- .../src/main/resources/php/api.mustache | 13 +++-- .../php/SwaggerClient-php/lib/Api/PetApi.php | 50 ++++++++++++------- .../SwaggerClient-php/lib/Api/StoreApi.php | 40 +++++++++------ .../php/SwaggerClient-php/lib/Api/UserApi.php | 32 ++++++++---- .../lib/ObjectSerializer.php | 2 +- 5 files changed, 88 insertions(+), 49 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index bb40ae7a98d6..4f0184310be8 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -170,6 +170,13 @@ use \{{invokerPackage}}\ObjectSerializer; $queryParams, $httpBody, $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} ); + {{#returnType}} + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '{{returnType}}', $httpHeader); + {{/returnType}} } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: @@ -181,11 +188,7 @@ use \{{invokerPackage}}\ObjectSerializer; throw $e; } {{#returnType}} - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '{{returnType}}'); + return null; {{/returnType}} } {{/operation}} 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 8e75c360aeab..45b2bbfe369e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -146,6 +146,7 @@ public function updatePet($body=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -210,6 +211,7 @@ public function addPet($body=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -273,6 +275,13 @@ public function findPetsByStatus($status=null) $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -284,11 +293,7 @@ public function findPetsByStatus($status=null) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]'); + return null; } @@ -346,6 +351,13 @@ public function findPetsByTags($tags=null) $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -357,11 +369,7 @@ public function findPetsByTags($tags=null) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet[]'); + return null; } @@ -416,6 +424,9 @@ public function getPetById($pet_id) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); if (isset($apiKey)) { $headerParams['api_key'] = $apiKey; @@ -423,9 +434,6 @@ public function getPetById($pet_id) - - //TODO support oauth - // make the API Call try { @@ -434,6 +442,13 @@ public function getPetById($pet_id) $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -445,11 +460,7 @@ public function getPetById($pet_id) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Pet'); + return null; } @@ -523,6 +534,7 @@ public function updatePetWithForm($pet_id, $name=null, $status=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -598,6 +610,7 @@ public function deletePet($pet_id, $api_key=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -677,6 +690,7 @@ public function uploadFile($pet_id, $additional_metadata=null, $file=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php index ede8a3c14dad..bab53eaa4dd7 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -145,6 +145,13 @@ public function getInventory() $queryParams, $httpBody, $headerParams, 'map[string,int]' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, 'map[string,int]', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -156,11 +163,7 @@ public function getInventory() throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, 'map[string,int]'); + return null; } @@ -216,6 +219,13 @@ public function placeOrder($body=null) $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -227,11 +237,7 @@ public function placeOrder($body=null) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order'); + return null; } @@ -294,6 +300,13 @@ public function getOrderById($order_id) $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -305,11 +318,7 @@ public function getOrderById($order_id) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\Order'); + return null; } @@ -372,6 +381,7 @@ public function deleteOrder($order_id) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php index d23731e08ffd..66024f4db4e8 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -143,6 +143,7 @@ public function createUser($body=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -204,6 +205,7 @@ public function createUsersWithArrayInput($body=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -265,6 +267,7 @@ public function createUsersWithListInput($body=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -329,6 +332,13 @@ public function loginUser($username=null, $password=null) $queryParams, $httpBody, $headerParams, 'string' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, 'string', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -340,11 +350,7 @@ public function loginUser($username=null, $password=null) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, 'string'); + return null; } @@ -395,6 +401,7 @@ public function logoutUser() $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -463,6 +470,13 @@ public function getUserByName($username) $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\User' ); + + if (!$response) { + return null; + } + + return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User', $httpHeader); + } catch (ApiException $e) { switch ($e->getCode()) { case 200: @@ -474,11 +488,7 @@ public function getUserByName($username) throw $e; } - if (!$response) { - return null; - } - - return $this->apiClient->getSerializer()->deserialize($response, '\Swagger\Client\Model\User'); + return null; } @@ -546,6 +556,7 @@ public function updateUser($username, $body=null) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } @@ -614,6 +625,7 @@ public function deleteUser($username) $queryParams, $httpBody, $headerParams ); + } catch (ApiException $e) { switch ($e->getCode()) { } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 0d281b9d1fa3..efdc1c896ab4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -193,7 +193,7 @@ public function deserialize($data, $class, $httpHeader=null) $deserialized = $values; } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { + } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { From b7b8b527dbb6c7d0a70b2daf00273d81ff7e3e52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Thu, 8 Oct 2015 11:46:36 +0200 Subject: [PATCH 166/219] Use HTTP headers from ApiException in PHP client. The `$httpHeader` variable was not set when catching exceptions. See also #1354. Regenerated php-petstore sample. --- .../src/main/resources/php/api.mustache | 2 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 12 ++++++------ .../php/SwaggerClient-php/lib/Api/StoreApi.php | 6 +++--- .../php/SwaggerClient-php/lib/Api/UserApi.php | 4 ++-- .../php/SwaggerClient-php/lib/ObjectSerializer.php | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index bb40ae7a98d6..9e2cabc92bc8 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -173,7 +173,7 @@ use \{{invokerPackage}}\ObjectSerializer; } catch (ApiException $e) { switch ($e->getCode()) { {{#responses}}{{#dataType}} case {{code}}: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '{{dataType}}', $e->getResponseHeaders()); $e->setResponseObject($data); break;{{/dataType}}{{/responses}} } 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 8e75c360aeab..b94fd3c5e724 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -276,7 +276,7 @@ public function findPetsByStatus($status=null) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -349,7 +349,7 @@ public function findPetsByTags($tags=null) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet[]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -416,6 +416,9 @@ public function getPetById($pet_id) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); if (isset($apiKey)) { $headerParams['api_key'] = $apiKey; @@ -423,9 +426,6 @@ public function getPetById($pet_id) - - //TODO support oauth - // make the API Call try { @@ -437,7 +437,7 @@ public function getPetById($pet_id) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Pet', $e->getResponseHeaders()); $e->setResponseObject($data); break; } 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 ede8a3c14dad..d73032b33296 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -148,7 +148,7 @@ public function getInventory() } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'map[string,int]', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -219,7 +219,7 @@ public function placeOrder($body=null) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -297,7 +297,7 @@ public function getOrderById($order_id) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\Order', $e->getResponseHeaders()); $e->setResponseObject($data); break; } 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 d23731e08ffd..b1bbf32c09f1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -332,7 +332,7 @@ public function loginUser($username=null, $password=null) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), 'string', $e->getResponseHeaders()); $e->setResponseObject($data); break; } @@ -466,7 +466,7 @@ public function getUserByName($username) } catch (ApiException $e) { switch ($e->getCode()) { case 200: - $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $httpHeader); + $data = $this->apiClient->getSerializer()->deserialize($e->getResponseBody(), '\Swagger\Client\Model\User', $e->getResponseHeaders()); $e->setResponseObject($data); break; } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 0d281b9d1fa3..efdc1c896ab4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -193,7 +193,7 @@ public function deserialize($data, $class, $httpHeader=null) $deserialized = $values; } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { + } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { From d451d4efb8af2fee8100493268e92727f0bc0324 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 1 Oct 2015 23:06:09 +0800 Subject: [PATCH 167/219] fix NPE when model's allof with no property --- .../src/main/java/io/swagger/codegen/DefaultCodegen.java | 2 +- .../java/default/src/main/java/io/swagger/client/ApiClient.java | 2 +- .../default/src/main/java/io/swagger/client/ApiException.java | 2 +- .../default/src/main/java/io/swagger/client/Configuration.java | 2 +- .../java/default/src/main/java/io/swagger/client/JSON.java | 2 +- .../java/default/src/main/java/io/swagger/client/Pair.java | 2 +- .../default/src/main/java/io/swagger/client/StringUtil.java | 2 +- .../java/default/src/main/java/io/swagger/client/TypeRef.java | 2 +- .../default/src/main/java/io/swagger/client/api/PetApi.java | 2 +- .../default/src/main/java/io/swagger/client/api/StoreApi.java | 2 +- .../default/src/main/java/io/swagger/client/api/UserApi.java | 2 +- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../src/main/java/io/swagger/client/auth/Authentication.java | 2 +- .../src/main/java/io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../default/src/main/java/io/swagger/client/auth/OAuth.java | 2 +- .../default/src/main/java/io/swagger/client/model/Category.java | 2 +- .../default/src/main/java/io/swagger/client/model/Order.java | 2 +- .../java/default/src/main/java/io/swagger/client/model/Pet.java | 2 +- .../java/default/src/main/java/io/swagger/client/model/Tag.java | 2 +- .../default/src/main/java/io/swagger/client/model/User.java | 2 +- 20 files changed, 20 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index efc0aa31dbc8..89cf238fa8dc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -584,7 +584,7 @@ public CodegenModel fromModel(String name, Model model, Map allDe } } // interfaces (intermediate models) - if (allDefinitions != null) { + if (allDefinitions != null && composed.getInterfaces() != null) { for (RefModel _interface : composed.getInterfaces()) { final String interfaceRef = toModelName(_interface.getSimpleRef()); final Model interfaceModel = allDefinitions.get(interfaceRef); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java index c4b1153dcd28..d468a50f9e32 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiClient.java @@ -39,7 +39,7 @@ import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class ApiClient { private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java index 649e4132cb04..d4b75ae39de4 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/ApiException.java @@ -3,7 +3,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class ApiException extends Exception { private int code = 0; private Map> responseHeaders = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java index e7837fa47a5c..5ad2bfb9049e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Configuration.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java index 19c2420656ad..13acc71c60c7 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/JSON.java @@ -6,7 +6,7 @@ import java.io.IOException; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class JSON { private ObjectMapper mapper; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java index 78c15c6c2a01..11bed7752c4b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/Pair.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class Pair { private String name = ""; private String value = ""; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java index 2348914456a9..d00d8e4e42ab 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java index a0ebe355071e..818a1b9cca5d 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/TypeRef.java @@ -3,7 +3,7 @@ import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class TypeRef { private final Type type; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index ca9111f41764..a1512a030c3e 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class PetApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index f0628c595c98..7a012f3e19e0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class StoreApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index 3412c565b376..28f16243ab52 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -17,7 +17,7 @@ import java.util.Map; import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class UserApi { private ApiClient apiClient; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 69d80c755b84..3d081ca0d4ff 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class ApiKeyAuth implements Authentication { private final String location; private final String paramName; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java index 0c254861af47..1c914f25e199 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/Authentication.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public interface Authentication { /** Apply authentication settings to header and query params. */ void applyToParams(List queryParams, Map headerParams); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 19dfa96e9f20..68466d091875 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -8,7 +8,7 @@ import java.io.UnsupportedEncodingException; import javax.xml.bind.DatatypeConverter; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class HttpBasicAuth implements Authentication { private String username; private String password; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java index ef89432a3598..996922d567ef 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/auth/OAuth.java @@ -5,7 +5,7 @@ import java.util.Map; import java.util.List; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class OAuth implements Authentication { @Override public void applyToParams(List queryParams, Map headerParams) { diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java index ea615a58e98b..8e49fe2f1d37 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Category.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index b51be0c52e03..083a6e87c67b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -10,7 +10,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index aca4848ff988..a55f3d73fbb0 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -12,7 +12,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java index 98ff0c44e177..7d112784c9f8 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Tag.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java index f4a80143b91f..2331a90f7d43 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/User.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-01T23:05:28.119+08:00") public class User { private Long id = null; From 69a346cb576fd4584ef6c7f984821e89f1580967 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 2 Oct 2015 22:43:37 +0800 Subject: [PATCH 168/219] remove python3 frmo all-petstore.sh --- bin/all-petstore.sh | 1 - 1 file changed, 1 deletion(-) diff --git a/bin/all-petstore.sh b/bin/all-petstore.sh index 180e95590be4..2f9d4c0c0ff1 100755 --- a/bin/all-petstore.sh +++ b/bin/all-petstore.sh @@ -33,7 +33,6 @@ cd $APP_DIR ./bin/perl-petstore.sh ./bin/php-petstore.sh ./bin/python-petstore.sh -./bin/python3-petstore.sh ./bin/qt5-petstore.sh ./bin/ruby-petstore.sh ./bin/scala-async-petstore.sh From 6ee42bebe686aa0de3b7e82238afbbaec4f98848 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Oct 2015 23:31:57 +0800 Subject: [PATCH 169/219] add exception handling for #1267 --- .../java/io/swagger/codegen/DefaultCodegen.java | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 89cf238fa8dc..69d7cadbf0ad 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -492,10 +492,16 @@ public String getSwaggerType(Property p) { } else if (p instanceof DecimalProperty) { datatype = "number"; } else if (p instanceof RefProperty) { - RefProperty r = (RefProperty) p; - datatype = r.get$ref(); - if (datatype.indexOf("#/definitions/") == 0) { - datatype = datatype.substring("#/definitions/".length()); + try { + RefProperty r = (RefProperty) p; + datatype = r.get$ref(); + if (datatype.indexOf("#/definitions/") == 0) { + datatype = datatype.substring("#/definitions/".length()); + } + } catch (Exception e) { + LOGGER.warn("Error obtaining the datatype from RefProperty:" + p + ". Datatype default to Object"); + datatype = "Object"; + e.printStackTrace(); } } else { if (p != null) { From 8e9e3a6171e3923d5d0661652ad7cc2c4810a930 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Oct 2015 23:52:41 +0800 Subject: [PATCH 170/219] update nodejs to use the var serverport --- .../src/main/resources/nodejs/index.mustache | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache index 0562c2f0c376..419b3fb5e63f 100644 --- a/modules/swagger-codegen/src/main/resources/nodejs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/nodejs/index.mustache @@ -31,8 +31,8 @@ swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { app.use(middleware.swaggerUi()); // Start the server - http.createServer(app).listen({{serverPort}}, function () { - console.log('Your server is listening on port %d (http://localhost:%d)', {{serverPort}}, {{serverPort}}); - console.log('Swagger-ui is available on http://localhost:%d/docs', {{serverPort}}); + http.createServer(app).listen(serverPort, function () { + console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort); + console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort); }); -}); \ No newline at end of file +}); From 725df15dd5ec2f17c62dca089eb93866b4ce8366 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 8 Oct 2015 23:57:14 +0800 Subject: [PATCH 171/219] update sample for nodejs --- .../server/petstore/nodejs/controllers/StoreService.js | 4 ++-- samples/server/petstore/nodejs/index.js | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/server/petstore/nodejs/controllers/StoreService.js b/samples/server/petstore/nodejs/controllers/StoreService.js index 947774aad2ec..27c18517ff55 100644 --- a/samples/server/petstore/nodejs/controllers/StoreService.js +++ b/samples/server/petstore/nodejs/controllers/StoreService.js @@ -24,7 +24,7 @@ exports.placeOrder = function(body) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-09-03T14:34:08.343+0000" + "shipDate" : "2015-10-08T15:56:08.367+0000" }; @@ -43,7 +43,7 @@ exports.getOrderById = function(orderId) { "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-09-03T14:34:08.347+0000" + "shipDate" : "2015-10-08T15:56:08.371+0000" }; diff --git a/samples/server/petstore/nodejs/index.js b/samples/server/petstore/nodejs/index.js index c73b630ed20a..c922cc7c1e7d 100644 --- a/samples/server/petstore/nodejs/index.js +++ b/samples/server/petstore/nodejs/index.js @@ -31,8 +31,8 @@ swaggerTools.initializeMiddleware(swaggerDoc, function (middleware) { app.use(middleware.swaggerUi()); // Start the server - http.createServer(app).listen(8080, function () { - console.log('Your server is listening on port %d (http://localhost:%d)', 8080, 8080); - console.log('Swagger-ui is available on http://localhost:%d/docs', 8080); + http.createServer(app).listen(serverPort, function () { + console.log('Your server is listening on port %d (http://localhost:%d)', serverPort, serverPort); + console.log('Swagger-ui is available on http://localhost:%d/docs', serverPort); }); -}); \ No newline at end of file +}); From 503ffd06d0471527586453dc1215edbbef605046 Mon Sep 17 00:00:00 2001 From: cristiangarciascmspain Date: Thu, 8 Oct 2015 18:26:41 +0200 Subject: [PATCH 172/219] Add StartAttachListener that fixes #1330 --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index f14e7b825cba..d2cbadb394fd 100644 --- a/pom.xml +++ b/pom.xml @@ -74,6 +74,7 @@ ${surefire-version} none:none + -XX:+StartAttachListener From edf2642e739f75debcc40bf454c8ee9513215f80 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 8 Oct 2015 21:18:11 +0800 Subject: [PATCH 173/219] Support model name like "List" in Java clients Support generating model files with name like "List", "Map" and "Date" by using full qualified names when using them from the java.util package. --- .../io/swagger/codegen/DefaultCodegen.java | 31 ++++++++---------- .../codegen/languages/JavaClientCodegen.java | 32 +++++++++++-------- .../src/main/resources/Java/api.mustache | 14 ++------ .../Java/libraries/jersey2/api.mustache | 12 ++----- .../Java/libraries/okhttp-gson/api.mustache | 12 ++----- .../Java/libraries/retrofit/api.mustache | 11 +++---- 6 files changed, 46 insertions(+), 66 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index efc0aa31dbc8..55868c0acaff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -311,15 +311,14 @@ public DefaultCodegen() { ); typeMapping = new HashMap(); - typeMapping.put("array", "List"); - typeMapping.put("map", "Map"); - typeMapping.put("List", "List"); + typeMapping.put("array", "java.util.List"); + typeMapping.put("map", "java.util.Map"); typeMapping.put("boolean", "Boolean"); typeMapping.put("string", "String"); typeMapping.put("int", "Integer"); typeMapping.put("float", "Float"); typeMapping.put("number", "BigDecimal"); - typeMapping.put("DateTime", "Date"); + typeMapping.put("DateTime", "java.util.Date"); typeMapping.put("long", "Long"); typeMapping.put("short", "Short"); typeMapping.put("char", "String"); @@ -337,15 +336,7 @@ public DefaultCodegen() { importMapping.put("BigDecimal", "java.math.BigDecimal"); importMapping.put("UUID", "java.util.UUID"); importMapping.put("File", "java.io.File"); - importMapping.put("Date", "java.util.Date"); importMapping.put("Timestamp", "java.sql.Timestamp"); - importMapping.put("Map", "java.util.Map"); - importMapping.put("HashMap", "java.util.HashMap"); - importMapping.put("Array", "java.util.List"); - importMapping.put("ArrayList", "java.util.ArrayList"); - importMapping.put("List", "java.util.*"); - importMapping.put("Set", "java.util.*"); - importMapping.put("DateTime", "org.joda.time.*"); importMapping.put("LocalDateTime", "org.joda.time.*"); importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); @@ -1038,7 +1029,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation } } for (String i : imports) { - if (!defaultIncludes.contains(i) && !languageSpecificPrimitives.contains(i)) { + if (needToImport(i)) { op.imports.add(i); } } @@ -1311,6 +1302,12 @@ public List fromSecurity(Map return secs; } + protected boolean needToImport(String type) { + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type) + && type.indexOf(".") < 0; + } + protected List> toExamples(Map examples) { if (examples == null) { return null; @@ -1414,7 +1411,7 @@ public static String underscore(String word) { } private void addImport(CodegenModel m, String type) { - if (type != null && !languageSpecificPrimitives.contains(type) && !defaultIncludes.contains(type)) { + if (type != null && needToImport(type)) { m.imports.add(type); } } @@ -1593,8 +1590,8 @@ protected CliOption buildLibraryCliOption(Map supportedLibraries * @return sanitized string */ public String sanitizeName(String name) { - // NOTE: performance wise, we should have written with 2 replaceAll to replace desired - // character with _ or empty character. Below aims to spell out different cases we've + // NOTE: performance wise, we should have written with 2 replaceAll to replace desired + // character with _ or empty character. Below aims to spell out different cases we've // encountered so far and hopefully make it easier for others to add more special // cases in the future. @@ -1617,7 +1614,7 @@ public String sanitizeName(String name) { // input name and age => input_name_and_age name = name.replaceAll(" ", "_"); - + // remove everything else other than word, number and _ // $php_variable => php_variable return name.replaceAll("[^a-zA-Z0-9_]", ""); 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 360dc9c0f2f0..1276c2dde6c5 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 @@ -71,8 +71,8 @@ public JavaClientCodegen() { "Object", "byte[]") ); - instantiationTypes.put("array", "ArrayList"); - instantiationTypes.put("map", "HashMap"); + instantiationTypes.put("array", "java.util.ArrayList"); + instantiationTypes.put("map", "java.util.HashMap"); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); @@ -107,7 +107,7 @@ public String getHelp() { @Override public void processOpts() { super.processOpts(); - + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); } else { @@ -158,7 +158,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); - + final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", File.separator); supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); @@ -172,7 +172,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("Pair.mustache", invokerFolder, "Pair.java")); supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); } - + // library-specific files if ("okhttp-gson".equals(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call @@ -189,25 +189,25 @@ public void processOpts() { } private void sanitizeConfig() { - // Sanitize any config options here. We also have to update the additionalProperties because + // Sanitize any config options here. We also have to update the additionalProperties because // the whole additionalProperties object is injected into the main object passed to the mustache layer - + this.setApiPackage(sanitizePackageName(apiPackage)); if (additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { this.additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); } - + this.setModelPackage(sanitizePackageName(modelPackage)); if (additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { this.additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); } - + this.setInvokerPackage(sanitizePackageName(invokerPackage)); if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { this.additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); } } - + @Override public String escapeReservedWord(String name) { return "_" + name; @@ -294,10 +294,10 @@ public String getTypeDeclaration(Property p) { public String toDefaultValue(Property p) { if (p instanceof ArrayProperty) { final ArrayProperty ap = (ArrayProperty) p; - return String.format("new ArrayList<%s>()", getTypeDeclaration(ap.getItems())); + return String.format("new java.util.ArrayList<%s>()", getTypeDeclaration(ap.getItems())); } else if (p instanceof MapProperty) { final MapProperty ap = (MapProperty) p; - return String.format("new HashMap()", getTypeDeclaration(ap.getAdditionalProperties())); + return String.format("new java.util.HashMap()", getTypeDeclaration(ap.getAdditionalProperties())); } return super.toDefaultValue(p); } @@ -308,7 +308,7 @@ public String getSwaggerType(Property p) { String type = null; if (typeMapping.containsKey(swaggerType)) { type = typeMapping.get(swaggerType); - if (languageSpecificPrimitives.contains(type)) { + if (languageSpecificPrimitives.contains(type) || type.indexOf(".") >= 0) { return type; } } else { @@ -394,7 +394,7 @@ public Map postProcessModels(Map objs) { } return objs; } - + public Map postProcessOperations(Map objs) { if("retrofit".equals(getLibrary())) { Map operations = (Map) objs.get("operations"); @@ -418,6 +418,10 @@ public Map postProcessOperations(Map objs) { return objs; } + protected boolean needToImport(String type) { + return super.needToImport(type) && type.indexOf(".") < 0; + } + private String findCommonPrefixOfVars(List vars) { String prefix = StringUtils.getCommonPrefix(vars.toArray(new String[vars.size()])); // exclude trailing characters that should be part of a valid variable diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index ad957261f2a4..38ebc1c54abd 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -6,17 +6,9 @@ import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; import {{invokerPackage}}.TypeRef; -import {{modelPackage}}.*; - -import java.util.*; - {{#imports}}import {{import}}; {{/imports}} -import java.io.File; -import java.util.Map; -import java.util.HashMap; - {{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -59,9 +51,9 @@ public class {{classname}} { .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - List {{localVariablePrefix}}queryParams = new ArrayList(); - Map {{localVariablePrefix}}headerParams = new HashMap(); - Map {{localVariablePrefix}}formParams = new HashMap(); + java.util.List {{localVariablePrefix}}queryParams = new java.util.ArrayList(); + java.util.Map {{localVariablePrefix}}headerParams = new java.util.HashMap(); + java.util.Map {{localVariablePrefix}}formParams = new java.util.HashMap(); {{#queryParams}} {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index d525db8a28d0..532f1ef78cf1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -8,15 +8,9 @@ import {{invokerPackage}}.TypeRef; import {{modelPackage}}.*; -import java.util.*; - {{#imports}}import {{import}}; {{/imports}} -import java.io.File; -import java.util.Map; -import java.util.HashMap; - {{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -58,9 +52,9 @@ public class {{classname}} { .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - List {{localVariablePrefix}}queryParams = new ArrayList(); - Map {{localVariablePrefix}}headerParams = new HashMap(); - Map {{localVariablePrefix}}formParams = new HashMap(); + java.util.List {{localVariablePrefix}}queryParams = new java.util.ArrayList(); + java.util.Map {{localVariablePrefix}}headerParams = new java.util.HashMap(); + java.util.Map {{localVariablePrefix}}formParams = new java.util.HashMap(); {{#queryParams}} {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index b272687c7fde..d1f38f0ac358 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -14,15 +14,9 @@ import com.squareup.okhttp.Call; import java.lang.reflect.Type; -import java.util.*; - {{#imports}}import {{import}}; {{/imports}} -import java.io.File; -import java.util.Map; -import java.util.HashMap; - {{#operations}} public class {{classname}} { private ApiClient {{localVariablePrefix}}apiClient; @@ -58,15 +52,15 @@ public class {{classname}} { String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - List {{localVariablePrefix}}queryParams = new ArrayList();{{#queryParams}} + java.util.List {{localVariablePrefix}}queryParams = new java.util.ArrayList();{{#queryParams}} if ({{paramName}} != null) {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - Map {{localVariablePrefix}}headerParams = new HashMap();{{#headerParams}} + java.util.Map {{localVariablePrefix}}headerParams = new java.util.HashMap();{{#headerParams}} if ({{paramName}} != null) {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - Map {{localVariablePrefix}}formParams = new HashMap();{{#formParams}} + java.util.Map {{localVariablePrefix}}formParams = new java.util.HashMap();{{#formParams}} if ({{paramName}} != null) {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index 89850d92bdc1..28d2d29f8d1a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -5,7 +5,6 @@ import {{modelPackage}}.*; import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; {{#imports}}import {{import}}; {{/imports}} @@ -22,7 +21,7 @@ public interface {{classname}} { */ {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} - @{{httpMethod}}("{{path}}") + @{{httpMethod}}("{{path}}") {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}} {{nickname}}({{^allParams}});{{/allParams}} {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}{{#hasMore}}, {{/hasMore}}{{^hasMore}} );{{/hasMore}}{{/allParams}} @@ -31,15 +30,15 @@ public interface {{classname}} { * {{summary}} * Async method {{#allParams}} * @param {{paramName}} {{description}} -{{/allParams}} * @param cb callback method +{{/allParams}} * @param cb callback method * @return void */ {{#formParams}}{{#-first}} {{#isMultipart}}@Multipart{{/isMultipart}}{{^isMultipart}}@FormUrlEncoded{{/isMultipart}}{{/-first}}{{/formParams}} - @{{httpMethod}}("{{path}}") + @{{httpMethod}}("{{path}}") void {{nickname}}( {{#allParams}}{{>libraries/retrofit/queryParams}}{{>libraries/retrofit/pathParams}}{{>libraries/retrofit/headerParams}}{{>libraries/retrofit/bodyParams}}{{>libraries/retrofit/formParams}}, {{/allParams}}Callback<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> cb - ); + ); {{/operation}} } -{{/operations}} \ No newline at end of file +{{/operations}} From ab34dc56979b2acc2ecad697169e6a2ca0ccceee Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 8 Oct 2015 21:21:43 +0800 Subject: [PATCH 174/219] Rebuild Java cilents of the Petstore sample --- .../java/io/swagger/client/api/PetApi.java | 72 ++++++++--------- .../java/io/swagger/client/api/StoreApi.java | 41 ++++------ .../java/io/swagger/client/api/UserApi.java | 63 +++++++-------- .../java/io/swagger/client/model/Order.java | 9 +-- .../java/io/swagger/client/model/Pet.java | 15 ++-- .../java/io/swagger/client/api/PetApi.java | 68 +++++++--------- .../java/io/swagger/client/api/StoreApi.java | 39 ++++----- .../java/io/swagger/client/api/UserApi.java | 61 +++++++------- .../java/io/swagger/client/model/Order.java | 13 +-- .../java/io/swagger/client/model/Pet.java | 19 ++--- .../java/io/swagger/client/api/PetApi.java | 78 +++++++++--------- .../java/io/swagger/client/api/StoreApi.java | 41 ++++------ .../java/io/swagger/client/api/UserApi.java | 67 +++++++-------- .../java/io/swagger/client/model/Order.java | 7 +- .../java/io/swagger/client/model/Pet.java | 13 ++- .../java/io/swagger/client/api/PetApi.java | 81 +++++++++---------- .../java/io/swagger/client/api/StoreApi.java | 40 +++++---- .../java/io/swagger/client/api/UserApi.java | 74 +++++++++-------- .../java/io/swagger/client/model/Order.java | 7 +- .../java/io/swagger/client/model/Pet.java | 13 ++- 20 files changed, 373 insertions(+), 448 deletions(-) diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index ca9111f41764..4f503f934cbd 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -6,18 +6,10 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; -import io.swagger.client.model.*; - -import java.util.*; - import io.swagger.client.model.Pet; import java.io.File; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") public class PetApi { private ApiClient apiClient; @@ -52,9 +44,9 @@ public void updatePet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -99,9 +91,9 @@ public void addPet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -136,9 +128,9 @@ public void addPet (Pet body) throws ApiException { * 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 List + * @return java.util.List */ - public List findPetsByStatus (List status) throws ApiException { + public java.util.List findPetsByStatus (java.util.List status) throws ApiException { Object postBody = null; byte[] postBinaryBody = null; @@ -146,9 +138,9 @@ public List findPetsByStatus (List status) throws ApiException { String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -174,7 +166,7 @@ public List findPetsByStatus (List status) throws ApiException { - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -186,9 +178,9 @@ public List findPetsByStatus (List status) throws ApiException { * 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 List + * @return java.util.List */ - public List findPetsByTags (List tags) throws ApiException { + public java.util.List findPetsByTags (java.util.List tags) throws ApiException { Object postBody = null; byte[] postBinaryBody = null; @@ -196,9 +188,9 @@ public List findPetsByTags (List tags) throws ApiException { String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); @@ -224,7 +216,7 @@ public List findPetsByTags (List tags) throws ApiException { - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -252,9 +244,9 @@ public Pet getPetById (Long petId) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -272,7 +264,7 @@ public Pet getPetById (Long petId) throws ApiException { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - String[] authNames = new String[] { "api_key", "petstore_auth" }; + String[] authNames = new String[] { "petstore_auth", "api_key" }; @@ -308,9 +300,9 @@ public void updatePetWithForm (String petId, String name, String status) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -366,9 +358,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -423,9 +415,9 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index f0628c595c98..4d861dcb5d8b 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -6,18 +6,9 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; -import io.swagger.client.model.*; - -import java.util.*; - -import java.util.Map; import io.swagger.client.model.Order; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") public class StoreApi { private ApiClient apiClient; @@ -41,9 +32,9 @@ public void setApiClient(ApiClient apiClient) { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return java.util.Map */ - public Map getInventory () throws ApiException { + public java.util.Map getInventory () throws ApiException { Object postBody = null; byte[] postBinaryBody = null; @@ -51,9 +42,9 @@ public Map getInventory () throws ApiException { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -77,7 +68,7 @@ public Map getInventory () throws ApiException { - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -99,9 +90,9 @@ public Order placeOrder (Order body) throws ApiException { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -153,9 +144,9 @@ public Order getOrderById (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -207,9 +198,9 @@ public void deleteOrder (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index 3412c565b376..e2e0e90b18d6 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -6,18 +6,9 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; -import io.swagger.client.model.*; - -import java.util.*; - import io.swagger.client.model.User; -import java.util.*; - -import java.io.File; -import java.util.Map; -import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") public class UserApi { private ApiClient apiClient; @@ -52,9 +43,9 @@ public void createUser (User body) throws ApiException { String path = "/user".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -91,7 +82,7 @@ public void createUser (User body) throws ApiException { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List body) throws ApiException { + public void createUsersWithArrayInput (java.util.List body) throws ApiException { Object postBody = body; byte[] postBinaryBody = null; @@ -99,9 +90,9 @@ public void createUsersWithArrayInput (List body) throws ApiException { String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -138,7 +129,7 @@ public void createUsersWithArrayInput (List body) throws ApiException { * @param body List of user object * @return void */ - public void createUsersWithListInput (List body) throws ApiException { + public void createUsersWithListInput (java.util.List body) throws ApiException { Object postBody = body; byte[] postBinaryBody = null; @@ -146,9 +137,9 @@ public void createUsersWithListInput (List body) throws ApiException { String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -194,9 +185,9 @@ public String loginUser (String username, String password) throws ApiException { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); queryParams.addAll(apiClient.parameterToPairs("", "username", username)); @@ -245,9 +236,9 @@ public void logoutUser () throws ApiException { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -298,9 +289,9 @@ public User getUserByName (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -353,9 +344,9 @@ public void updateUser (String username, User body) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -406,9 +397,9 @@ public void deleteUser (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index b51be0c52e03..22320fbb39b2 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -1,7 +1,6 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; -import java.util.Date; @@ -10,13 +9,13 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private java.util.Date shipDate = null; public enum StatusEnum { PLACED("placed"), @@ -79,10 +78,10 @@ public void setQuantity(Integer quantity) { **/ @ApiModelProperty(value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public java.util.Date getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(java.util.Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index aca4848ff988..fc0db631e60f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -3,7 +3,6 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; import io.swagger.client.model.Tag; -import java.util.*; @@ -12,14 +11,14 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-30T16:27:52.437+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") public class Pet { private Long id = null; private Category category = null; private String name = null; - private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); + private java.util.List photoUrls = new java.util.ArrayList(); + private java.util.List tags = new java.util.ArrayList(); public enum StatusEnum { AVAILABLE("available"), @@ -81,10 +80,10 @@ public void setName(String name) { **/ @ApiModelProperty(required = true, value = "") @JsonProperty("photoUrls") - public List getPhotoUrls() { + public java.util.List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { + public void setPhotoUrls(java.util.List photoUrls) { this.photoUrls = photoUrls; } @@ -93,10 +92,10 @@ public void setPhotoUrls(List photoUrls) { **/ @ApiModelProperty(value = "") @JsonProperty("tags") - public List getTags() { + public java.util.List getTags() { return tags; } - public void setTags(List tags) { + public void setTags(java.util.List tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index 26e0f275c8e2..56c0b1e173ce 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -8,16 +8,10 @@ import io.swagger.client.model.*; -import java.util.*; - import io.swagger.client.model.Pet; import java.io.File; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") public class PetApi { private ApiClient apiClient; @@ -51,9 +45,9 @@ public void updatePet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -91,9 +85,9 @@ public void addPet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -122,18 +116,18 @@ public void addPet (Pet body) throws ApiException { * 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 List + * @return java.util.List */ - public List findPetsByStatus (List status) throws ApiException { + public java.util.List findPetsByStatus (java.util.List status) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -156,7 +150,7 @@ public List findPetsByStatus (List status) throws ApiException { String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -165,18 +159,18 @@ public List findPetsByStatus (List status) throws ApiException { * 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 List + * @return java.util.List */ - public List findPetsByTags (List tags) throws ApiException { + public java.util.List findPetsByTags (java.util.List tags) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); @@ -199,7 +193,7 @@ public List findPetsByTags (List tags) throws ApiException { String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -223,9 +217,9 @@ public Pet getPetById (Long petId) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -272,9 +266,9 @@ public void updatePetWithForm (String petId, String name, String status) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -323,9 +317,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -373,9 +367,9 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index c95256c69aae..5f8a9fb13d8e 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -8,16 +8,9 @@ import io.swagger.client.model.*; -import java.util.*; - -import java.util.Map; import io.swagger.client.model.Order; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") public class StoreApi { private ApiClient apiClient; @@ -41,18 +34,18 @@ public void setApiClient(ApiClient apiClient) { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return java.util.Map */ - public Map getInventory () throws ApiException { + public java.util.Map getInventory () throws ApiException { Object postBody = null; // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -73,7 +66,7 @@ public Map getInventory () throws ApiException { String[] authNames = new String[] { "api_key" }; - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -91,9 +84,9 @@ public Order placeOrder (Order body) throws ApiException { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -138,9 +131,9 @@ public Order getOrderById (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -185,9 +178,9 @@ public void deleteOrder (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 26c8d4b035f6..36199161b160 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -8,16 +8,9 @@ import io.swagger.client.model.*; -import java.util.*; - import io.swagger.client.model.User; -import java.util.*; - -import java.io.File; -import java.util.Map; -import java.util.HashMap; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") public class UserApi { private ApiClient apiClient; @@ -51,9 +44,9 @@ public void createUser (User body) throws ApiException { String path = "/user".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -84,16 +77,16 @@ public void createUser (User body) throws ApiException { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (List body) throws ApiException { + public void createUsersWithArrayInput (java.util.List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -124,16 +117,16 @@ public void createUsersWithArrayInput (List body) throws ApiException { * @param body List of user object * @return void */ - public void createUsersWithListInput (List body) throws ApiException { + public void createUsersWithListInput (java.util.List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -172,9 +165,9 @@ public String loginUser (String username, String password) throws ApiException { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); queryParams.addAll(apiClient.parameterToPairs("", "username", username)); @@ -216,9 +209,9 @@ public void logoutUser () throws ApiException { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -262,9 +255,9 @@ public User getUserByName (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -310,9 +303,9 @@ public void updateUser (String username, User body) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); @@ -356,9 +349,9 @@ public void deleteUser (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - List queryParams = new ArrayList(); - Map headerParams = new HashMap(); - Map formParams = new HashMap(); + java.util.List queryParams = new java.util.ArrayList(); + java.util.Map headerParams = new java.util.HashMap(); + java.util.Map formParams = new java.util.HashMap(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 868c59a783d8..5b952459ddeb 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,7 +1,6 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; -import java.util.Date; @@ -10,16 +9,18 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private Date shipDate = null; + private java.util.Date shipDate = null; public enum StatusEnum { - PLACED("placed"), APPROVED("approved"), DELIVERED("delivered"); + PLACED("placed"), + APPROVED("approved"), + DELIVERED("delivered"); private String value; @@ -77,10 +78,10 @@ public void setQuantity(Integer quantity) { **/ @ApiModelProperty(value = "") @JsonProperty("shipDate") - public Date getShipDate() { + public java.util.Date getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(java.util.Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index 2a4a0b6c93d9..1e205686fd45 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -2,7 +2,6 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; @@ -12,17 +11,19 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-11T11:35:51.678+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") public class Pet { private Long id = null; private Category category = null; private String name = null; - private List photoUrls = new ArrayList(); - private List tags = new ArrayList(); + private java.util.List photoUrls = new java.util.ArrayList(); + private java.util.List tags = new java.util.ArrayList(); public enum StatusEnum { - AVAILABLE("available"), PENDING("pending"), SOLD("sold"); + AVAILABLE("available"), + PENDING("pending"), + SOLD("sold"); private String value; @@ -79,10 +80,10 @@ public void setName(String name) { **/ @ApiModelProperty(required = true, value = "") @JsonProperty("photoUrls") - public List getPhotoUrls() { + public java.util.List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { + public void setPhotoUrls(java.util.List photoUrls) { this.photoUrls = photoUrls; } @@ -91,10 +92,10 @@ public void setPhotoUrls(List photoUrls) { **/ @ApiModelProperty(value = "") @JsonProperty("tags") - public List getTags() { + public java.util.List getTags() { return tags; } - public void setTags(List tags) { + public void setTags(java.util.List tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index debe576dc9dc..78bde8330796 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -14,15 +14,9 @@ import java.lang.reflect.Type; -import java.util.*; - import io.swagger.client.model.Pet; import java.io.File; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - public class PetApi { private ApiClient apiClient; @@ -51,11 +45,11 @@ private Call updatePetCall(Pet body) throws ApiException { // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -104,11 +98,11 @@ private Call addPetCall(Pet body) throws ApiException { // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -150,20 +144,20 @@ public Call addPetAsync(Pet body, ApiCallback callback) throws ApiExceptio } /* Build call for findPetsByStatus */ - private Call findPetsByStatusCall(List status) throws ApiException { + private Call findPetsByStatusCall(java.util.List status) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); if (status != null) queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -185,11 +179,11 @@ private Call findPetsByStatusCall(List status) throws ApiException { * 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 List + * @return java.util.List */ - public List findPetsByStatus(List status) throws ApiException { + public java.util.List findPetsByStatus(java.util.List status) throws ApiException { Call call = findPetsByStatusCall(status); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -200,28 +194,28 @@ public List findPetsByStatus(List status) throws ApiException { * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call findPetsByStatusAsync(List status, ApiCallback> callback) throws ApiException { + public Call findPetsByStatusAsync(java.util.List status, ApiCallback> callback) throws ApiException { Call call = findPetsByStatusCall(status); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for findPetsByTags */ - private Call findPetsByTagsCall(List tags) throws ApiException { + private Call findPetsByTagsCall(java.util.List tags) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); if (tags != null) queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -243,11 +237,11 @@ private Call findPetsByTagsCall(List tags) throws ApiException { * 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 List + * @return java.util.List */ - public List findPetsByTags(List tags) throws ApiException { + public java.util.List findPetsByTags(java.util.List tags) throws ApiException { Call call = findPetsByTagsCall(tags); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -258,9 +252,9 @@ public List findPetsByTags(List tags) throws ApiException { * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call findPetsByTagsAsync(List tags, ApiCallback> callback) throws ApiException { + public Call findPetsByTagsAsync(java.util.List tags, ApiCallback> callback) throws ApiException { Call call = findPetsByTagsCall(tags); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } @@ -279,11 +273,11 @@ private Call getPetByIdCall(Long petId) throws ApiException { String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -341,11 +335,11 @@ private Call updatePetWithFormCall(String petId, String name, String status) thr String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); if (name != null) formParams.put("name", name); if (status != null) @@ -408,13 +402,13 @@ private Call deletePetCall(Long petId, String apiKey) throws ApiException { String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); if (apiKey != null) headerParams.put("api_key", apiClient.parameterToString(apiKey)); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -471,11 +465,11 @@ private Call uploadFileCall(Long petId, String additionalMetadata, File file) th String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); if (additionalMetadata != null) formParams.put("additionalMetadata", additionalMetadata); if (file != null) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index a3fb14bb5210..ff7f02ecf562 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -14,15 +14,8 @@ import java.lang.reflect.Type; -import java.util.*; - -import java.util.Map; import io.swagger.client.model.Order; -import java.io.File; -import java.util.Map; -import java.util.HashMap; - public class StoreApi { private ApiClient apiClient; @@ -51,11 +44,11 @@ private Call getInventoryCall() throws ApiException { // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -76,11 +69,11 @@ private Call getInventoryCall() throws ApiException { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return Map + * @return java.util.Map */ - public Map getInventory() throws ApiException { + public java.util.Map getInventory() throws ApiException { Call call = getInventoryCall(); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -90,9 +83,9 @@ public Map getInventory() throws ApiException { * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call getInventoryAsync(ApiCallback> callback) throws ApiException { + public Call getInventoryAsync(ApiCallback> callback) throws ApiException { Call call = getInventoryCall(); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } @@ -105,11 +98,11 @@ private Call placeOrderCall(Order body) throws ApiException { // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -167,11 +160,11 @@ private Call getOrderByIdCall(String orderId) throws ApiException { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -229,11 +222,11 @@ private Call deleteOrderCall(String orderId) throws ApiException { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index ce1bae64a46e..dccd7003b2b7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -14,14 +14,7 @@ import java.lang.reflect.Type; -import java.util.*; - import io.swagger.client.model.User; -import java.util.*; - -import java.io.File; -import java.util.Map; -import java.util.HashMap; public class UserApi { private ApiClient apiClient; @@ -51,11 +44,11 @@ private Call createUserCall(User body) throws ApiException { // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -97,18 +90,18 @@ public Call createUserAsync(User body, ApiCallback callback) throws ApiExc } /* Build call for createUsersWithArrayInput */ - private Call createUsersWithArrayInputCall(List body) throws ApiException { + private Call createUsersWithArrayInputCall(java.util.List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -131,7 +124,7 @@ private Call createUsersWithArrayInputCall(List body) throws ApiException * * @param body List of user object */ - public void createUsersWithArrayInput(List body) throws ApiException { + public void createUsersWithArrayInput(java.util.List body) throws ApiException { Call call = createUsersWithArrayInputCall(body); apiClient.execute(call); } @@ -143,25 +136,25 @@ public void createUsersWithArrayInput(List body) throws ApiException { * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call createUsersWithArrayInputAsync(List body, ApiCallback callback) throws ApiException { + public Call createUsersWithArrayInputAsync(java.util.List body, ApiCallback callback) throws ApiException { Call call = createUsersWithArrayInputCall(body); apiClient.executeAsync(call, callback); return call; } /* Build call for createUsersWithListInput */ - private Call createUsersWithListInputCall(List body) throws ApiException { + private Call createUsersWithListInputCall(java.util.List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -184,7 +177,7 @@ private Call createUsersWithListInputCall(List body) throws ApiException { * * @param body List of user object */ - public void createUsersWithListInput(List body) throws ApiException { + public void createUsersWithListInput(java.util.List body) throws ApiException { Call call = createUsersWithListInputCall(body); apiClient.execute(call); } @@ -196,7 +189,7 @@ public void createUsersWithListInput(List body) throws ApiException { * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call createUsersWithListInputAsync(List body, ApiCallback callback) throws ApiException { + public Call createUsersWithListInputAsync(java.util.List body, ApiCallback callback) throws ApiException { Call call = createUsersWithListInputCall(body); apiClient.executeAsync(call, callback); return call; @@ -210,15 +203,15 @@ private Call loginUserCall(String username, String password) throws ApiException // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); if (username != null) queryParams.addAll(apiClient.parameterToPairs("", "username", username)); if (password != null) queryParams.addAll(apiClient.parameterToPairs("", "password", password)); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -272,11 +265,11 @@ private Call logoutUserCall() throws ApiException { // create path and map variables String path = "/user/logout".replaceAll("\\{format\\}","json"); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -329,11 +322,11 @@ private Call getUserByNameCall(String username) throws ApiException { String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -391,11 +384,11 @@ private Call updateUserCall(String username, User body) throws ApiException { String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -452,11 +445,11 @@ private Call deleteUserCall(String username) throws ApiException { String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - List queryParams = new ArrayList(); + java.util.List queryParams = new java.util.ArrayList(); - Map headerParams = new HashMap(); + java.util.Map headerParams = new java.util.HashMap(); - Map formParams = new HashMap(); + java.util.Map formParams = new java.util.HashMap(); final String[] accepts = { "application/json", "application/xml" diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index df8e77b6fb35..57c9f791e97c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -1,7 +1,6 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; -import java.util.Date; import com.google.gson.annotations.SerializedName; @@ -24,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private java.util.Date shipDate = null; public enum StatusEnum { @@ -93,10 +92,10 @@ public void setQuantity(Integer quantity) { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public java.util.Date getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(java.util.Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index 9ab5457e26ac..4b214d56c01e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -2,7 +2,6 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; import com.google.gson.annotations.SerializedName; @@ -26,10 +25,10 @@ public class Pet { private String name = null; @SerializedName("photoUrls") - private List photoUrls = new ArrayList(); + private java.util.List photoUrls = new java.util.ArrayList(); @SerializedName("tags") - private List tags = new ArrayList(); + private java.util.List tags = new java.util.ArrayList(); public enum StatusEnum { @@ -95,10 +94,10 @@ public void setName(String name) { /** **/ @ApiModelProperty(required = true, value = "") - public List getPhotoUrls() { + public java.util.List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { + public void setPhotoUrls(java.util.List photoUrls) { this.photoUrls = photoUrls; } @@ -106,10 +105,10 @@ public void setPhotoUrls(List photoUrls) { /** **/ @ApiModelProperty(value = "") - public List getTags() { + public java.util.List getTags() { return tags; } - public void setTags(List tags) { + public void setTags(java.util.List tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index cd4dbe866a51..568e17b6cfc0 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -5,7 +5,6 @@ import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; import io.swagger.client.model.Pet; import java.io.File; @@ -20,7 +19,7 @@ public interface PetApi { * @return Void */ - @PUT("/pet") + @PUT("/pet") Void updatePet( @Body Pet body ); @@ -29,14 +28,14 @@ Void updatePet( * Update an existing pet * Async method * @param body Pet object that needs to be added to the store - * @param cb callback method + * @param cb callback method * @return void */ - @PUT("/pet") + @PUT("/pet") void updatePet( @Body Pet body, Callback cb - ); + ); /** * Add a new pet to the store @@ -46,7 +45,7 @@ void updatePet( * @return Void */ - @POST("/pet") + @POST("/pet") Void addPet( @Body Pet body ); @@ -55,66 +54,66 @@ Void addPet( * Add a new pet to the store * Async method * @param body Pet object that needs to be added to the store - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/pet") + @POST("/pet") void addPet( @Body Pet body, Callback cb - ); + ); /** * Finds Pets by status * Sync method * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter - * @return List + * @return java.util.List */ - @GET("/pet/findByStatus") - List findPetsByStatus( - @Query("status") List status + @GET("/pet/findByStatus") + java.util.List findPetsByStatus( + @Query("status") java.util.List status ); /** * Finds Pets by status * Async method * @param status Status values that need to be considered for filter - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/findByStatus") + @GET("/pet/findByStatus") void findPetsByStatus( - @Query("status") List status, Callback> cb - ); + @Query("status") java.util.List status, Callback> cb + ); /** * Finds Pets by tags * Sync method * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by - * @return List + * @return java.util.List */ - @GET("/pet/findByTags") - List findPetsByTags( - @Query("tags") List tags + @GET("/pet/findByTags") + java.util.List findPetsByTags( + @Query("tags") java.util.List tags ); /** * Finds Pets by tags * Async method * @param tags Tags to filter by - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/findByTags") + @GET("/pet/findByTags") void findPetsByTags( - @Query("tags") List tags, Callback> cb - ); + @Query("tags") java.util.List tags, Callback> cb + ); /** * Find pet by ID @@ -124,7 +123,7 @@ void findPetsByTags( * @return Pet */ - @GET("/pet/{petId}") + @GET("/pet/{petId}") Pet getPetById( @Path("petId") Long petId ); @@ -133,14 +132,14 @@ Pet getPetById( * Find pet by ID * Async method * @param petId ID of pet that needs to be fetched - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/pet/{petId}") + @GET("/pet/{petId}") void getPetById( @Path("petId") Long petId, Callback cb - ); + ); /** * Updates a pet in the store with form data @@ -153,7 +152,7 @@ void getPetById( */ @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") Void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status ); @@ -164,15 +163,15 @@ Void updatePetWithForm( * @param petId ID of pet that needs to be updated * @param name Updated name of the pet * @param status Updated status of the pet - * @param cb callback method + * @param cb callback method * @return void */ @FormUrlEncoded - @POST("/pet/{petId}") + @POST("/pet/{petId}") void updatePetWithForm( @Path("petId") String petId, @Field("name") String name, @Field("status") String status, Callback cb - ); + ); /** * Deletes a pet @@ -183,7 +182,7 @@ void updatePetWithForm( * @return Void */ - @DELETE("/pet/{petId}") + @DELETE("/pet/{petId}") Void deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey ); @@ -193,14 +192,14 @@ Void deletePet( * Async method * @param petId Pet id to delete * @param apiKey - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/pet/{petId}") + @DELETE("/pet/{petId}") void deletePet( @Path("petId") Long petId, @Header("api_key") String apiKey, Callback cb - ); + ); /** * uploads an image @@ -213,7 +212,7 @@ void deletePet( */ @Multipart - @POST("/pet/{petId}/uploadImage") + @POST("/pet/{petId}/uploadImage") Void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file ); @@ -224,14 +223,14 @@ Void uploadFile( * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @param cb callback method + * @param cb callback method * @return void */ @Multipart - @POST("/pet/{petId}/uploadImage") + @POST("/pet/{petId}/uploadImage") void uploadFile( @Path("petId") Long petId, @Part("additionalMetadata") String additionalMetadata, @Part("file") TypedFile file, Callback cb - ); + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index 1c0a8291d020..ce9e9456859f 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -5,9 +5,7 @@ import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; -import java.util.Map; import io.swagger.client.model.Order; public interface StoreApi { @@ -16,24 +14,24 @@ public interface StoreApi { * Returns pet inventories by status * Sync method * Returns a map of status codes to quantities - * @return Map + * @return java.util.Map */ - @GET("/store/inventory") - Map getInventory(); + @GET("/store/inventory") + java.util.Map getInventory(); /** * Returns pet inventories by status * Async method - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/store/inventory") + @GET("/store/inventory") void getInventory( - Callback> cb - ); + Callback> cb + ); /** * Place an order for a pet @@ -43,7 +41,7 @@ void getInventory( * @return Order */ - @POST("/store/order") + @POST("/store/order") Order placeOrder( @Body Order body ); @@ -52,14 +50,14 @@ Order placeOrder( * Place an order for a pet * Async method * @param body order placed for purchasing the pet - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/store/order") + @POST("/store/order") void placeOrder( @Body Order body, Callback cb - ); + ); /** * Find purchase order by ID @@ -69,7 +67,7 @@ void placeOrder( * @return Order */ - @GET("/store/order/{orderId}") + @GET("/store/order/{orderId}") Order getOrderById( @Path("orderId") String orderId ); @@ -78,14 +76,14 @@ Order getOrderById( * Find purchase order by ID * Async method * @param orderId ID of pet that needs to be fetched - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/store/order/{orderId}") + @GET("/store/order/{orderId}") void getOrderById( @Path("orderId") String orderId, Callback cb - ); + ); /** * Delete purchase order by ID @@ -95,7 +93,7 @@ void getOrderById( * @return Void */ - @DELETE("/store/order/{orderId}") + @DELETE("/store/order/{orderId}") Void deleteOrder( @Path("orderId") String orderId ); @@ -104,13 +102,13 @@ Void deleteOrder( * Delete purchase order by ID * Async method * @param orderId ID of the order that needs to be deleted - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/store/order/{orderId}") + @DELETE("/store/order/{orderId}") void deleteOrder( @Path("orderId") String orderId, Callback cb - ); + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 162222bc0f1b..57b8f66f4277 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -5,10 +5,8 @@ import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; -import java.util.*; import io.swagger.client.model.User; -import java.util.*; public interface UserApi { @@ -20,7 +18,7 @@ public interface UserApi { * @return Void */ - @POST("/user") + @POST("/user") Void createUser( @Body User body ); @@ -29,14 +27,14 @@ Void createUser( * Create user * Async method * @param body Created user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user") + @POST("/user") void createUser( @Body User body, Callback cb - ); + ); /** * Creates list of users with given input array @@ -46,23 +44,23 @@ void createUser( * @return Void */ - @POST("/user/createWithArray") + @POST("/user/createWithArray") Void createUsersWithArrayInput( - @Body List body + @Body java.util.List body ); /** * Creates list of users with given input array * Async method * @param body List of user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user/createWithArray") + @POST("/user/createWithArray") void createUsersWithArrayInput( - @Body List body, Callback cb - ); + @Body java.util.List body, Callback cb + ); /** * Creates list of users with given input array @@ -72,23 +70,23 @@ void createUsersWithArrayInput( * @return Void */ - @POST("/user/createWithList") + @POST("/user/createWithList") Void createUsersWithListInput( - @Body List body + @Body java.util.List body ); /** * Creates list of users with given input array * Async method * @param body List of user object - * @param cb callback method + * @param cb callback method * @return void */ - @POST("/user/createWithList") + @POST("/user/createWithList") void createUsersWithListInput( - @Body List body, Callback cb - ); + @Body java.util.List body, Callback cb + ); /** * Logs user into the system @@ -99,7 +97,7 @@ void createUsersWithListInput( * @return String */ - @GET("/user/login") + @GET("/user/login") String loginUser( @Query("username") String username, @Query("password") String password ); @@ -109,14 +107,14 @@ String loginUser( * Async method * @param username The user name for login * @param password The password for login in clear text - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/login") + @GET("/user/login") void loginUser( @Query("username") String username, @Query("password") String password, Callback cb - ); + ); /** * Logs out current logged in user session @@ -125,21 +123,21 @@ void loginUser( * @return Void */ - @GET("/user/logout") + @GET("/user/logout") Void logoutUser(); /** * Logs out current logged in user session * Async method - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/logout") + @GET("/user/logout") void logoutUser( Callback cb - ); + ); /** * Get user by user name @@ -149,7 +147,7 @@ void logoutUser( * @return User */ - @GET("/user/{username}") + @GET("/user/{username}") User getUserByName( @Path("username") String username ); @@ -158,14 +156,14 @@ User getUserByName( * Get user by user name * Async method * @param username The name that needs to be fetched. Use user1 for testing. - * @param cb callback method + * @param cb callback method * @return void */ - @GET("/user/{username}") + @GET("/user/{username}") void getUserByName( @Path("username") String username, Callback cb - ); + ); /** * Updated user @@ -176,7 +174,7 @@ void getUserByName( * @return Void */ - @PUT("/user/{username}") + @PUT("/user/{username}") Void updateUser( @Path("username") String username, @Body User body ); @@ -186,14 +184,14 @@ Void updateUser( * Async method * @param username name that need to be deleted * @param body Updated user object - * @param cb callback method + * @param cb callback method * @return void */ - @PUT("/user/{username}") + @PUT("/user/{username}") void updateUser( @Path("username") String username, @Body User body, Callback cb - ); + ); /** * Delete user @@ -203,7 +201,7 @@ void updateUser( * @return Void */ - @DELETE("/user/{username}") + @DELETE("/user/{username}") Void deleteUser( @Path("username") String username ); @@ -212,13 +210,13 @@ Void deleteUser( * Delete user * Async method * @param username The name that needs to be deleted - * @param cb callback method + * @param cb callback method * @return void */ - @DELETE("/user/{username}") + @DELETE("/user/{username}") void deleteUser( @Path("username") String username, Callback cb - ); + ); } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index df8e77b6fb35..57c9f791e97c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -1,7 +1,6 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; -import java.util.Date; import com.google.gson.annotations.SerializedName; @@ -24,7 +23,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private Date shipDate = null; + private java.util.Date shipDate = null; public enum StatusEnum { @@ -93,10 +92,10 @@ public void setQuantity(Integer quantity) { /** **/ @ApiModelProperty(value = "") - public Date getShipDate() { + public java.util.Date getShipDate() { return shipDate; } - public void setShipDate(Date shipDate) { + public void setShipDate(java.util.Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index 9ab5457e26ac..4b214d56c01e 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -2,7 +2,6 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; import com.google.gson.annotations.SerializedName; @@ -26,10 +25,10 @@ public class Pet { private String name = null; @SerializedName("photoUrls") - private List photoUrls = new ArrayList(); + private java.util.List photoUrls = new java.util.ArrayList(); @SerializedName("tags") - private List tags = new ArrayList(); + private java.util.List tags = new java.util.ArrayList(); public enum StatusEnum { @@ -95,10 +94,10 @@ public void setName(String name) { /** **/ @ApiModelProperty(required = true, value = "") - public List getPhotoUrls() { + public java.util.List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { + public void setPhotoUrls(java.util.List photoUrls) { this.photoUrls = photoUrls; } @@ -106,10 +105,10 @@ public void setPhotoUrls(List photoUrls) { /** **/ @ApiModelProperty(value = "") - public List getTags() { + public java.util.List getTags() { return tags; } - public void setTags(List tags) { + public void setTags(java.util.List tags) { this.tags = tags; } From aa0fbada0737839c7e62f8043d59b323be00bc1d Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 9 Oct 2015 22:07:43 +0800 Subject: [PATCH 175/219] Add a "fullJavaUtil" option to Java clients to toggle whether to use full qualified name (with full package prefix) for classes under java.util --- .../io/swagger/codegen/DefaultCodegen.java | 15 +++- .../codegen/languages/JavaClientCodegen.java | 49 +++++++++++- .../src/main/resources/Java/api.mustache | 10 ++- .../Java/libraries/jersey2/api.mustache | 12 +-- .../Java/libraries/okhttp-gson/api.mustache | 15 ++-- .../Java/libraries/retrofit/api.mustache | 6 +- .../java/io/swagger/client/api/PetApi.java | 64 +++++++-------- .../java/io/swagger/client/api/StoreApi.java | 35 ++++---- .../java/io/swagger/client/api/UserApi.java | 57 ++++++------- .../java/io/swagger/client/model/Order.java | 9 ++- .../java/io/swagger/client/model/Pet.java | 15 ++-- .../java/io/swagger/client/api/PetApi.java | 66 ++++++++-------- .../java/io/swagger/client/api/StoreApi.java | 37 ++++----- .../java/io/swagger/client/api/UserApi.java | 59 +++++++------- .../java/io/swagger/client/model/Order.java | 9 ++- .../java/io/swagger/client/model/Pet.java | 15 ++-- .../java/io/swagger/client/api/PetApi.java | 79 +++++++++---------- .../java/io/swagger/client/api/StoreApi.java | 42 +++++----- .../java/io/swagger/client/api/UserApi.java | 68 ++++++++-------- .../java/io/swagger/client/model/Order.java | 7 +- .../java/io/swagger/client/model/Pet.java | 13 +-- .../java/io/swagger/client/api/PetApi.java | 20 ++--- .../java/io/swagger/client/api/StoreApi.java | 11 +-- .../java/io/swagger/client/api/UserApi.java | 13 +-- .../java/io/swagger/client/model/Order.java | 7 +- .../java/io/swagger/client/model/Pet.java | 13 +-- 26 files changed, 412 insertions(+), 334 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 55868c0acaff..b5f544a749b5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -311,14 +311,15 @@ public DefaultCodegen() { ); typeMapping = new HashMap(); - typeMapping.put("array", "java.util.List"); - typeMapping.put("map", "java.util.Map"); + typeMapping.put("array", "List"); + typeMapping.put("map", "Map"); + typeMapping.put("List", "List"); typeMapping.put("boolean", "Boolean"); typeMapping.put("string", "String"); typeMapping.put("int", "Integer"); typeMapping.put("float", "Float"); typeMapping.put("number", "BigDecimal"); - typeMapping.put("DateTime", "java.util.Date"); + typeMapping.put("DateTime", "Date"); typeMapping.put("long", "Long"); typeMapping.put("short", "Short"); typeMapping.put("char", "String"); @@ -336,7 +337,15 @@ public DefaultCodegen() { importMapping.put("BigDecimal", "java.math.BigDecimal"); importMapping.put("UUID", "java.util.UUID"); importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "java.util.Map"); + importMapping.put("HashMap", "java.util.HashMap"); + importMapping.put("Array", "java.util.List"); + importMapping.put("ArrayList", "java.util.ArrayList"); + importMapping.put("List", "java.util.*"); + importMapping.put("Set", "java.util.*"); + importMapping.put("DateTime", "org.joda.time.*"); importMapping.put("LocalDateTime", "org.joda.time.*"); importMapping.put("LocalDate", "org.joda.time.*"); importMapping.put("LocalTime", "org.joda.time.*"); 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 1276c2dde6c5..5d61f1b59324 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 @@ -37,6 +37,8 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String artifactVersion = "1.0.0"; protected String sourceFolder = "src/main/java"; protected String localVariablePrefix = ""; + protected boolean fullJavaUtil = false; + protected String javaUtilPrefix = ""; protected Boolean serializableModel = false; public JavaClientCodegen() { @@ -71,8 +73,8 @@ public JavaClientCodegen() { "Object", "byte[]") ); - instantiationTypes.put("array", "java.util.ArrayList"); - instantiationTypes.put("map", "java.util.HashMap"); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); cliOptions.add(new CliOption(CodegenConstants.INVOKER_PACKAGE, CodegenConstants.INVOKER_PACKAGE_DESC)); cliOptions.add(new CliOption(CodegenConstants.GROUP_ID, CodegenConstants.GROUP_ID_DESC)); @@ -81,6 +83,7 @@ public JavaClientCodegen() { cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); + cliOptions.add(new CliOption("fullJavaUtil", "whether to use full qualified name for classes under java.util (default to false)")); supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); @@ -152,6 +155,32 @@ public void processOpts() { // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); + if (additionalProperties.containsKey("fullJavaUtil")) { + fullJavaUtil = Boolean.valueOf(additionalProperties.get("fullJavaUtil").toString()); + } + if (fullJavaUtil) { + javaUtilPrefix = "java.util."; + } + additionalProperties.put("fullJavaUtil", fullJavaUtil); + additionalProperties.put("javaUtilPrefix", javaUtilPrefix); + + if (fullJavaUtil) { + typeMapping.put("array", "java.util.List"); + typeMapping.put("map", "java.util.Map"); + typeMapping.put("DateTime", "java.util.Date"); + typeMapping.remove("List"); + importMapping.remove("Date"); + importMapping.remove("Map"); + importMapping.remove("HashMap"); + importMapping.remove("Array"); + importMapping.remove("ArrayList"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("DateTime"); + instantiationTypes.put("array", "java.util.ArrayList"); + instantiationTypes.put("map", "java.util.HashMap"); + } + this.sanitizeConfig(); final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); @@ -294,10 +323,22 @@ public String getTypeDeclaration(Property p) { public String toDefaultValue(Property p) { if (p instanceof ArrayProperty) { final ArrayProperty ap = (ArrayProperty) p; - return String.format("new java.util.ArrayList<%s>()", getTypeDeclaration(ap.getItems())); + final String pattern; + if (fullJavaUtil) { + pattern = "new java.util.ArrayList<%s>()"; + } else { + pattern = "new ArrayList<%s>()"; + } + return String.format(pattern, getTypeDeclaration(ap.getItems())); } else if (p instanceof MapProperty) { final MapProperty ap = (MapProperty) p; - return String.format("new java.util.HashMap()", getTypeDeclaration(ap.getAdditionalProperties())); + final String pattern; + if (fullJavaUtil) { + pattern = "new java.util.HashMap()"; + } else { + pattern = "new HashMap()"; + } + return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties())); } return super.toDefaultValue(p); } diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 38ebc1c54abd..08d28ebd51b1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -9,6 +9,10 @@ import {{invokerPackage}}.TypeRef; {{#imports}}import {{import}}; {{/imports}} +{{^fullJavaUtil}} +import java.util.*; +{{/fullJavaUtil}} + {{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -51,9 +55,9 @@ public class {{classname}} { .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - java.util.List {{localVariablePrefix}}queryParams = new java.util.ArrayList(); - java.util.Map {{localVariablePrefix}}headerParams = new java.util.HashMap(); - java.util.Map {{localVariablePrefix}}formParams = new java.util.HashMap(); + {{javaUtilPrefix}}List {{localVariablePrefix}}queryParams = new {{javaUtilPrefix}}ArrayList(); + {{javaUtilPrefix}}Map {{localVariablePrefix}}headerParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map {{localVariablePrefix}}formParams = new {{javaUtilPrefix}}HashMap(); {{#queryParams}} {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache index 532f1ef78cf1..10f2fa2f7446 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/api.mustache @@ -6,11 +6,13 @@ import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; import {{invokerPackage}}.TypeRef; -import {{modelPackage}}.*; - {{#imports}}import {{import}}; {{/imports}} +{{^fullJavaUtil}} +import java.util.*; +{{/fullJavaUtil}} + {{>generatedAnnotation}} {{#operations}} public class {{classname}} { @@ -52,9 +54,9 @@ public class {{classname}} { .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; // query params - java.util.List {{localVariablePrefix}}queryParams = new java.util.ArrayList(); - java.util.Map {{localVariablePrefix}}headerParams = new java.util.HashMap(); - java.util.Map {{localVariablePrefix}}formParams = new java.util.HashMap(); + {{javaUtilPrefix}}List {{localVariablePrefix}}queryParams = new {{javaUtilPrefix}}ArrayList(); + {{javaUtilPrefix}}Map {{localVariablePrefix}}headerParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map {{localVariablePrefix}}formParams = new {{javaUtilPrefix}}HashMap(); {{#queryParams}} {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache index d1f38f0ac358..efb1a14f27d7 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -6,17 +6,18 @@ import {{invokerPackage}}.ApiException; import {{invokerPackage}}.Configuration; import {{invokerPackage}}.Pair; -import {{modelPackage}}.*; - import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; -import java.lang.reflect.Type; - {{#imports}}import {{import}}; {{/imports}} +import java.lang.reflect.Type; +{{^fullJavaUtil}} +import java.util.*; +{{/fullJavaUtil}} + {{#operations}} public class {{classname}} { private ApiClient {{localVariablePrefix}}apiClient; @@ -52,15 +53,15 @@ public class {{classname}} { String {{localVariablePrefix}}path = "{{path}}".replaceAll("\\{format\\}","json"){{#pathParams}} .replaceAll("\\{" + "{{baseName}}" + "\\}", {{localVariablePrefix}}apiClient.escapeString({{{paramName}}}.toString())){{/pathParams}}; - java.util.List {{localVariablePrefix}}queryParams = new java.util.ArrayList();{{#queryParams}} + {{javaUtilPrefix}}List {{localVariablePrefix}}queryParams = new {{javaUtilPrefix}}ArrayList();{{#queryParams}} if ({{paramName}} != null) {{localVariablePrefix}}queryParams.addAll({{localVariablePrefix}}apiClient.parameterToPairs("{{#collectionFormat}}{{{collectionFormat}}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}));{{/queryParams}} - java.util.Map {{localVariablePrefix}}headerParams = new java.util.HashMap();{{#headerParams}} + {{javaUtilPrefix}}Map {{localVariablePrefix}}headerParams = new {{javaUtilPrefix}}HashMap();{{#headerParams}} if ({{paramName}} != null) {{localVariablePrefix}}headerParams.put("{{baseName}}", {{localVariablePrefix}}apiClient.parameterToString({{paramName}}));{{/headerParams}} - java.util.Map {{localVariablePrefix}}formParams = new java.util.HashMap();{{#formParams}} + {{javaUtilPrefix}}Map {{localVariablePrefix}}formParams = new {{javaUtilPrefix}}HashMap();{{#formParams}} if ({{paramName}} != null) {{localVariablePrefix}}formParams.put("{{baseName}}", {{paramName}});{{/formParams}} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index 28d2d29f8d1a..b41e18aff47c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -1,7 +1,5 @@ package {{package}}; -import {{modelPackage}}.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; @@ -9,6 +7,10 @@ import retrofit.mime.*; {{#imports}}import {{import}}; {{/imports}} +{{^fullJavaUtil}} +import java.util.*; +{{/fullJavaUtil}} + {{#operations}} public interface {{classname}} { {{#operation}} diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 4f503f934cbd..8715238ae148 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -9,7 +9,9 @@ import io.swagger.client.model.Pet; import java.io.File; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") +import java.util.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") public class PetApi { private ApiClient apiClient; @@ -44,9 +46,9 @@ public void updatePet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -91,9 +93,9 @@ public void addPet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -128,9 +130,9 @@ public void addPet (Pet body) throws ApiException { * 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 java.util.List + * @return List */ - public java.util.List findPetsByStatus (java.util.List status) throws ApiException { + public List findPetsByStatus (List status) throws ApiException { Object postBody = null; byte[] postBinaryBody = null; @@ -138,9 +140,9 @@ public java.util.List findPetsByStatus (java.util.List status) thro String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -166,7 +168,7 @@ public java.util.List findPetsByStatus (java.util.List status) thro - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -178,9 +180,9 @@ public java.util.List findPetsByStatus (java.util.List status) thro * 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 java.util.List + * @return List */ - public java.util.List findPetsByTags (java.util.List tags) throws ApiException { + public List findPetsByTags (List tags) throws ApiException { Object postBody = null; byte[] postBinaryBody = null; @@ -188,9 +190,9 @@ public java.util.List findPetsByTags (java.util.List tags) throws A String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); @@ -216,7 +218,7 @@ public java.util.List findPetsByTags (java.util.List tags) throws A - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -244,9 +246,9 @@ public Pet getPetById (Long petId) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -300,9 +302,9 @@ public void updatePetWithForm (String petId, String name, String status) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -358,9 +360,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -415,9 +417,9 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java index 4d861dcb5d8b..916b16e17ff1 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/StoreApi.java @@ -6,9 +6,12 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; +import java.util.Map; import io.swagger.client.model.Order; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") +import java.util.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") public class StoreApi { private ApiClient apiClient; @@ -32,9 +35,9 @@ public void setApiClient(ApiClient apiClient) { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return java.util.Map + * @return Map */ - public java.util.Map getInventory () throws ApiException { + public Map getInventory () throws ApiException { Object postBody = null; byte[] postBinaryBody = null; @@ -42,9 +45,9 @@ public java.util.Map getInventory () throws ApiException { String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -68,7 +71,7 @@ public java.util.Map getInventory () throws ApiException { - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, postBinaryBody, headerParams, formParams, accept, contentType, authNames, returnType); @@ -90,9 +93,9 @@ public Order placeOrder (Order body) throws ApiException { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -144,9 +147,9 @@ public Order getOrderById (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -198,9 +201,9 @@ public void deleteOrder (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java index e2e0e90b18d6..80ee07041f76 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/UserApi.java @@ -7,8 +7,11 @@ import io.swagger.client.TypeRef; import io.swagger.client.model.User; +import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") +import java.util.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") public class UserApi { private ApiClient apiClient; @@ -43,9 +46,9 @@ public void createUser (User body) throws ApiException { String path = "/user".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -82,7 +85,7 @@ public void createUser (User body) throws ApiException { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (java.util.List body) throws ApiException { + public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; byte[] postBinaryBody = null; @@ -90,9 +93,9 @@ public void createUsersWithArrayInput (java.util.List body) throws ApiExce String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -129,7 +132,7 @@ public void createUsersWithArrayInput (java.util.List body) throws ApiExce * @param body List of user object * @return void */ - public void createUsersWithListInput (java.util.List body) throws ApiException { + public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; byte[] postBinaryBody = null; @@ -137,9 +140,9 @@ public void createUsersWithListInput (java.util.List body) throws ApiExcep String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -185,9 +188,9 @@ public String loginUser (String username, String password) throws ApiException { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("", "username", username)); @@ -236,9 +239,9 @@ public void logoutUser () throws ApiException { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -289,9 +292,9 @@ public User getUserByName (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -344,9 +347,9 @@ public void updateUser (String username, User body) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -397,9 +400,9 @@ public void deleteUser (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java index 22320fbb39b2..84582f973200 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Order.java @@ -1,6 +1,7 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Date; @@ -9,13 +10,13 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private java.util.Date shipDate = null; + private Date shipDate = null; public enum StatusEnum { PLACED("placed"), @@ -78,10 +79,10 @@ public void setQuantity(Integer quantity) { **/ @ApiModelProperty(value = "") @JsonProperty("shipDate") - public java.util.Date getShipDate() { + public Date getShipDate() { return shipDate; } - public void setShipDate(java.util.Date shipDate) { + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java index fc0db631e60f..3076f4a5be90 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/model/Pet.java @@ -2,6 +2,7 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; +import java.util.*; import io.swagger.client.model.Tag; @@ -11,14 +12,14 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:43.997+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") public class Pet { private Long id = null; private Category category = null; private String name = null; - private java.util.List photoUrls = new java.util.ArrayList(); - private java.util.List tags = new java.util.ArrayList(); + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { AVAILABLE("available"), @@ -80,10 +81,10 @@ public void setName(String name) { **/ @ApiModelProperty(required = true, value = "") @JsonProperty("photoUrls") - public java.util.List getPhotoUrls() { + public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(java.util.List photoUrls) { + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } @@ -92,10 +93,10 @@ public void setPhotoUrls(java.util.List photoUrls) { **/ @ApiModelProperty(value = "") @JsonProperty("tags") - public java.util.List getTags() { + public List getTags() { return tags; } - public void setTags(java.util.List tags) { + public void setTags(List tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index 56c0b1e173ce..b979fd081340 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -6,12 +6,12 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; -import io.swagger.client.model.*; - import io.swagger.client.model.Pet; import java.io.File; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") +import java.util.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") public class PetApi { private ApiClient apiClient; @@ -45,9 +45,9 @@ public void updatePet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -85,9 +85,9 @@ public void addPet (Pet body) throws ApiException { String path = "/pet".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -116,18 +116,18 @@ public void addPet (Pet body) throws ApiException { * 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 java.util.List + * @return List */ - public java.util.List findPetsByStatus (java.util.List status) throws ApiException { + public List findPetsByStatus (List status) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); @@ -150,7 +150,7 @@ public java.util.List findPetsByStatus (java.util.List status) thro String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -159,18 +159,18 @@ public java.util.List findPetsByStatus (java.util.List status) thro * 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 java.util.List + * @return List */ - public java.util.List findPetsByTags (java.util.List tags) throws ApiException { + public List findPetsByTags (List tags) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); @@ -193,7 +193,7 @@ public java.util.List findPetsByTags (java.util.List tags) throws A String[] authNames = new String[] { "petstore_auth" }; - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -217,9 +217,9 @@ public Pet getPetById (Long petId) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -266,9 +266,9 @@ public void updatePetWithForm (String petId, String name, String status) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -317,9 +317,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -367,9 +367,9 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throws .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java index 5f8a9fb13d8e..d011bca14175 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/StoreApi.java @@ -6,11 +6,12 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; -import io.swagger.client.model.*; - +import java.util.Map; import io.swagger.client.model.Order; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") +import java.util.*; + +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") public class StoreApi { private ApiClient apiClient; @@ -34,18 +35,18 @@ public void setApiClient(ApiClient apiClient) { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return java.util.Map + * @return Map */ - public java.util.Map getInventory () throws ApiException { + public Map getInventory () throws ApiException { Object postBody = null; // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -66,7 +67,7 @@ public java.util.Map getInventory () throws ApiException { String[] authNames = new String[] { "api_key" }; - TypeRef returnType = new TypeRef>() {}; + TypeRef returnType = new TypeRef>() {}; return apiClient.invokeAPI(path, "GET", queryParams, postBody, headerParams, formParams, accept, contentType, authNames, returnType); } @@ -84,9 +85,9 @@ public Order placeOrder (Order body) throws ApiException { String path = "/store/order".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -131,9 +132,9 @@ public Order getOrderById (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -178,9 +179,9 @@ public void deleteOrder (String orderId) throws ApiException { .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java index 36199161b160..1c811a06a3b2 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/UserApi.java @@ -6,11 +6,12 @@ import io.swagger.client.Pair; import io.swagger.client.TypeRef; -import io.swagger.client.model.*; - import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") public class UserApi { private ApiClient apiClient; @@ -44,9 +45,9 @@ public void createUser (User body) throws ApiException { String path = "/user".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -77,16 +78,16 @@ public void createUser (User body) throws ApiException { * @param body List of user object * @return void */ - public void createUsersWithArrayInput (java.util.List body) throws ApiException { + public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -117,16 +118,16 @@ public void createUsersWithArrayInput (java.util.List body) throws ApiExce * @param body List of user object * @return void */ - public void createUsersWithListInput (java.util.List body) throws ApiException { + public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -165,9 +166,9 @@ public String loginUser (String username, String password) throws ApiException { String path = "/user/login".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); queryParams.addAll(apiClient.parameterToPairs("", "username", username)); @@ -209,9 +210,9 @@ public void logoutUser () throws ApiException { String path = "/user/logout".replaceAll("\\{format\\}","json"); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -255,9 +256,9 @@ public User getUserByName (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -303,9 +304,9 @@ public void updateUser (String username, User body) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); @@ -349,9 +350,9 @@ public void deleteUser (String username) throws ApiException { .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); // query params - java.util.List queryParams = new java.util.ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); - java.util.Map formParams = new java.util.HashMap(); + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map formParams = new HashMap(); diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java index 5b952459ddeb..2f091e480853 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Order.java @@ -1,6 +1,7 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Date; @@ -9,13 +10,13 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") public class Order { private Long id = null; private Long petId = null; private Integer quantity = null; - private java.util.Date shipDate = null; + private Date shipDate = null; public enum StatusEnum { PLACED("placed"), @@ -78,10 +79,10 @@ public void setQuantity(Integer quantity) { **/ @ApiModelProperty(value = "") @JsonProperty("shipDate") - public java.util.Date getShipDate() { + public Date getShipDate() { return shipDate; } - public void setShipDate(java.util.Date shipDate) { + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java index 1e205686fd45..784478c84f94 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/model/Pet.java @@ -2,6 +2,7 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; +import java.util.*; import io.swagger.client.model.Tag; @@ -11,14 +12,14 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-08T20:57:48.684+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") public class Pet { private Long id = null; private Category category = null; private String name = null; - private java.util.List photoUrls = new java.util.ArrayList(); - private java.util.List tags = new java.util.ArrayList(); + private List photoUrls = new ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { AVAILABLE("available"), @@ -80,10 +81,10 @@ public void setName(String name) { **/ @ApiModelProperty(required = true, value = "") @JsonProperty("photoUrls") - public java.util.List getPhotoUrls() { + public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(java.util.List photoUrls) { + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } @@ -92,10 +93,10 @@ public void setPhotoUrls(java.util.List photoUrls) { **/ @ApiModelProperty(value = "") @JsonProperty("tags") - public java.util.List getTags() { + public List getTags() { return tags; } - public void setTags(java.util.List tags) { + public void setTags(List tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 78bde8330796..596596b935ac 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -6,17 +6,16 @@ import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.model.*; - import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; -import java.lang.reflect.Type; - import io.swagger.client.model.Pet; import java.io.File; +import java.lang.reflect.Type; +import java.util.*; + public class PetApi { private ApiClient apiClient; @@ -45,11 +44,11 @@ private Call updatePetCall(Pet body) throws ApiException { // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -98,11 +97,11 @@ private Call addPetCall(Pet body) throws ApiException { // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -144,20 +143,20 @@ public Call addPetAsync(Pet body, ApiCallback callback) throws ApiExceptio } /* Build call for findPetsByStatus */ - private Call findPetsByStatusCall(java.util.List status) throws ApiException { + private Call findPetsByStatusCall(List status) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); if (status != null) queryParams.addAll(apiClient.parameterToPairs("multi", "status", status)); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -179,11 +178,11 @@ private Call findPetsByStatusCall(java.util.List status) throws ApiExcep * 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 java.util.List + * @return List */ - public java.util.List findPetsByStatus(java.util.List status) throws ApiException { + public List findPetsByStatus(List status) throws ApiException { Call call = findPetsByStatusCall(status); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -194,28 +193,28 @@ public java.util.List findPetsByStatus(java.util.List status) throw * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call findPetsByStatusAsync(java.util.List status, ApiCallback> callback) throws ApiException { + public Call findPetsByStatusAsync(List status, ApiCallback> callback) throws ApiException { Call call = findPetsByStatusCall(status); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } /* Build call for findPetsByTags */ - private Call findPetsByTagsCall(java.util.List tags) throws ApiException { + private Call findPetsByTagsCall(List tags) throws ApiException { Object postBody = null; // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); if (tags != null) queryParams.addAll(apiClient.parameterToPairs("multi", "tags", tags)); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -237,11 +236,11 @@ private Call findPetsByTagsCall(java.util.List tags) throws ApiException * 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 java.util.List + * @return List */ - public java.util.List findPetsByTags(java.util.List tags) throws ApiException { + public List findPetsByTags(List tags) throws ApiException { Call call = findPetsByTagsCall(tags); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -252,9 +251,9 @@ public java.util.List findPetsByTags(java.util.List tags) throws Ap * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call findPetsByTagsAsync(java.util.List tags, ApiCallback> callback) throws ApiException { + public Call findPetsByTagsAsync(List tags, ApiCallback> callback) throws ApiException { Call call = findPetsByTagsCall(tags); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } @@ -273,11 +272,11 @@ private Call getPetByIdCall(Long petId) throws ApiException { String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -335,11 +334,11 @@ private Call updatePetWithFormCall(String petId, String name, String status) thr String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); if (name != null) formParams.put("name", name); if (status != null) @@ -402,13 +401,13 @@ private Call deletePetCall(Long petId, String apiKey) throws ApiException { String path = "/pet/{petId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); if (apiKey != null) headerParams.put("api_key", apiClient.parameterToString(apiKey)); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -465,11 +464,11 @@ private Call uploadFileCall(Long petId, String additionalMetadata, File file) th String path = "/pet/{petId}/uploadImage".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "petId" + "\\}", apiClient.escapeString(petId.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); if (additionalMetadata != null) formParams.put("additionalMetadata", additionalMetadata); if (file != null) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java index ff7f02ecf562..cb780538e18d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/StoreApi.java @@ -6,16 +6,16 @@ import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.model.*; - import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; -import java.lang.reflect.Type; - +import java.util.Map; import io.swagger.client.model.Order; +import java.lang.reflect.Type; +import java.util.*; + public class StoreApi { private ApiClient apiClient; @@ -44,11 +44,11 @@ private Call getInventoryCall() throws ApiException { // create path and map variables String path = "/store/inventory".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -69,11 +69,11 @@ private Call getInventoryCall() throws ApiException { /** * Returns pet inventories by status * Returns a map of status codes to quantities - * @return java.util.Map + * @return Map */ - public java.util.Map getInventory() throws ApiException { + public Map getInventory() throws ApiException { Call call = getInventoryCall(); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); return apiClient.execute(call, returnType); } @@ -83,9 +83,9 @@ public java.util.Map getInventory() throws ApiException { * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call getInventoryAsync(ApiCallback> callback) throws ApiException { + public Call getInventoryAsync(ApiCallback> callback) throws ApiException { Call call = getInventoryCall(); - Type returnType = new TypeToken>(){}.getType(); + Type returnType = new TypeToken>(){}.getType(); apiClient.executeAsync(call, returnType, callback); return call; } @@ -98,11 +98,11 @@ private Call placeOrderCall(Order body) throws ApiException { // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -160,11 +160,11 @@ private Call getOrderByIdCall(String orderId) throws ApiException { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -222,11 +222,11 @@ private Call deleteOrderCall(String orderId) throws ApiException { String path = "/store/order/{orderId}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "orderId" + "\\}", apiClient.escapeString(orderId.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java index dccd7003b2b7..a04470b3b405 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/UserApi.java @@ -6,15 +6,15 @@ import io.swagger.client.Configuration; import io.swagger.client.Pair; -import io.swagger.client.model.*; - import com.google.gson.reflect.TypeToken; import com.squareup.okhttp.Call; -import java.lang.reflect.Type; - import io.swagger.client.model.User; +import java.util.*; + +import java.lang.reflect.Type; +import java.util.*; public class UserApi { private ApiClient apiClient; @@ -44,11 +44,11 @@ private Call createUserCall(User body) throws ApiException { // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -90,18 +90,18 @@ public Call createUserAsync(User body, ApiCallback callback) throws ApiExc } /* Build call for createUsersWithArrayInput */ - private Call createUsersWithArrayInputCall(java.util.List body) throws ApiException { + private Call createUsersWithArrayInputCall(List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -124,7 +124,7 @@ private Call createUsersWithArrayInputCall(java.util.List body) throws Api * * @param body List of user object */ - public void createUsersWithArrayInput(java.util.List body) throws ApiException { + public void createUsersWithArrayInput(List body) throws ApiException { Call call = createUsersWithArrayInputCall(body); apiClient.execute(call); } @@ -136,25 +136,25 @@ public void createUsersWithArrayInput(java.util.List body) throws ApiExcep * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call createUsersWithArrayInputAsync(java.util.List body, ApiCallback callback) throws ApiException { + public Call createUsersWithArrayInputAsync(List body, ApiCallback callback) throws ApiException { Call call = createUsersWithArrayInputCall(body); apiClient.executeAsync(call, callback); return call; } /* Build call for createUsersWithListInput */ - private Call createUsersWithListInputCall(java.util.List body) throws ApiException { + private Call createUsersWithListInputCall(List body) throws ApiException { Object postBody = body; // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -177,7 +177,7 @@ private Call createUsersWithListInputCall(java.util.List body) throws ApiE * * @param body List of user object */ - public void createUsersWithListInput(java.util.List body) throws ApiException { + public void createUsersWithListInput(List body) throws ApiException { Call call = createUsersWithListInputCall(body); apiClient.execute(call); } @@ -189,7 +189,7 @@ public void createUsersWithListInput(java.util.List body) throws ApiExcept * @param callback The callback to be executed when the API call finishes * @return The request call */ - public Call createUsersWithListInputAsync(java.util.List body, ApiCallback callback) throws ApiException { + public Call createUsersWithListInputAsync(List body, ApiCallback callback) throws ApiException { Call call = createUsersWithListInputCall(body); apiClient.executeAsync(call, callback); return call; @@ -203,15 +203,15 @@ private Call loginUserCall(String username, String password) throws ApiException // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); if (username != null) queryParams.addAll(apiClient.parameterToPairs("", "username", username)); if (password != null) queryParams.addAll(apiClient.parameterToPairs("", "password", password)); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -265,11 +265,11 @@ private Call logoutUserCall() throws ApiException { // create path and map variables String path = "/user/logout".replaceAll("\\{format\\}","json"); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -322,11 +322,11 @@ private Call getUserByNameCall(String username) throws ApiException { String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -384,11 +384,11 @@ private Call updateUserCall(String username, User body) throws ApiException { String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" @@ -445,11 +445,11 @@ private Call deleteUserCall(String username) throws ApiException { String path = "/user/{username}".replaceAll("\\{format\\}","json") .replaceAll("\\{" + "username" + "\\}", apiClient.escapeString(username.toString())); - java.util.List queryParams = new java.util.ArrayList(); + List queryParams = new ArrayList(); - java.util.Map headerParams = new java.util.HashMap(); + Map headerParams = new HashMap(); - java.util.Map formParams = new java.util.HashMap(); + Map formParams = new HashMap(); final String[] accepts = { "application/json", "application/xml" diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java index 57c9f791e97c..df8e77b6fb35 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Order.java @@ -1,6 +1,7 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Date; import com.google.gson.annotations.SerializedName; @@ -23,7 +24,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private java.util.Date shipDate = null; + private Date shipDate = null; public enum StatusEnum { @@ -92,10 +93,10 @@ public void setQuantity(Integer quantity) { /** **/ @ApiModelProperty(value = "") - public java.util.Date getShipDate() { + public Date getShipDate() { return shipDate; } - public void setShipDate(java.util.Date shipDate) { + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java index 4b214d56c01e..9ab5457e26ac 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/model/Pet.java @@ -2,6 +2,7 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; +import java.util.*; import io.swagger.client.model.Tag; import com.google.gson.annotations.SerializedName; @@ -25,10 +26,10 @@ public class Pet { private String name = null; @SerializedName("photoUrls") - private java.util.List photoUrls = new java.util.ArrayList(); + private List photoUrls = new ArrayList(); @SerializedName("tags") - private java.util.List tags = new java.util.ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { @@ -94,10 +95,10 @@ public void setName(String name) { /** **/ @ApiModelProperty(required = true, value = "") - public java.util.List getPhotoUrls() { + public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(java.util.List photoUrls) { + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } @@ -105,10 +106,10 @@ public void setPhotoUrls(java.util.List photoUrls) { /** **/ @ApiModelProperty(value = "") - public java.util.List getTags() { + public List getTags() { return tags; } - public void setTags(java.util.List tags) { + public void setTags(List tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 568e17b6cfc0..f6b29f11a2af 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -1,7 +1,5 @@ package io.swagger.client.api; -import io.swagger.client.model.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; @@ -9,6 +7,8 @@ import io.swagger.client.model.Pet; import java.io.File; +import java.util.*; + public interface PetApi { /** @@ -68,12 +68,12 @@ void addPet( * Sync method * Multiple status values can be provided with comma seperated strings * @param status Status values that need to be considered for filter - * @return java.util.List + * @return List */ @GET("/pet/findByStatus") - java.util.List findPetsByStatus( - @Query("status") java.util.List status + List findPetsByStatus( + @Query("status") List status ); /** @@ -86,7 +86,7 @@ java.util.List findPetsByStatus( @GET("/pet/findByStatus") void findPetsByStatus( - @Query("status") java.util.List status, Callback> cb + @Query("status") List status, Callback> cb ); /** @@ -94,12 +94,12 @@ void findPetsByStatus( * Sync method * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. * @param tags Tags to filter by - * @return java.util.List + * @return List */ @GET("/pet/findByTags") - java.util.List findPetsByTags( - @Query("tags") java.util.List tags + List findPetsByTags( + @Query("tags") List tags ); /** @@ -112,7 +112,7 @@ java.util.List findPetsByTags( @GET("/pet/findByTags") void findPetsByTags( - @Query("tags") java.util.List tags, Callback> cb + @Query("tags") List tags, Callback> cb ); /** diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index ce9e9456859f..16819d04a94d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,24 +1,25 @@ package io.swagger.client.api; -import io.swagger.client.model.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; +import java.util.Map; import io.swagger.client.model.Order; +import java.util.*; + public interface StoreApi { /** * Returns pet inventories by status * Sync method * Returns a map of status codes to quantities - * @return java.util.Map + * @return Map */ @GET("/store/inventory") - java.util.Map getInventory(); + Map getInventory(); /** @@ -30,7 +31,7 @@ public interface StoreApi { @GET("/store/inventory") void getInventory( - Callback> cb + Callback> cb ); /** diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index 57b8f66f4277..a5bc4d03477d 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -1,12 +1,13 @@ package io.swagger.client.api; -import io.swagger.client.model.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; import io.swagger.client.model.User; +import java.util.*; + +import java.util.*; public interface UserApi { @@ -46,7 +47,7 @@ void createUser( @POST("/user/createWithArray") Void createUsersWithArrayInput( - @Body java.util.List body + @Body List body ); /** @@ -59,7 +60,7 @@ Void createUsersWithArrayInput( @POST("/user/createWithArray") void createUsersWithArrayInput( - @Body java.util.List body, Callback cb + @Body List body, Callback cb ); /** @@ -72,7 +73,7 @@ void createUsersWithArrayInput( @POST("/user/createWithList") Void createUsersWithListInput( - @Body java.util.List body + @Body List body ); /** @@ -85,7 +86,7 @@ Void createUsersWithListInput( @POST("/user/createWithList") void createUsersWithListInput( - @Body java.util.List body, Callback cb + @Body List body, Callback cb ); /** diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java index 57c9f791e97c..df8e77b6fb35 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Order.java @@ -1,6 +1,7 @@ package io.swagger.client.model; import io.swagger.client.StringUtil; +import java.util.Date; import com.google.gson.annotations.SerializedName; @@ -23,7 +24,7 @@ public class Order { private Integer quantity = null; @SerializedName("shipDate") - private java.util.Date shipDate = null; + private Date shipDate = null; public enum StatusEnum { @@ -92,10 +93,10 @@ public void setQuantity(Integer quantity) { /** **/ @ApiModelProperty(value = "") - public java.util.Date getShipDate() { + public Date getShipDate() { return shipDate; } - public void setShipDate(java.util.Date shipDate) { + public void setShipDate(Date shipDate) { this.shipDate = shipDate; } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java index 4b214d56c01e..9ab5457e26ac 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/model/Pet.java @@ -2,6 +2,7 @@ import io.swagger.client.StringUtil; import io.swagger.client.model.Category; +import java.util.*; import io.swagger.client.model.Tag; import com.google.gson.annotations.SerializedName; @@ -25,10 +26,10 @@ public class Pet { private String name = null; @SerializedName("photoUrls") - private java.util.List photoUrls = new java.util.ArrayList(); + private List photoUrls = new ArrayList(); @SerializedName("tags") - private java.util.List tags = new java.util.ArrayList(); + private List tags = new ArrayList(); public enum StatusEnum { @@ -94,10 +95,10 @@ public void setName(String name) { /** **/ @ApiModelProperty(required = true, value = "") - public java.util.List getPhotoUrls() { + public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(java.util.List photoUrls) { + public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } @@ -105,10 +106,10 @@ public void setPhotoUrls(java.util.List photoUrls) { /** **/ @ApiModelProperty(value = "") - public java.util.List getTags() { + public List getTags() { return tags; } - public void setTags(java.util.List tags) { + public void setTags(List tags) { this.tags = tags; } From c31ed5a30db504cee255f2f4e72d2fb0b9a84190 Mon Sep 17 00:00:00 2001 From: Tomasz Ducin Date: Fri, 9 Oct 2015 18:14:27 +0200 Subject: [PATCH 176/219] maven central badge added --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 42ee357746f2..0577dceb8e8a 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # Swagger Code Generator [![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.png)](https://travis-ci.org/swagger-api/swagger-codegen) +[![Maven Central](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project/badge.svg?style=plastic)](https://maven-badges.herokuapp.com/maven-central/io.swagger/swagger-codegen-project) ## Overview This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. From 9311dcaccbfac1d8beda29a6017be217f462b399 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 18:39:54 +0800 Subject: [PATCH 177/219] update codegen to support global consumes and produces --- .../io/swagger/codegen/CodegenConfig.java | 2 + .../io/swagger/codegen/DefaultCodegen.java | 40 +++++++++++++++---- .../io/swagger/codegen/DefaultGenerator.java | 2 +- .../codegen/languages/SwiftCodegen.java | 6 ++- .../petstore/objc/SwaggerClient.podspec | 8 ++-- .../petstore/objc/SwaggerClient/SWGOrder.h | 2 +- .../petstore/objc/SwaggerClient/SWGOrder.m | 4 +- .../petstore/objc/SwaggerClient/SWGPet.h | 2 +- .../petstore/objc/SwaggerClient/SWGPetApi.m | 2 +- .../petstore/objc/SwaggerClient/SWGUserApi.h | 2 +- .../petstore/objc/SwaggerClient/SWGUserApi.m | 2 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 31 -------------- .../SwaggerClient-php/lib/Api/StoreApi.php | 7 ---- .../lib/ObjectSerializer.php | 2 +- 14 files changed, 52 insertions(+), 60 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 10d7363cc35a..b50147a6ff3e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -67,6 +67,8 @@ public interface CodegenConfig { CodegenModel fromModel(String name, Model model, Map allDefinitions); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); List fromSecurity(Map schemes); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index efc0aa31dbc8..d0185c0ad021 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -861,8 +861,12 @@ private Response findMethodResponse(Map responses) { } return responses.get(code); } - + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + return fromOperation(path, httpMethod, operation, definitions, null); + } + + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); @@ -899,14 +903,25 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.notes = escapeText(operation.getDescription()); op.tags = operation.getTags(); - if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { + List consumes = new ArrayList(); + if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { + // use consumes defined in the operation + consumes = operation.getConsumes(); + } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { + // use consumes defined globally + consumes = swagger.getConsumes(); + LOGGER.debug("Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + } + + // if "consumes" is defined (per operation or using global definition) + if (consumes != null && consumes.size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : operation.getConsumes()) { + for (String key : consumes) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getConsumes().size()) { + if (count < consumes.size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); @@ -917,14 +932,25 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.hasConsumes = true; } - if (operation.getProduces() != null && operation.getProduces().size() > 0) { + List produces = new ArrayList(); + if (operation.getProduces() != null && operation.getProduces().size() > 0) { + // use produces defined in the operation + produces = operation.getProduces(); + } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { + // use produces defined globally + produces = swagger.getProduces(); + LOGGER.debug("Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + } + + // if "produces" is defined (per operation or using global definition) + if (produces != null && produces.size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : operation.getProduces()) { + for (String key : produces) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getProduces().size()) { + if (count < produces.size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index a785f45bdf21..2b61635e0b9b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -470,7 +470,7 @@ public void processOperation(String resourcePath, String httpMethod, Operation o for (String tag : tags) { CodegenOperation co = null; try { - co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); + co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); co.tags = new ArrayList(); co.tags.add(sanitizeTag(tag)); config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 55c3864adb7d..9bb1dfd61d47 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -1,9 +1,11 @@ package io.swagger.codegen.languages; import com.google.common.base.Predicate; + import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import io.swagger.codegen.*; +import io.swagger.models.Swagger; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.parameters.HeaderParameter; @@ -256,7 +258,7 @@ public String toApiName(String name) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { path = normalizePath(path); List parameters = operation.getParameters(); parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { @@ -266,7 +268,7 @@ public boolean apply(@Nullable Parameter parameter) { } })); operation.setParameters(parameters); - return super.fromOperation(path, httpMethod, operation, definitions); + return super.fromOperation(path, httpMethod, operation, definitions, swagger); } private static String normalizePath(String path) { diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 4445bc52ad23..0afb511073c3 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -21,10 +21,10 @@ Pod::Spec.new do |s| s.framework = 'SystemConfiguration' - s.homepage = "" - s.license = "" - s.source = { :git => ".git", :tag => "#{s.version}" } - s.author = { "" => "" } + s.homepage = "https://github.com/swagger-api/swagger-codegen" + s.license = "MIT" + s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } + s.author = { "Swagger" => "apiteam@swagger.io" } s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h index 48a7cf0d6c1f..4b132c57be50 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h @@ -26,6 +26,6 @@ */ @property(nonatomic) NSString* status; -@property(nonatomic) NSNumber* complete; +@property(nonatomic) NSString* count; @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 83fe5741cd7f..8bf5f75c5ad6 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -8,7 +8,7 @@ @implementation SWGOrder */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"count": @"count" }]; } /** @@ -18,7 +18,7 @@ + (JSONKeyMapper *)keyMapper */ + (BOOL)propertyIsOptional:(NSString *)propertyName { - NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; + NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"count"]; if ([optionalProperties containsObject:propertyName]) { return YES; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index 84f10969e5be..e340e0e2b86a 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -7,8 +7,8 @@ * Do not edit the class manually. */ -#import "SWGCategory.h" #import "SWGTag.h" +#import "SWGCategory.h" @protocol SWGPet diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index b890e03570fb..156700c9a769 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -450,7 +450,7 @@ -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth", @"api_key"]; + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index ec41ecd99078..21f314684fd7 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -99,7 +99,7 @@ /// Get user by user name /// /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// /// @return SWGUser* diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 5c3c313b2e23..75cf8d51b0ea 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -470,7 +470,7 @@ -(NSNumber*) logoutUserWithCompletionBlock: /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// @returns SWGUser* /// 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 e8dea97be931..57af48845e18 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -135,9 +135,6 @@ public function updatePet($body=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { @@ -200,9 +197,6 @@ public function addPet($body=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { @@ -264,9 +258,6 @@ public function findPetsByStatus($status=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { @@ -340,9 +331,6 @@ public function findPetsByTags($tags=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { @@ -424,16 +412,6 @@ public function getPetById($pet_id) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (isset($apiKey)) { - $headerParams['api_key'] = $apiKey; - } - - - // make the API Call try { @@ -523,9 +501,6 @@ public function updatePetWithForm($pet_id, $name=null, $status=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { @@ -599,9 +574,6 @@ public function deletePet($pet_id, $api_key=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { @@ -679,9 +651,6 @@ public function uploadFile($pet_id, $additional_metadata=null, $file=null) $httpBody = $formParams; // for HTTP post (form) } - - //TODO support oauth - // make the API Call try { 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 b64b52d22252..1b0f9558695c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -130,13 +130,6 @@ public function getInventory() $httpBody = $formParams; // for HTTP post (form) } - $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); - if (isset($apiKey)) { - $headerParams['api_key'] = $apiKey; - } - - - // make the API Call try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index efdc1c896ab4..0d281b9d1fa3 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -193,7 +193,7 @@ public function deserialize($data, $class, $httpHeader=null) $deserialized = $values; } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { + } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { From 5144c54895c04a0c58a5d25521721507c36bc2fd Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 22:47:24 +0800 Subject: [PATCH 178/219] add test case for global consumes and produces --- .../io/swagger/codegen/DefaultCodegen.java | 26 ++++++---- .../java/io/swagger/codegen/CodegenTest.java | 48 +++++++++++++++++++ 2 files changed, 66 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index d0185c0ad021..558f22bc0a09 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -902,15 +902,21 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.summary = escapeText(operation.getSummary()); op.notes = escapeText(operation.getDescription()); op.tags = operation.getTags(); + op.hasConsumes = false; + op.hasProduces = false; List consumes = new ArrayList(); - if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { - // use consumes defined in the operation - consumes = operation.getConsumes(); + if (operation.getConsumes() != null) { + if (operation.getConsumes().size() > 0) { + // use consumes defined in the operation + consumes = operation.getConsumes(); + } else { + // empty list, do nothing to override global setting + } } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { // use consumes defined globally consumes = swagger.getConsumes(); - LOGGER.debug("Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); } // if "consumes" is defined (per operation or using global definition) @@ -933,13 +939,17 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation } List produces = new ArrayList(); - if (operation.getProduces() != null && operation.getProduces().size() > 0) { - // use produces defined in the operation - produces = operation.getProduces(); + if (operation.getProduces() != null) { + if (operation.getProduces().size() > 0) { + // use produces defined in the operation + produces = operation.getProduces(); + } else { + // empty list, do nothing to override global setting + } } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { // use produces defined globally produces = swagger.getProduces(); - LOGGER.debug("Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); } // if "produces" is defined (per operation or using global definition) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index ee70b427bfdf..68ebb349e6cf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -139,4 +139,52 @@ public void binaryDataTest() { Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.responses.get(0).isBinary); } + + @Test(description = "use operation consumes and producus") + public void localConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/localConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 1); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); + } + + @Test(description = "use spec consumes and producus") + public void globalConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/globalConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 1); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); + } + + @Test(description = "use spec consumes and producus (reset in operation with empty array)") + public void localResetConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/localResetConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertNotNull(op); + Assert.assertFalse(op.hasConsumes); + Assert.assertNull(op.consumes); + Assert.assertFalse(op.hasProduces); + Assert.assertNull(op.produces); + + } } From 64fd94262f1b36a98e60328b4453290e4a370bb1 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 22:54:13 +0800 Subject: [PATCH 179/219] add globalConsumesAndProduces.json --- .../2_0/globalConsumesAndProduces.json | 149 ++++++++++++++++++ 1 file changed, 149 insertions(+) create mode 100644 modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json new file mode 100644 index 000000000000..221d00b6dad9 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json @@ -0,0 +1,149 @@ +{ + "swagger": "2.0", + "info": { + "description": "Spec for testing global consumes and produces", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "consumes": ["application/global_consumes"], + "produces": ["application/global_produces"], + "schemes": [ + "http" + ], + "paths": { + "/tests/localConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with local consumes and produces", + "description": "", + "operationId": "localConsumesAndProduces", + "produces": [ + "application/json" + ], + "consumes": [ + "application/json" + ], + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + }, + "post": { + "tags": [ + "tests" + ], + "summary": "Operation with global consumes and produces", + "description": "", + "operationId": "globalConsumesAndProduces", + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "/tests/globalConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with global consumes and produces", + "description": "", + "operationId": "globalConsumesAndProduces", + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "/tests/localResetConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with local consumes and produces set to empty (reset)", + "description": "", + "operationId": "localResetConsumesAndProduces", + "parameters": [ + ], + "consumes": [], + "produces": [], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + } + + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + }, + "definitions": { + "CustomModel": { + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "example": "doggie" + } + } + } + } +} \ No newline at end of file From 6cc5a32d4013cd405aa83cfd377302273e3cbbbd Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 23:09:41 +0800 Subject: [PATCH 180/219] update objc sample --- .../petstore/objc/SwaggerClient/SWGApiClient.m | 15 ++++++++++----- .../objc/SwaggerClient/SWGConfiguration.m | 7 ------- .../petstore/objc/SwaggerClient/SWGOrder.h | 2 +- .../petstore/objc/SwaggerClient/SWGOrder.m | 4 ++-- .../petstore/objc/SwaggerClient/SWGPetApi.m | 16 ++++++++-------- .../petstore/objc/SwaggerClient/SWGStoreApi.m | 2 +- samples/client/petstore/ruby/lib/petstore.rb | 2 +- .../petstore/ruby/lib/petstore/api/pet_api.rb | 16 ++++++++-------- .../petstore/ruby/lib/petstore/api/store_api.rb | 2 +- .../petstore/ruby/lib/petstore/api/user_api.rb | 2 +- .../petstore/ruby/lib/petstore/api_client.rb | 2 -- .../petstore/ruby/lib/petstore/configuration.rb | 7 ------- 12 files changed, 33 insertions(+), 44 deletions(-) diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index fc3c79078625..dcd33575fc6f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -311,9 +311,10 @@ - (id) deserialize:(id) data class:(NSString *) class { range:NSMakeRange(0, [class length])]; if (match) { + NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; } @@ -332,9 +333,10 @@ - (id) deserialize:(id) data class:(NSString *) class { range:NSMakeRange(0, [class length])]; if (match) { + NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; }]; @@ -352,9 +354,10 @@ - (id) deserialize:(id) data class:(NSString *) class { range:NSMakeRange(0, [class length])]; if (match) { + NSDictionary *dataDict = data; NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; }]; @@ -728,7 +731,8 @@ - (id) sanitizeForSerialization:(id) object { return [object ISO8601String]; } else if ([object isKindOfClass:[NSArray class]]) { - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + NSArray *objectArray = object; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if (obj) { [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; @@ -737,7 +741,8 @@ - (id) sanitizeForSerialization:(id) object { return sanitizedObjs; } else if ([object isKindOfClass:[NSDictionary class]]) { - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + NSDictionary *objectDict = object; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (obj) { [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 16ce311c59ed..3f1f926b3312 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -107,13 +107,6 @@ - (NSDictionary *) apiKeyPrefix { - (NSDictionary *) authSettings { return @{ - @"api_key": - @{ - @"type": @"api_key", - @"in": @"header", - @"key": @"api_key", - @"value": [self getApiKeyWithPrefix:@"api_key"] - }, }; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h index 4b132c57be50..48a7cf0d6c1f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.h @@ -26,6 +26,6 @@ */ @property(nonatomic) NSString* status; -@property(nonatomic) NSString* count; +@property(nonatomic) NSNumber* complete; @end diff --git a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m index 8bf5f75c5ad6..83fe5741cd7f 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGOrder.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGOrder.m @@ -8,7 +8,7 @@ @implementation SWGOrder */ + (JSONKeyMapper *)keyMapper { - return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"count": @"count" }]; + return [[JSONKeyMapper alloc] initWithDictionary:@{ @"id": @"_id", @"petId": @"petId", @"quantity": @"quantity", @"shipDate": @"shipDate", @"status": @"status", @"complete": @"complete" }]; } /** @@ -18,7 +18,7 @@ + (JSONKeyMapper *)keyMapper */ + (BOOL)propertyIsOptional:(NSString *)propertyName { - NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"count"]; + NSArray *optionalProperties = @[@"_id", @"petId", @"quantity", @"shipDate", @"status", @"complete"]; if ([optionalProperties containsObject:propertyName]) { return YES; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 156700c9a769..64ff58e31e6b 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -118,7 +118,7 @@ -(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -196,7 +196,7 @@ -(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -280,7 +280,7 @@ -(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray* /* NSString */) stat NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -364,7 +364,7 @@ -(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray* /* NSString */) tags NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -450,7 +450,7 @@ -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -542,7 +542,7 @@ -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -646,7 +646,7 @@ -(NSNumber*) deletePetWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -738,7 +738,7 @@ -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; // Authentication setting - NSArray *authSettings = @[@"petstore_auth"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 5fdf86b43aff..8450022164ce 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -115,7 +115,7 @@ -(NSNumber*) getInventoryWithCompletionBlock: NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key"]; + NSArray *authSettings = @[]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index c13e99f29fc4..61640d687ac7 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -14,8 +14,8 @@ # APIs require 'petstore/api/user_api' -require 'petstore/api/store_api' require 'petstore/api/pet_api' +require 'petstore/api/store_api' module Petstore class << self diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index a9d30a00147c..bb1b66c19a40 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -42,7 +42,7 @@ def update_pet(opts = {}) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = ['petstore_auth'] + auth_names = [] @api_client.call_api(:PUT, path, :header_params => header_params, :query_params => query_params, @@ -89,7 +89,7 @@ def add_pet(opts = {}) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = ['petstore_auth'] + auth_names = [] @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, @@ -137,7 +137,7 @@ def find_pets_by_status(opts = {}) post_body = nil - auth_names = ['petstore_auth'] + auth_names = [] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, @@ -186,7 +186,7 @@ def find_pets_by_tags(opts = {}) post_body = nil - auth_names = ['petstore_auth'] + auth_names = [] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, @@ -237,7 +237,7 @@ def get_pet_by_id(pet_id, opts = {}) post_body = nil - auth_names = ['petstore_auth', 'api_key'] + auth_names = [] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, @@ -292,7 +292,7 @@ def update_pet_with_form(pet_id, opts = {}) post_body = nil - auth_names = ['petstore_auth'] + auth_names = [] @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, @@ -344,7 +344,7 @@ def delete_pet(pet_id, opts = {}) post_body = nil - auth_names = ['petstore_auth'] + auth_names = [] @api_client.call_api(:DELETE, path, :header_params => header_params, :query_params => query_params, @@ -398,7 +398,7 @@ def upload_file(pet_id, opts = {}) post_body = nil - auth_names = ['petstore_auth'] + auth_names = [] @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index 235ff1c41060..b33aa87a505b 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -41,7 +41,7 @@ def get_inventory(opts = {}) post_body = nil - auth_names = ['api_key'] + auth_names = [] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index f4672e2a3585..7f546330f3aa 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -248,7 +248,7 @@ def logout_user(opts = {}) # Get user by user name # - # @param username The name that needs to be fetched. Use user1 for testing. + # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] def get_user_by_name(username, opts = {}) diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 4f747bcd6a11..77e9c4487183 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -62,8 +62,6 @@ def build_request(http_method, path, opts = {}) form_params = opts[:form_params] || {} - update_params_for_auth! header_params, query_params, opts[:auth_names] - req_opts = { :method => http_method, diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 008be48ee4da..5e333ee79efe 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -160,13 +160,6 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { - 'api_key' => - { - type: 'api_key', - in: 'header', - key: 'api_key', - value: api_key_with_prefix('api_key') - }, } end end From 9ecb2e92ae83e05eac75552ae3844faf056f335a Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 23:13:26 +0800 Subject: [PATCH 181/219] restore sample files for objc, php and ruby --- .../petstore/objc/SwaggerClient.podspec | 8 ++--- .../objc/SwaggerClient/SWGApiClient.m | 15 +++------ .../objc/SwaggerClient/SWGConfiguration.m | 7 +++++ .../petstore/objc/SwaggerClient/SWGPet.h | 2 +- .../petstore/objc/SwaggerClient/SWGPetApi.m | 16 +++++----- .../petstore/objc/SwaggerClient/SWGStoreApi.m | 2 +- .../petstore/objc/SwaggerClient/SWGUserApi.h | 2 +- .../petstore/objc/SwaggerClient/SWGUserApi.m | 2 +- .../php/SwaggerClient-php/lib/Api/PetApi.php | 31 +++++++++++++++++++ .../SwaggerClient-php/lib/Api/StoreApi.php | 7 +++++ .../lib/ObjectSerializer.php | 2 +- samples/client/petstore/ruby/lib/petstore.rb | 2 +- .../petstore/ruby/lib/petstore/api/pet_api.rb | 16 +++++----- .../ruby/lib/petstore/api/store_api.rb | 2 +- .../ruby/lib/petstore/api/user_api.rb | 2 +- .../petstore/ruby/lib/petstore/api_client.rb | 2 ++ .../ruby/lib/petstore/configuration.rb | 7 +++++ 17 files changed, 87 insertions(+), 38 deletions(-) diff --git a/samples/client/petstore/objc/SwaggerClient.podspec b/samples/client/petstore/objc/SwaggerClient.podspec index 0afb511073c3..4445bc52ad23 100644 --- a/samples/client/petstore/objc/SwaggerClient.podspec +++ b/samples/client/petstore/objc/SwaggerClient.podspec @@ -21,10 +21,10 @@ Pod::Spec.new do |s| s.framework = 'SystemConfiguration' - s.homepage = "https://github.com/swagger-api/swagger-codegen" - s.license = "MIT" - s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } - s.author = { "Swagger" => "apiteam@swagger.io" } + s.homepage = "" + s.license = "" + s.source = { :git => ".git", :tag => "#{s.version}" } + s.author = { "" => "" } s.source_files = 'SwaggerClient/**/*' s.public_header_files = 'SwaggerClient/**/*.h' diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index dcd33575fc6f..fc3c79078625 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -311,10 +311,9 @@ - (id) deserialize:(id) data class:(NSString *) class { range:NSMakeRange(0, [class length])]; if (match) { - NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; } @@ -333,10 +332,9 @@ - (id) deserialize:(id) data class:(NSString *) class { range:NSMakeRange(0, [class length])]; if (match) { - NSArray *dataArray = data; innerType = [class substringWithRange:[match rangeAtIndex:1]]; - resultArray = [NSMutableArray arrayWithCapacity:[dataArray count]]; + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { [resultArray addObject:[self deserialize:obj class:innerType]]; }]; @@ -354,10 +352,9 @@ - (id) deserialize:(id) data class:(NSString *) class { range:NSMakeRange(0, [class length])]; if (match) { - NSDictionary *dataDict = data; NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; - resultDict = [NSMutableDictionary dictionaryWithCapacity:[dataDict count]]; + resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; }]; @@ -731,8 +728,7 @@ - (id) sanitizeForSerialization:(id) object { return [object ISO8601String]; } else if ([object isKindOfClass:[NSArray class]]) { - NSArray *objectArray = object; - NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[objectArray count]]; + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { if (obj) { [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; @@ -741,8 +737,7 @@ - (id) sanitizeForSerialization:(id) object { return sanitizedObjs; } else if ([object isKindOfClass:[NSDictionary class]]) { - NSDictionary *objectDict = object; - NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[objectDict count]]; + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { if (obj) { [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m index 3f1f926b3312..16ce311c59ed 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGConfiguration.m @@ -107,6 +107,13 @@ - (NSDictionary *) apiKeyPrefix { - (NSDictionary *) authSettings { return @{ + @"api_key": + @{ + @"type": @"api_key", + @"in": @"header", + @"key": @"api_key", + @"value": [self getApiKeyWithPrefix:@"api_key"] + }, }; } diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPet.h b/samples/client/petstore/objc/SwaggerClient/SWGPet.h index e340e0e2b86a..84f10969e5be 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPet.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGPet.h @@ -7,8 +7,8 @@ * Do not edit the class manually. */ -#import "SWGTag.h" #import "SWGCategory.h" +#import "SWGTag.h" @protocol SWGPet diff --git a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m index 64ff58e31e6b..b890e03570fb 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGPetApi.m @@ -118,7 +118,7 @@ -(NSNumber*) updatePetWithCompletionBlock: (SWGPet*) body NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -196,7 +196,7 @@ -(NSNumber*) addPetWithCompletionBlock: (SWGPet*) body NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -280,7 +280,7 @@ -(NSNumber*) findPetsByStatusWithCompletionBlock: (NSArray* /* NSString */) stat NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -364,7 +364,7 @@ -(NSNumber*) findPetsByTagsWithCompletionBlock: (NSArray* /* NSString */) tags NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -450,7 +450,7 @@ -(NSNumber*) getPetByIdWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -542,7 +542,7 @@ -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -646,7 +646,7 @@ -(NSNumber*) deletePetWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -738,7 +738,7 @@ -(NSNumber*) uploadFileWithCompletionBlock: (NSNumber*) petId NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m index 8450022164ce..5fdf86b43aff 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGStoreApi.m @@ -115,7 +115,7 @@ -(NSNumber*) getInventoryWithCompletionBlock: NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[]; + NSArray *authSettings = @[@"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h index 21f314684fd7..ec41ecd99078 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.h @@ -99,7 +99,7 @@ /// Get user by user name /// /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// /// @return SWGUser* diff --git a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m index 75cf8d51b0ea..5c3c313b2e23 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGUserApi.m @@ -470,7 +470,7 @@ -(NSNumber*) logoutUserWithCompletionBlock: /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// /// @returns SWGUser* /// 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 57af48845e18..e8dea97be931 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -135,6 +135,9 @@ public function updatePet($body=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { @@ -197,6 +200,9 @@ public function addPet($body=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { @@ -258,6 +264,9 @@ public function findPetsByStatus($status=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { @@ -331,6 +340,9 @@ public function findPetsByTags($tags=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { @@ -412,6 +424,16 @@ public function getPetById($pet_id) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + // make the API Call try { @@ -501,6 +523,9 @@ public function updatePetWithForm($pet_id, $name=null, $status=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { @@ -574,6 +599,9 @@ public function deletePet($pet_id, $api_key=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { @@ -651,6 +679,9 @@ public function uploadFile($pet_id, $additional_metadata=null, $file=null) $httpBody = $formParams; // for HTTP post (form) } + + //TODO support oauth + // make the API Call try { 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 1b0f9558695c..b64b52d22252 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -130,6 +130,13 @@ public function getInventory() $httpBody = $formParams; // for HTTP post (form) } + $apiKey = $this->apiClient->getApiKeyWithPrefix('api_key'); + if (isset($apiKey)) { + $headerParams['api_key'] = $apiKey; + } + + + // make the API Call try { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 0d281b9d1fa3..efdc1c896ab4 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -193,7 +193,7 @@ public function deserialize($data, $class, $httpHeader=null) $deserialized = $values; } elseif ($class === '\DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('integer', 'int', 'void', 'number', 'object', 'double', 'float', 'byte', 'DateTime', 'string', 'mixed', 'boolean', 'bool'))) { + } elseif (in_array($class, array('void', 'bool', 'string', 'double', 'byte', 'mixed', 'integer', 'float', 'int', 'DateTime', 'number', 'boolean', 'object'))) { settype($data, $class); $deserialized = $data; } elseif ($class === '\SplFileObject') { diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 61640d687ac7..c13e99f29fc4 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -14,8 +14,8 @@ # APIs require 'petstore/api/user_api' -require 'petstore/api/pet_api' require 'petstore/api/store_api' +require 'petstore/api/pet_api' module Petstore class << self diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index bb1b66c19a40..a9d30a00147c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -42,7 +42,7 @@ def update_pet(opts = {}) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = [] + auth_names = ['petstore_auth'] @api_client.call_api(:PUT, path, :header_params => header_params, :query_params => query_params, @@ -89,7 +89,7 @@ def add_pet(opts = {}) post_body = @api_client.object_to_http_body(opts[:'body']) - auth_names = [] + auth_names = ['petstore_auth'] @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, @@ -137,7 +137,7 @@ def find_pets_by_status(opts = {}) post_body = nil - auth_names = [] + auth_names = ['petstore_auth'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, @@ -186,7 +186,7 @@ def find_pets_by_tags(opts = {}) post_body = nil - auth_names = [] + auth_names = ['petstore_auth'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, @@ -237,7 +237,7 @@ def get_pet_by_id(pet_id, opts = {}) post_body = nil - auth_names = [] + auth_names = ['petstore_auth', 'api_key'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, @@ -292,7 +292,7 @@ def update_pet_with_form(pet_id, opts = {}) post_body = nil - auth_names = [] + auth_names = ['petstore_auth'] @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, @@ -344,7 +344,7 @@ def delete_pet(pet_id, opts = {}) post_body = nil - auth_names = [] + auth_names = ['petstore_auth'] @api_client.call_api(:DELETE, path, :header_params => header_params, :query_params => query_params, @@ -398,7 +398,7 @@ def upload_file(pet_id, opts = {}) post_body = nil - auth_names = [] + auth_names = ['petstore_auth'] @api_client.call_api(:POST, path, :header_params => header_params, :query_params => query_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index b33aa87a505b..235ff1c41060 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -41,7 +41,7 @@ def get_inventory(opts = {}) post_body = nil - auth_names = [] + auth_names = ['api_key'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 7f546330f3aa..f4672e2a3585 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -248,7 +248,7 @@ def logout_user(opts = {}) # Get user by user name # - # @param username The name that needs to be fetched. Use user1 for testing. + # @param username The name that needs to be fetched. Use user1 for testing. # @param [Hash] opts the optional parameters # @return [User] def get_user_by_name(username, opts = {}) diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index 77e9c4487183..4f747bcd6a11 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -62,6 +62,8 @@ def build_request(http_method, path, opts = {}) form_params = opts[:form_params] || {} + update_params_for_auth! header_params, query_params, opts[:auth_names] + req_opts = { :method => http_method, diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 5e333ee79efe..008be48ee4da 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -160,6 +160,13 @@ def basic_auth_token # Returns Auth Settings hash for api client. def auth_settings { + 'api_key' => + { + type: 'api_key', + in: 'header', + key: 'api_key', + value: api_key_with_prefix('api_key') + }, } end end From 5cd01af35059c4424040aa5c558e2f58dbdaaa31 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 23:22:42 +0800 Subject: [PATCH 182/219] fix typo in test cases --- .../src/test/java/io/swagger/codegen/CodegenTest.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index 68ebb349e6cf..0fa8953e7bf5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -140,7 +140,7 @@ public void binaryDataTest() { Assert.assertTrue(op.responses.get(0).isBinary); } - @Test(description = "use operation consumes and producus") + @Test(description = "use operation consumes and produces") public void localConsumesAndProducesTest() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); @@ -156,7 +156,7 @@ public void localConsumesAndProducesTest() { Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); } - @Test(description = "use spec consumes and producus") + @Test(description = "use spec consumes and produces") public void globalConsumesAndProducesTest() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); @@ -172,7 +172,7 @@ public void globalConsumesAndProducesTest() { Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); } - @Test(description = "use spec consumes and producus (reset in operation with empty array)") + @Test(description = "use operation consumes and produces (reset in operation with empty array)") public void localResetConsumesAndProducesTest() { final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); final DefaultCodegen codegen = new DefaultCodegen(); From 00517a1ad3a5f98e513064f9186197b5628b6b57 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 10 Oct 2015 23:27:21 +0800 Subject: [PATCH 183/219] remove unused operation in test json file --- .../2_0/globalConsumesAndProduces.json | 23 ++----------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json index 221d00b6dad9..520218ed707e 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json +++ b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json @@ -46,26 +46,7 @@ } } } - }, - "post": { - "tags": [ - "tests" - ], - "summary": "Operation with global consumes and produces", - "description": "", - "operationId": "globalConsumesAndProduces", - "parameters": [ - ], - "responses": { - "200": { - "description": "successful operation. Returning a simple int.", - "schema": { - "type": "integer", - "format": "int64" - } - } - } - } + } }, "/tests/globalConsumesAndProduces": { "get": { @@ -146,4 +127,4 @@ } } } -} \ No newline at end of file +} From 6fd54d52858142071c5fd5c77e1524aa147a2848 Mon Sep 17 00:00:00 2001 From: Eran Stiller Date: Mon, 12 Oct 2015 08:51:00 +0300 Subject: [PATCH 184/219] Fix bug in handling 204 responses --- .../src/main/resources/android-java/apiInvoker.mustache | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index ac24335df186..b5f0ae7a6623 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -365,8 +365,10 @@ public class ApiInvoker { int code = response.getStatusLine().getStatusCode(); String responseString = null; - if(code == 204) + if(code == 204) { responseString = ""; + return responseString; + } else if(code >= 200 && code < 300) { if(response.getEntity() != null) { HttpEntity resEntity = response.getEntity(); From 15f5eae2a80da4c658b466da04d11d5d51532cee Mon Sep 17 00:00:00 2001 From: Eran Stiller Date: Mon, 12 Oct 2015 08:51:48 +0300 Subject: [PATCH 185/219] Regenerate Android-Java sample --- .../client/petstore/android-java/build.gradle | 6 ++ .../java/io/swagger/client/ApiInvoker.java | 4 +- .../main/java/io/swagger/client/JsonUtil.java | 32 +++++---- .../java/io/swagger/client/api/PetApi.java | 42 +++++++++--- .../java/io/swagger/client/api/StoreApi.java | 10 ++- .../java/io/swagger/client/api/UserApi.java | 35 +++++++++- .../io/swagger/client/model/ApiResponse.java | 68 +++++++++++++++++++ .../io/swagger/client/model/Category.java | 4 ++ .../java/io/swagger/client/model/Order.java | 4 ++ .../java/io/swagger/client/model/Pet.java | 10 ++- .../java/io/swagger/client/model/Tag.java | 4 ++ .../java/io/swagger/client/model/User.java | 4 ++ 12 files changed, 196 insertions(+), 27 deletions(-) create mode 100644 samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index 417503cb51ea..c5f4edf79cb0 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -1,6 +1,8 @@ + group = 'io.swagger' project.version = '1.0.0' + buildscript { repositories { jcenter() @@ -21,8 +23,10 @@ allprojects { apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + android { compileSdkVersion 22 buildToolsVersion '22.0.0' @@ -81,6 +85,7 @@ afterEvaluate { } } + task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' @@ -89,3 +94,4 @@ task sourcesJar(type: Jar) { artifacts { archives sourcesJar } + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index eabb47e818d4..aa786ff5b31d 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -365,8 +365,10 @@ else if ("PATCH".equals(method)) { int code = response.getStatusLine().getStatusCode(); String responseString = null; - if(code == 204) + if(code == 204) { responseString = ""; + return responseString; + } else if(code >= 200 && code < 300) { if(response.getEntity() != null) { HttpEntity resEntity = response.getEntity(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java index 5aa10d3ea825..93a59d71b5e7 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java @@ -35,6 +35,10 @@ public static T deserializeToObject(String jsonString, Class cls){ public static Type getListTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); + if ("Order".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + if ("User".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } @@ -43,16 +47,16 @@ public static Type getListTypeForDeserialization(Class cls) { return new TypeToken>(){}.getType(); } - if ("Pet".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); - } - if ("Tag".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } - if ("Order".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("Pet".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("ApiResponse".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } return new TypeToken>(){}.getType(); @@ -61,6 +65,10 @@ public static Type getListTypeForDeserialization(Class cls) { public static Type getTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); + if ("Order".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + if ("User".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } @@ -69,16 +77,16 @@ public static Type getTypeForDeserialization(Class cls) { return new TypeToken(){}.getType(); } - if ("Pet".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - if ("Tag".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } - if ("Order".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); + if ("Pet".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("ApiResponse".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); } return new TypeToken(){}.getType(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java index f6b6403a3424..5a607ba393fb 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java @@ -10,6 +10,8 @@ import io.swagger.client.model.Pet; import java.io.File; +import io.swagger.client.model.ApiResponse; + import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -18,6 +20,7 @@ import java.util.HashMap; import java.io.File; + public class PetApi { String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); @@ -48,6 +51,11 @@ public String getBasePath() { public void updatePet (Pet body) throws ApiException { Object postBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); + } + // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -102,6 +110,11 @@ public void updatePet (Pet body) throws ApiException { public void addPet (Pet body) throws ApiException { Object postBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); + } + // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -156,6 +169,11 @@ public void addPet (Pet body) throws ApiException { public List findPetsByStatus (List status) throws ApiException { Object postBody = null; + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); + } + // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); @@ -168,7 +186,7 @@ public List findPetsByStatus (List status) throws ApiException { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToPairs("multi", "status", status)); + queryParams.addAll(ApiInvoker.parameterToPairs("csv", "status", status)); @@ -212,6 +230,11 @@ public List findPetsByStatus (List status) throws ApiException { public List findPetsByTags (List tags) throws ApiException { Object postBody = null; + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); + } + // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); @@ -224,7 +247,7 @@ public List findPetsByTags (List tags) throws ApiException { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToPairs("multi", "tags", tags)); + queryParams.addAll(ApiInvoker.parameterToPairs("csv", "tags", tags)); @@ -261,8 +284,8 @@ public List findPetsByTags (List tags) throws ApiException { /** * 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 a single pet + * @param petId ID of pet to return * @return Pet */ public Pet getPetById (Long petId) throws ApiException { @@ -326,7 +349,7 @@ public Pet getPetById (Long petId) throws ApiException { * @param status Updated status of the pet * @return void */ - public void updatePetWithForm (String petId, String name, String status) throws ApiException { + public void updatePetWithForm (Long petId, String name, String status) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -457,9 +480,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @return void + * @return ApiResponse */ - public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + public ApiResponse uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -512,10 +535,10 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throw try { String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return ; + return (ApiResponse) ApiInvoker.deserialize(response, "", ApiResponse.class); } else { - return ; + return null; } } catch (ApiException ex) { throw ex; @@ -523,3 +546,4 @@ public void uploadFile (Long petId, String additionalMetadata, File file) throw } } + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java index 49a3ac4aa9a1..b89a0ddbd473 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java @@ -11,6 +11,7 @@ import java.util.Map; import io.swagger.client.model.Order; + import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -18,6 +19,7 @@ import java.util.HashMap; import java.io.File; + public class StoreApi { String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); @@ -101,6 +103,11 @@ public Map getInventory () throws ApiException { public Order placeOrder (Order body) throws ApiException { Object postBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); + } + // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -152,7 +159,7 @@ public Order placeOrder (Order body) throws ApiException { * @param orderId ID of pet that needs to be fetched * @return Order */ - public Order getOrderById (String orderId) throws ApiException { + public Order getOrderById (Long orderId) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set @@ -265,3 +272,4 @@ public void deleteOrder (String orderId) throws ApiException { } } + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java index a16a745c7f8a..6703b54f7581 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java @@ -11,6 +11,7 @@ import io.swagger.client.model.User; import java.util.*; + import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -18,6 +19,7 @@ import java.util.HashMap; import java.io.File; + public class UserApi { String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); @@ -48,6 +50,11 @@ public String getBasePath() { public void createUser (User body) throws ApiException { Object postBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); + } + // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); @@ -102,6 +109,11 @@ public void createUser (User body) throws ApiException { public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); + } + // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); @@ -156,6 +168,11 @@ public void createUsersWithArrayInput (List body) throws ApiException { public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); + } + // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); @@ -211,6 +228,16 @@ public void createUsersWithListInput (List body) throws ApiException { public String loginUser (String username, String password) throws ApiException { Object postBody = null; + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); + } + // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); @@ -316,7 +343,7 @@ public void logoutUser () throws ApiException { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ public User getUserByName (String username) throws ApiException { @@ -387,6 +414,11 @@ public void updateUser (String username, User body) throws ApiException { throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); } + // verify the required parameter 'body' is set + if (body == null) { + throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); + } + // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); @@ -492,3 +524,4 @@ public void deleteUser (String username) throws ApiException { } } + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java new file mode 100644 index 000000000000..6dd0a9c2fc21 --- /dev/null +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java @@ -0,0 +1,68 @@ +package io.swagger.client.model; + + + +import io.swagger.annotations.*; +import com.google.gson.annotations.SerializedName; + + + +@ApiModel(description = "") +public class ApiResponse { + + @SerializedName("code") + private Integer code = null; + @SerializedName("type") + private String type = null; + @SerializedName("message") + private String message = null; + + + /** + **/ + @ApiModelProperty(value = "") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + + /** + **/ + @ApiModelProperty(value = "") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + + /** + **/ + @ApiModelProperty(value = "") + 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/android-java/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java index 44c71e8a6208..98e5c25c80f9 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java @@ -1,10 +1,12 @@ package io.swagger.client.model; + import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; + @ApiModel(description = "") public class Category { @@ -48,3 +50,5 @@ public String toString() { return sb.toString(); } } + + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java index f3f42db615c5..4ef664deba2d 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java @@ -2,10 +2,12 @@ import java.util.Date; + import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; + @ApiModel(description = "") public class Order { @@ -109,3 +111,5 @@ public String toString() { return sb.toString(); } } + + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index 90a840e6e422..cf7eb877b2ab 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,13 +1,15 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import io.swagger.client.model.Tag; import java.util.*; +import io.swagger.client.model.Tag; + import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; + @ApiModel(description = "") public class Pet { @@ -18,9 +20,9 @@ public class Pet { @SerializedName("name") private String name = null; @SerializedName("photoUrls") - private List photoUrls = new ArrayList() ; + private List photoUrls = null; @SerializedName("tags") - private List tags = new ArrayList() ; + private List tags = null; public enum StatusEnum { available, pending, sold, }; @@ -111,3 +113,5 @@ public String toString() { return sb.toString(); } } + + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java index 7c9651b1ba8e..e87a002a1447 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java @@ -1,10 +1,12 @@ package io.swagger.client.model; + import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; + @ApiModel(description = "") public class Tag { @@ -48,3 +50,5 @@ public String toString() { return sb.toString(); } } + + diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java index dc022697eb0f..fabdab0b4e37 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java @@ -1,10 +1,12 @@ package io.swagger.client.model; + import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; + @ApiModel(description = "") public class User { @@ -133,3 +135,5 @@ public String toString() { return sb.toString(); } } + + From 1fb2a97497a15c6b61de66ba3e721a2810e038d7 Mon Sep 17 00:00:00 2001 From: Eran Stiller Date: Mon, 12 Oct 2015 09:22:36 +0300 Subject: [PATCH 186/219] Revert "Regenerate Android-Java sample" This reverts commit 15f5eae2a80da4c658b466da04d11d5d51532cee. --- .../client/petstore/android-java/build.gradle | 6 -- .../java/io/swagger/client/ApiInvoker.java | 4 +- .../main/java/io/swagger/client/JsonUtil.java | 32 ++++----- .../java/io/swagger/client/api/PetApi.java | 42 +++--------- .../java/io/swagger/client/api/StoreApi.java | 10 +-- .../java/io/swagger/client/api/UserApi.java | 35 +--------- .../io/swagger/client/model/ApiResponse.java | 68 ------------------- .../io/swagger/client/model/Category.java | 4 -- .../java/io/swagger/client/model/Order.java | 4 -- .../java/io/swagger/client/model/Pet.java | 10 +-- .../java/io/swagger/client/model/Tag.java | 4 -- .../java/io/swagger/client/model/User.java | 4 -- 12 files changed, 27 insertions(+), 196 deletions(-) delete mode 100644 samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index c5f4edf79cb0..417503cb51ea 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -1,8 +1,6 @@ - group = 'io.swagger' project.version = '1.0.0' - buildscript { repositories { jcenter() @@ -23,10 +21,8 @@ allprojects { apply plugin: 'com.android.library' - apply plugin: 'com.github.dcendents.android-maven' - android { compileSdkVersion 22 buildToolsVersion '22.0.0' @@ -85,7 +81,6 @@ afterEvaluate { } } - task sourcesJar(type: Jar) { from android.sourceSets.main.java.srcDirs classifier = 'sources' @@ -94,4 +89,3 @@ task sourcesJar(type: Jar) { artifacts { archives sourcesJar } - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index aa786ff5b31d..eabb47e818d4 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -365,10 +365,8 @@ else if ("PATCH".equals(method)) { int code = response.getStatusLine().getStatusCode(); String responseString = null; - if(code == 204) { + if(code == 204) responseString = ""; - return responseString; - } else if(code >= 200 && code < 300) { if(response.getEntity() != null) { HttpEntity resEntity = response.getEntity(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java index 93a59d71b5e7..5aa10d3ea825 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/JsonUtil.java @@ -35,10 +35,6 @@ public static T deserializeToObject(String jsonString, Class cls){ public static Type getListTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); - if ("Order".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); - } - if ("User".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } @@ -47,16 +43,16 @@ public static Type getListTypeForDeserialization(Class cls) { return new TypeToken>(){}.getType(); } - if ("Tag".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); - } - if ("Pet".equalsIgnoreCase(className)) { return new TypeToken>(){}.getType(); } - if ("ApiResponse".equalsIgnoreCase(className)) { - return new TypeToken>(){}.getType(); + if ("Tag".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); + } + + if ("Order".equalsIgnoreCase(className)) { + return new TypeToken>(){}.getType(); } return new TypeToken>(){}.getType(); @@ -65,10 +61,6 @@ public static Type getListTypeForDeserialization(Class cls) { public static Type getTypeForDeserialization(Class cls) { String className = cls.getSimpleName(); - if ("Order".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - if ("User".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } @@ -77,16 +69,16 @@ public static Type getTypeForDeserialization(Class cls) { return new TypeToken(){}.getType(); } - if ("Tag".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); - } - if ("Pet".equalsIgnoreCase(className)) { return new TypeToken(){}.getType(); } - if ("ApiResponse".equalsIgnoreCase(className)) { - return new TypeToken(){}.getType(); + if ("Tag".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); + } + + if ("Order".equalsIgnoreCase(className)) { + return new TypeToken(){}.getType(); } return new TypeToken(){}.getType(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java index 5a607ba393fb..f6b6403a3424 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java @@ -10,8 +10,6 @@ import io.swagger.client.model.Pet; import java.io.File; -import io.swagger.client.model.ApiResponse; - import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -20,7 +18,6 @@ import java.util.HashMap; import java.io.File; - public class PetApi { String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); @@ -51,11 +48,6 @@ public String getBasePath() { public void updatePet (Pet body) throws ApiException { Object postBody = body; - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updatePet"); - } - // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -110,11 +102,6 @@ public void updatePet (Pet body) throws ApiException { public void addPet (Pet body) throws ApiException { Object postBody = body; - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling addPet"); - } - // create path and map variables String path = "/pet".replaceAll("\\{format\\}","json"); @@ -169,11 +156,6 @@ public void addPet (Pet body) throws ApiException { public List findPetsByStatus (List status) throws ApiException { Object postBody = null; - // verify the required parameter 'status' is set - if (status == null) { - throw new ApiException(400, "Missing the required parameter 'status' when calling findPetsByStatus"); - } - // create path and map variables String path = "/pet/findByStatus".replaceAll("\\{format\\}","json"); @@ -186,7 +168,7 @@ public List findPetsByStatus (List status) throws ApiException { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToPairs("csv", "status", status)); + queryParams.addAll(ApiInvoker.parameterToPairs("multi", "status", status)); @@ -230,11 +212,6 @@ public List findPetsByStatus (List status) throws ApiException { public List findPetsByTags (List tags) throws ApiException { Object postBody = null; - // verify the required parameter 'tags' is set - if (tags == null) { - throw new ApiException(400, "Missing the required parameter 'tags' when calling findPetsByTags"); - } - // create path and map variables String path = "/pet/findByTags".replaceAll("\\{format\\}","json"); @@ -247,7 +224,7 @@ public List findPetsByTags (List tags) throws ApiException { Map formParams = new HashMap(); - queryParams.addAll(ApiInvoker.parameterToPairs("csv", "tags", tags)); + queryParams.addAll(ApiInvoker.parameterToPairs("multi", "tags", tags)); @@ -284,8 +261,8 @@ public List findPetsByTags (List tags) throws ApiException { /** * Find pet by ID - * Returns a single pet - * @param petId ID of pet to return + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * @param petId ID of pet that needs to be fetched * @return Pet */ public Pet getPetById (Long petId) throws ApiException { @@ -349,7 +326,7 @@ public Pet getPetById (Long petId) throws ApiException { * @param status Updated status of the pet * @return void */ - public void updatePetWithForm (Long petId, String name, String status) throws ApiException { + public void updatePetWithForm (String petId, String name, String status) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -480,9 +457,9 @@ public void deletePet (Long petId, String apiKey) throws ApiException { * @param petId ID of pet to update * @param additionalMetadata Additional data to pass to server * @param file file to upload - * @return ApiResponse + * @return void */ - public ApiResponse uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { + public void uploadFile (Long petId, String additionalMetadata, File file) throws ApiException { Object postBody = null; // verify the required parameter 'petId' is set @@ -535,10 +512,10 @@ public ApiResponse uploadFile (Long petId, String additionalMetadata, File file try { String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); if(response != null){ - return (ApiResponse) ApiInvoker.deserialize(response, "", ApiResponse.class); + return ; } else { - return null; + return ; } } catch (ApiException ex) { throw ex; @@ -546,4 +523,3 @@ public ApiResponse uploadFile (Long petId, String additionalMetadata, File file } } - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java index b89a0ddbd473..49a3ac4aa9a1 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/StoreApi.java @@ -11,7 +11,6 @@ import java.util.Map; import io.swagger.client.model.Order; - import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -19,7 +18,6 @@ import java.util.HashMap; import java.io.File; - public class StoreApi { String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); @@ -103,11 +101,6 @@ public Map getInventory () throws ApiException { public Order placeOrder (Order body) throws ApiException { Object postBody = body; - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling placeOrder"); - } - // create path and map variables String path = "/store/order".replaceAll("\\{format\\}","json"); @@ -159,7 +152,7 @@ public Order placeOrder (Order body) throws ApiException { * @param orderId ID of pet that needs to be fetched * @return Order */ - public Order getOrderById (Long orderId) throws ApiException { + public Order getOrderById (String orderId) throws ApiException { Object postBody = null; // verify the required parameter 'orderId' is set @@ -272,4 +265,3 @@ public void deleteOrder (String orderId) throws ApiException { } } - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java index 6703b54f7581..a16a745c7f8a 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/UserApi.java @@ -11,7 +11,6 @@ import io.swagger.client.model.User; import java.util.*; - import org.apache.http.HttpEntity; import org.apache.http.entity.mime.MultipartEntityBuilder; @@ -19,7 +18,6 @@ import java.util.HashMap; import java.io.File; - public class UserApi { String basePath = "http://petstore.swagger.io/v2"; ApiInvoker apiInvoker = ApiInvoker.getInstance(); @@ -50,11 +48,6 @@ public String getBasePath() { public void createUser (User body) throws ApiException { Object postBody = body; - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUser"); - } - // create path and map variables String path = "/user".replaceAll("\\{format\\}","json"); @@ -109,11 +102,6 @@ public void createUser (User body) throws ApiException { public void createUsersWithArrayInput (List body) throws ApiException { Object postBody = body; - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithArrayInput"); - } - // create path and map variables String path = "/user/createWithArray".replaceAll("\\{format\\}","json"); @@ -168,11 +156,6 @@ public void createUsersWithArrayInput (List body) throws ApiException { public void createUsersWithListInput (List body) throws ApiException { Object postBody = body; - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling createUsersWithListInput"); - } - // create path and map variables String path = "/user/createWithList".replaceAll("\\{format\\}","json"); @@ -228,16 +211,6 @@ public void createUsersWithListInput (List body) throws ApiException { public String loginUser (String username, String password) throws ApiException { Object postBody = null; - // verify the required parameter 'username' is set - if (username == null) { - throw new ApiException(400, "Missing the required parameter 'username' when calling loginUser"); - } - - // verify the required parameter 'password' is set - if (password == null) { - throw new ApiException(400, "Missing the required parameter 'password' when calling loginUser"); - } - // create path and map variables String path = "/user/login".replaceAll("\\{format\\}","json"); @@ -343,7 +316,7 @@ public void logoutUser () throws ApiException { /** * Get user by user name * - * @param username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. * @return User */ public User getUserByName (String username) throws ApiException { @@ -414,11 +387,6 @@ public void updateUser (String username, User body) throws ApiException { throw new ApiException(400, "Missing the required parameter 'username' when calling updateUser"); } - // verify the required parameter 'body' is set - if (body == null) { - throw new ApiException(400, "Missing the required parameter 'body' when calling updateUser"); - } - // create path and map variables String path = "/user/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}", apiInvoker.escapeString(username.toString())); @@ -524,4 +492,3 @@ public void deleteUser (String username) throws ApiException { } } - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java deleted file mode 100644 index 6dd0a9c2fc21..000000000000 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/ApiResponse.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.swagger.client.model; - - - -import io.swagger.annotations.*; -import com.google.gson.annotations.SerializedName; - - - -@ApiModel(description = "") -public class ApiResponse { - - @SerializedName("code") - private Integer code = null; - @SerializedName("type") - private String type = null; - @SerializedName("message") - private String message = null; - - - /** - **/ - @ApiModelProperty(value = "") - public Integer getCode() { - return code; - } - public void setCode(Integer code) { - this.code = code; - } - - - /** - **/ - @ApiModelProperty(value = "") - public String getType() { - return type; - } - public void setType(String type) { - this.type = type; - } - - - /** - **/ - @ApiModelProperty(value = "") - 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/android-java/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java index 98e5c25c80f9..44c71e8a6208 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Category.java @@ -1,12 +1,10 @@ package io.swagger.client.model; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") public class Category { @@ -50,5 +48,3 @@ public String toString() { return sb.toString(); } } - - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java index 4ef664deba2d..f3f42db615c5 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Order.java @@ -2,12 +2,10 @@ import java.util.Date; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") public class Order { @@ -111,5 +109,3 @@ public String toString() { return sb.toString(); } } - - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java index cf7eb877b2ab..90a840e6e422 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Pet.java @@ -1,15 +1,13 @@ package io.swagger.client.model; import io.swagger.client.model.Category; -import java.util.*; import io.swagger.client.model.Tag; - +import java.util.*; import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") public class Pet { @@ -20,9 +18,9 @@ public class Pet { @SerializedName("name") private String name = null; @SerializedName("photoUrls") - private List photoUrls = null; + private List photoUrls = new ArrayList() ; @SerializedName("tags") - private List tags = null; + private List tags = new ArrayList() ; public enum StatusEnum { available, pending, sold, }; @@ -113,5 +111,3 @@ public String toString() { return sb.toString(); } } - - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java index e87a002a1447..7c9651b1ba8e 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/Tag.java @@ -1,12 +1,10 @@ package io.swagger.client.model; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") public class Tag { @@ -50,5 +48,3 @@ public String toString() { return sb.toString(); } } - - diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java index fabdab0b4e37..dc022697eb0f 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/model/User.java @@ -1,12 +1,10 @@ package io.swagger.client.model; - import io.swagger.annotations.*; import com.google.gson.annotations.SerializedName; - @ApiModel(description = "") public class User { @@ -135,5 +133,3 @@ public String toString() { return sb.toString(); } } - - From 748460488aa6477f406cb3e5d15eb9334ba34192 Mon Sep 17 00:00:00 2001 From: Eran Stiller Date: Mon, 12 Oct 2015 09:25:24 +0300 Subject: [PATCH 187/219] Regenerate only the ApiInvoker.java file in the sample --- .../src/main/java/io/swagger/client/ApiInvoker.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index eabb47e818d4..aa786ff5b31d 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -365,8 +365,10 @@ else if ("PATCH".equals(method)) { int code = response.getStatusLine().getStatusCode(); String responseString = null; - if(code == 204) + if(code == 204) { responseString = ""; + return responseString; + } else if(code >= 200 && code < 300) { if(response.getEntity() != null) { HttpEntity resEntity = response.getEntity(); From e562b0ae34f7161ca4fb629cb22b5e2967d16dfd Mon Sep 17 00:00:00 2001 From: Eran Stiller Date: Mon, 12 Oct 2015 09:52:20 +0300 Subject: [PATCH 188/219] Fix indentation --- .../src/main/resources/android-java/apiInvoker.mustache | 4 ++-- .../src/main/java/io/swagger/client/ApiInvoker.java | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache index b5f0ae7a6623..1f6d77a071ce 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/apiInvoker.mustache @@ -367,8 +367,8 @@ public class ApiInvoker { String responseString = null; if(code == 204) { responseString = ""; - return responseString; - } + return responseString; + } else if(code >= 200 && code < 300) { if(response.getEntity() != null) { HttpEntity resEntity = response.getEntity(); diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java index aa786ff5b31d..5eddeb6b9e96 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/ApiInvoker.java @@ -367,8 +367,8 @@ else if ("PATCH".equals(method)) { String responseString = null; if(code == 204) { responseString = ""; - return responseString; - } + return responseString; + } else if(code >= 200 && code < 300) { if(response.getEntity() != null) { HttpEntity resEntity = response.getEntity(); From 43b3acf550a06e98c12990e8929bcc4a3e57dfc7 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 12 Oct 2015 16:33:11 +0800 Subject: [PATCH 189/219] Remove duplicate fields from sub-classes of the Java codegen Closes #1308 --- .../codegen/languages/JavaInflectorServerCodegen.java | 6 ++---- .../swagger/codegen/languages/JaxRSServerCodegen.java | 6 ++---- .../codegen/languages/SpringMVCServerCodegen.java | 10 ++-------- 3 files changed, 6 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java index 56dbdd0e48b8..d678515f4cbb 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaInflectorServerCodegen.java @@ -22,10 +22,6 @@ import java.util.Map; public class JavaInflectorServerCodegen extends JavaClientCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.handler"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-inflector-server"; - protected String artifactVersion = "1.0.0"; protected String title = "Swagger Inflector"; public JavaInflectorServerCodegen() { @@ -35,6 +31,8 @@ public JavaInflectorServerCodegen() { modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); templateDir = "JavaInflector"; + invokerPackage = "io.swagger.handler"; + artifactId = "swagger-inflector-server"; apiPackage = System.getProperty("swagger.codegen.inflector.apipackage", "io.swagger.handler"); modelPackage = System.getProperty("swagger.codegen.inflector.modelpackage", "io.swagger.model"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java index eb0f6be03e9d..883b08d8dfa2 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JaxRSServerCodegen.java @@ -16,16 +16,14 @@ import java.util.Map; public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.api"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-jaxrs-server"; - protected String artifactVersion = "1.0.0"; protected String title = "Swagger Server"; public JaxRSServerCodegen() { super.processOpts(); sourceFolder = "src/gen/java"; + invokerPackage = "io.swagger.api"; + artifactId = "swagger-jaxrs-server"; outputFolder = System.getProperty("swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS"); modelTemplateFiles.put("model.mustache", ".java"); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java index 6bd64b0e4f68..30d10073268f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SpringMVCServerCodegen.java @@ -15,13 +15,7 @@ import java.util.Iterator; public class SpringMVCServerCodegen extends JavaClientCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.api"; - protected String groupId = "io.swagger"; - protected String artifactId = "swagger-spring-mvc-server"; - protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; protected String title = "Petstore Server"; - protected String configPackage = ""; public SpringMVCServerCodegen() { @@ -33,7 +27,8 @@ public SpringMVCServerCodegen() { apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; configPackage = "io.swagger.configuration"; - + invokerPackage = "io.swagger.api"; + artifactId = "swagger-spring-mvc-server"; additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); additionalProperties.put(CodegenConstants.GROUP_ID, groupId); @@ -201,4 +196,3 @@ public Map postProcessModels(Map objs) { return objs; } } - From 6ce09ee77924cae5c77c341b266ad93623988069 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 12 Oct 2015 17:34:07 +0800 Subject: [PATCH 190/219] Update config option --- README.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/README.md b/README.md index 0577dceb8e8a..7b130b4b8ab7 100644 --- a/README.md +++ b/README.md @@ -276,6 +276,9 @@ CONFIG OPTIONS apiPackage package for generated api classes + sortParamsByRequiredFlag + Sort method arguments to place required parameters before optional parameters. Default: true + invokerPackage root package for generated code @@ -291,6 +294,12 @@ CONFIG OPTIONS sourceFolder source folder for generated code + localVariablePrefix + prefix for generated code members and local variables + + serializableModel + boolean - toggle "implements Serializable" for generated models + library library template (sub-template) to use: - HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2 From 5ed52b3e1d2b04d3d55a3f18280dabee9f7215c3 Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 12 Oct 2015 16:16:38 +0200 Subject: [PATCH 191/219] add gradle files with android support --- .../codegen/languages/JavaClientCodegen.java | 5 +- .../main/resources/Java/build.gradle.mustache | 107 ++++++++++++++++++ .../resources/Java/gradle.properties.mustache | 2 + .../libraries/jersey2/build.gradle.mustache | 107 ++++++++++++++++++ .../okhttp-gson/build.gradle.mustache | 102 +++++++++++++---- .../libraries/retrofit/build.gradle.mustache | 103 +++++++++++++++++ .../resources/Java/settings.gradle.mustache | 1 + .../client/petstore/java/default/build.gradle | 107 ++++++++++++++++++ .../petstore/java/default/gradle.properties | 2 + .../petstore/java/default/settings.gradle | 1 + .../client/petstore/java/jersey2/build.gradle | 107 ++++++++++++++++++ .../petstore/java/jersey2/gradle.properties | 2 + .../petstore/java/jersey2/settings.gradle | 1 + .../petstore/java/okhttp-gson/build.gradle | 102 +++++++++++++---- .../java/okhttp-gson/gradle.properties | 2 + .../petstore/java/okhttp-gson/settings.gradle | 1 + .../petstore/java/retrofit/build.gradle | 103 +++++++++++++++++ .../petstore/java/retrofit/gradle.properties | 2 + .../petstore/java/retrofit/settings.gradle | 1 + 19 files changed, 818 insertions(+), 40 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/gradle.properties.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/settings.gradle.mustache create mode 100644 samples/client/petstore/java/default/build.gradle create mode 100644 samples/client/petstore/java/default/gradle.properties create mode 100644 samples/client/petstore/java/default/settings.gradle create mode 100644 samples/client/petstore/java/jersey2/build.gradle create mode 100644 samples/client/petstore/java/jersey2/gradle.properties create mode 100644 samples/client/petstore/java/jersey2/settings.gradle create mode 100644 samples/client/petstore/java/okhttp-gson/gradle.properties create mode 100644 samples/client/petstore/java/okhttp-gson/settings.gradle create mode 100644 samples/client/petstore/java/retrofit/build.gradle create mode 100644 samples/client/petstore/java/retrofit/gradle.properties create mode 100644 samples/client/petstore/java/retrofit/settings.gradle 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 360dc9c0f2f0..1d56c340dea4 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 @@ -156,6 +156,9 @@ public void processOpts() { final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); + supportingFiles.add(new SupportingFile("gradle.properties.mustache", "", "gradle.properties")); supportingFiles.add(new SupportingFile("ApiClient.mustache", invokerFolder, "ApiClient.java")); supportingFiles.add(new SupportingFile("StringUtil.mustache", invokerFolder, "StringUtil.java")); @@ -177,8 +180,6 @@ public void processOpts() { if ("okhttp-gson".equals(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); - // "build.gradle" is for development with Gradle - supportingFiles.add(new SupportingFile("build.gradle.mustache", "", "build.gradle")); // "build.sbt" is for development with SBT supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } else if ("retrofit".equals(getLibrary())) { diff --git a/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache new file mode 100644 index 000000000000..971dcd816a49 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/build.gradle.mustache @@ -0,0 +1,107 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.4.2" + jersey_version = "1.18" + jodatime_version = "2.3" + junit_version = "4.8.1" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + testCompile "junit:junit:$junit_version" +} diff --git a/modules/swagger-codegen/src/main/resources/Java/gradle.properties.mustache b/modules/swagger-codegen/src/main/resources/Java/gradle.properties.mustache new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/gradle.properties.mustache @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache new file mode 100644 index 000000000000..548c1854e5e1 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/jersey2/build.gradle.mustache @@ -0,0 +1,107 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.4.2" + jersey_version = "2.6" + jodatime_version = "2.3" + junit_version = "4.8.1" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + testCompile "junit:junit:$junit_version" +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 02e1caa673af..289f9a6df722 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -1,11 +1,89 @@ -apply plugin: 'java' -apply plugin: 'maven' +group = '{{groupId}}' +version = '{{artifactVersion}}' -sourceCompatibility = JavaVersion.VERSION_1_7 -targetCompatibility = JavaVersion.VERSION_1_7 +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} repositories { - mavenCentral() + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } dependencies { @@ -15,17 +93,3 @@ dependencies { compile 'com.brsanthu:migbase64:2.2' testCompile 'junit:junit:4.8.1' } - -group = '{{groupId}}' -version = '{{artifactVersion}}' - -install { - repositories.mavenInstaller { - pom.artifactId = '{{artifactId}}' - } -} - -task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath -} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache new file mode 100644 index 000000000000..a285745505ac --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/build.gradle.mustache @@ -0,0 +1,103 @@ +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = '{{artifactId}}' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + okhttp_version = "2.3.0" + oltu_version = "1.0.0" + retrofit_version = "1.9.0" + swagger_annotations_version = "1.5.0" + junit_version = "4.12" +} + +dependencies { + compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + testCompile "junit:junit:$junit_version" +} diff --git a/modules/swagger-codegen/src/main/resources/Java/settings.gradle.mustache b/modules/swagger-codegen/src/main/resources/Java/settings.gradle.mustache new file mode 100644 index 000000000000..b8fd6c4c41f9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/samples/client/petstore/java/default/build.gradle b/samples/client/petstore/java/default/build.gradle new file mode 100644 index 000000000000..baa5ce97b015 --- /dev/null +++ b/samples/client/petstore/java/default/build.gradle @@ -0,0 +1,107 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-java-client' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.4.2" + jersey_version = "1.18" + jodatime_version = "2.3" + junit_version = "4.8.1" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "com.sun.jersey:jersey-client:$jersey_version" + compile "com.sun.jersey.contribs:jersey-multipart:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/default/gradle.properties b/samples/client/petstore/java/default/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/client/petstore/java/default/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/default/settings.gradle b/samples/client/petstore/java/default/settings.gradle new file mode 100644 index 000000000000..55640f75122e --- /dev/null +++ b/samples/client/petstore/java/default/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-java-client" \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/build.gradle b/samples/client/petstore/java/jersey2/build.gradle new file mode 100644 index 000000000000..9727e5693e6d --- /dev/null +++ b/samples/client/petstore/java/jersey2/build.gradle @@ -0,0 +1,107 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-jersey2' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.5.0" + jackson_version = "2.4.2" + jersey_version = "2.6" + jodatime_version = "2.3" + junit_version = "4.8.1" +} + +dependencies { + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.glassfish.jersey.core:jersey-client:$jersey_version" + compile "org.glassfish.jersey.media:jersey-media-multipart:$jersey_version" + compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" + compile "com.fasterxml.jackson.datatype:jackson-datatype-joda:2.1.5" + compile "joda-time:joda-time:$jodatime_version" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/jersey2/gradle.properties b/samples/client/petstore/java/jersey2/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/client/petstore/java/jersey2/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2/settings.gradle b/samples/client/petstore/java/jersey2/settings.gradle new file mode 100644 index 000000000000..498d426abeeb --- /dev/null +++ b/samples/client/petstore/java/jersey2/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-jersey2" \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index ada6a992573a..eea46b819d02 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -1,11 +1,89 @@ -apply plugin: 'java' -apply plugin: 'maven' +group = 'io.swagger' +version = '1.0.0' -sourceCompatibility = JavaVersion.VERSION_1_7 -targetCompatibility = JavaVersion.VERSION_1_7 +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} repositories { - mavenCentral() + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-okhttp-gson' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } } dependencies { @@ -15,17 +93,3 @@ dependencies { compile 'com.brsanthu:migbase64:2.2' testCompile 'junit:junit:4.8.1' } - -group = 'io.swagger' -version = '1.0.0' - -install { - repositories.mavenInstaller { - pom.artifactId = 'swagger-petstore-okhttp-gson' - } -} - -task execute(type:JavaExec) { - main = System.getProperty('mainClass') - classpath = sourceSets.main.runtimeClasspath -} diff --git a/samples/client/petstore/java/okhttp-gson/gradle.properties b/samples/client/petstore/java/okhttp-gson/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/settings.gradle b/samples/client/petstore/java/okhttp-gson/settings.gradle new file mode 100644 index 000000000000..b73eec845910 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-okhttp-gson" \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/build.gradle b/samples/client/petstore/java/retrofit/build.gradle new file mode 100644 index 000000000000..710d9da9a54c --- /dev/null +++ b/samples/client/petstore/java/retrofit/build.gradle @@ -0,0 +1,103 @@ +group = 'io.swagger' +version = '1.0.0' + +buildscript { + repositories { + jcenter() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.2.2' + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } +} + +repositories { + jcenter() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 22 + buildToolsVersion '22.0.0' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_7 + targetCompatibility JavaVersion.VERSION_1_7 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDir + task.destinationDir = project.file("${project.buildDir}/outputs/jar") + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven' + + sourceCompatibility = JavaVersion.VERSION_1_7 + targetCompatibility = JavaVersion.VERSION_1_7 + + install { + repositories.mavenInstaller { + pom.artifactId = 'swagger-petstore-retrofit' + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + okhttp_version = "2.3.0" + oltu_version = "1.0.0" + retrofit_version = "1.9.0" + swagger_annotations_version = "1.5.0" + junit_version = "4.12" +} + +dependencies { + compile "com.squareup.okhttp:okhttp:$okhttp_version" + compile "com.squareup.retrofit:retrofit:$retrofit_version" + compile "io.swagger:swagger-annotations:$swagger_annotations_version" + compile "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:$oltu_version" + testCompile "junit:junit:$junit_version" +} diff --git a/samples/client/petstore/java/retrofit/gradle.properties b/samples/client/petstore/java/retrofit/gradle.properties new file mode 100644 index 000000000000..05644f0754af --- /dev/null +++ b/samples/client/petstore/java/retrofit/gradle.properties @@ -0,0 +1,2 @@ +# Uncomment to build for Android +#target = android \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/settings.gradle b/samples/client/petstore/java/retrofit/settings.gradle new file mode 100644 index 000000000000..7e540c099de9 --- /dev/null +++ b/samples/client/petstore/java/retrofit/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-petstore-retrofit" \ No newline at end of file From 17545e959ac3edf1bd5bca87821b72e16399e9c5 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 13 Oct 2015 10:32:07 +0800 Subject: [PATCH 192/219] Handle enum names starting with number in Java client --- .../io/swagger/codegen/languages/JavaClientCodegen.java | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) 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 360dc9c0f2f0..df4f07e25e6a 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 @@ -426,7 +426,12 @@ private String findCommonPrefixOfVars(List vars) { } private String toEnumVarName(String value) { - return value.replaceAll("\\W+", "_").toUpperCase(); + String var = value.replaceAll("\\W+", "_").toUpperCase(); + if (var.matches("\\d.*")) { + return "_" + var; + } else { + return var; + } } private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { From 1ef51e5ad7ae6dfee448bbd0702bc1b86fd2a2c5 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 13 Oct 2015 16:22:02 +0800 Subject: [PATCH 193/219] Apply global security to operations when necessary Closes #1365 --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index a785f45bdf21..94f57d144c5c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -12,6 +12,7 @@ import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.Path; +import io.swagger.models.SecurityRequirement; import io.swagger.models.Swagger; import io.swagger.models.auth.OAuth2Definition; import io.swagger.models.auth.SecuritySchemeDefinition; @@ -476,6 +477,12 @@ public void processOperation(String resourcePath, String httpMethod, Operation o config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); List>> securities = operation.getSecurity(); + if (securities == null && swagger.getSecurity() != null) { + securities = new ArrayList>>(); + for (SecurityRequirement sr : swagger.getSecurity()) { + securities.add(sr.getRequirements()); + } + } if (securities == null) { continue; } From 4e7d893a8e637d1072791a8422d4465412fce657 Mon Sep 17 00:00:00 2001 From: aersamkull Date: Tue, 13 Oct 2015 12:01:34 +0200 Subject: [PATCH 194/219] Updates to TypeScript Templates --- .../resources/TypeScript-Angular/api.mustache | 14 +++++++------- .../resources/TypeScript-Angular/model.mustache | 6 +++--- .../main/resources/TypeScript-node/api.mustache | 16 ++++++++-------- 3 files changed, 18 insertions(+), 18 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 233ead8bee48..2045dd353826 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -3,7 +3,7 @@ /* tslint:disable:no-unused-variable member-ordering */ {{#operations}} -module {{package}} { +namespace {{package}} { 'use strict'; {{#description}} @@ -24,16 +24,16 @@ module {{package}} { {{#operation}} public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}, {{/allParams}}extraHttpRequestParams?: any ) : ng.IHttpPromise<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}{}{{/returnType}}> { - var path = this.basePath + '{{path}}'; + let path = this.basePath + '{{path}}'; {{#pathParams}} path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); {{/pathParams}} - var queryParameters: any = {}; - var headerParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = {}; {{#hasFormParams}} - var formParams: any = {}; + let formParams: any = {}; {{/hasFormParams}} {{#allParams}} @@ -63,7 +63,7 @@ module {{package}} { formParams['{{baseName}}'] = {{paramName}}; {{/formParams}} - var httpRequestParams: any = { + let httpRequestParams: any = { method: '{{httpMethod}}', url: path, json: {{#hasFormParams}}false{{/hasFormParams}}{{^hasFormParams}}true{{/hasFormParams}}, @@ -76,7 +76,7 @@ module {{package}} { }; if (extraHttpRequestParams) { - for (var k in extraHttpRequestParams) { + for (let k in extraHttpRequestParams) { if (extraHttpRequestParams.hasOwnProperty(k)) { httpRequestParams[k] = extraHttpRequestParams[k]; } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache index b425d14d5e43..5b57ed4dc94f 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/model.mustache @@ -1,6 +1,6 @@ /// -module {{package}} { +namespace {{package}} { 'use strict'; {{#models}} @@ -10,7 +10,7 @@ module {{package}} { * {{{description}}} */ {{/description}} - export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ + export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ {{#vars}} {{#description}} @@ -23,7 +23,7 @@ module {{package}} { } {{#hasEnums}} - export module {{classname}} { + export namespace {{classname}} { {{#vars}} {{#isEnum}} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache index 6528a5d3a22c..4d03ae0f4248 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-node/api.mustache @@ -27,7 +27,7 @@ export class {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ } {{#hasEnums}} -export module {{classname}} { +export namespace {{classname}} { {{#vars}} {{#isEnum}} export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} @@ -157,15 +157,15 @@ export class {{classname}} { {{#operation}} public {{nickname}} ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{{dataType}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) : Promise<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }> { - var path = this.url + this.basePath + '{{path}}'; + let path = this.url + this.basePath + '{{path}}'; {{#pathParams}} path = path.replace('{' + '{{baseName}}' + '}', String({{paramName}})); {{/pathParams}} - var queryParameters: any = {}; - var headerParams: any = {}; - var formParams: any = {}; + let queryParameters: any = {}; + let headerParams: any = {}; + let formParams: any = {}; {{#allParams}}{{#required}} // verify required parameter '{{paramName}}' is set @@ -183,7 +183,7 @@ export class {{classname}} { headerParams['{{baseName}}'] = {{paramName}}; {{/headerParams}} - var useFormData = false; + let useFormData = false; {{#formParams}} if ({{paramName}} !== undefined) { @@ -194,9 +194,9 @@ export class {{classname}} { {{/isFile}} {{/formParams}} - var deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); + let deferred = promise.defer<{ response: http.ClientResponse; {{#returnType}}body: {{{returnType}}}; {{/returnType}} }>(); - var requestOptions: request.Options = { + let requestOptions: request.Options = { method: '{{httpMethod}}', qs: queryParameters, headers: headerParams, From f603efc419e79dab5b0840f634c8581b5b01dbb2 Mon Sep 17 00:00:00 2001 From: cbornet Date: Tue, 13 Oct 2015 12:18:32 +0200 Subject: [PATCH 195/219] add retrofit to CI verified samples --- pom.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/pom.xml b/pom.xml index d2cbadb394fd..27ce57442785 100644 --- a/pom.xml +++ b/pom.xml @@ -426,6 +426,7 @@ samples/client/petstore/java/default samples/client/petstore/java/jersey2 samples/client/petstore/java/okhttp-gson + samples/client/petstore/java/retrofit samples/client/petstore/scala samples/server/petstore/spring-mvc From 988de07c1798890d0468ecfdcfe32db5a246b119 Mon Sep 17 00:00:00 2001 From: aersamkull Date: Tue, 13 Oct 2015 13:32:01 +0200 Subject: [PATCH 196/219] Fixes noImplicitAny Error --- .../src/main/resources/TypeScript-Angular/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache index 2045dd353826..9681634a765a 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Angular/api.mustache @@ -16,7 +16,7 @@ namespace {{package}} { static $inject: string[] = ['$http', '$httpParamSerializer']; - constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (any) => any) { + constructor(private $http: ng.IHttpService, basePath?: string, private $httpParamSerializer?: (d: any) => any) { if (basePath) { this.basePath = basePath; } From 0b4b5e8839cd3f447fde86e4aa2a8db8fc2985f6 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 13 Oct 2015 23:47:42 +0800 Subject: [PATCH 197/219] Revert "Add support for top-level consumes and produces" --- .../io/swagger/codegen/CodegenConfig.java | 2 - .../io/swagger/codegen/DefaultCodegen.java | 52 ++----- .../io/swagger/codegen/DefaultGenerator.java | 2 +- .../codegen/languages/SwiftCodegen.java | 6 +- .../java/io/swagger/codegen/CodegenTest.java | 48 ------- .../2_0/globalConsumesAndProduces.json | 130 ------------------ 6 files changed, 11 insertions(+), 229 deletions(-) delete mode 100644 modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index b50147a6ff3e..10d7363cc35a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -67,8 +67,6 @@ public interface CodegenConfig { CodegenModel fromModel(String name, Model model, Map allDefinitions); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger); - CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); List fromSecurity(Map schemes); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index b5dd47b47687..69d7cadbf0ad 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -867,12 +867,8 @@ private Response findMethodResponse(Map responses) { } return responses.get(code); } - + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { - return fromOperation(path, httpMethod, operation, definitions, null); - } - - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); @@ -908,32 +904,15 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.summary = escapeText(operation.getSummary()); op.notes = escapeText(operation.getDescription()); op.tags = operation.getTags(); - op.hasConsumes = false; - op.hasProduces = false; - - List consumes = new ArrayList(); - if (operation.getConsumes() != null) { - if (operation.getConsumes().size() > 0) { - // use consumes defined in the operation - consumes = operation.getConsumes(); - } else { - // empty list, do nothing to override global setting - } - } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { - // use consumes defined globally - consumes = swagger.getConsumes(); - LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); - } - - // if "consumes" is defined (per operation or using global definition) - if (consumes != null && consumes.size() > 0) { + + if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : consumes) { + for (String key : operation.getConsumes()) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < consumes.size()) { + if (count < operation.getConsumes().size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); @@ -944,29 +923,14 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.hasConsumes = true; } - List produces = new ArrayList(); - if (operation.getProduces() != null) { - if (operation.getProduces().size() > 0) { - // use produces defined in the operation - produces = operation.getProduces(); - } else { - // empty list, do nothing to override global setting - } - } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { - // use produces defined globally - produces = swagger.getProduces(); - LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); - } - - // if "produces" is defined (per operation or using global definition) - if (produces != null && produces.size() > 0) { + if (operation.getProduces() != null && operation.getProduces().size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : produces) { + for (String key : operation.getProduces()) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < produces.size()) { + if (count < operation.getProduces().size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 2b61635e0b9b..a785f45bdf21 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -470,7 +470,7 @@ public void processOperation(String resourcePath, String httpMethod, Operation o for (String tag : tags) { CodegenOperation co = null; try { - co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); + co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); co.tags = new ArrayList(); co.tags.add(sanitizeTag(tag)); config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 9bb1dfd61d47..55c3864adb7d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -1,11 +1,9 @@ package io.swagger.codegen.languages; import com.google.common.base.Predicate; - import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import io.swagger.codegen.*; -import io.swagger.models.Swagger; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.parameters.HeaderParameter; @@ -258,7 +256,7 @@ public String toApiName(String name) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { path = normalizePath(path); List parameters = operation.getParameters(); parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { @@ -268,7 +266,7 @@ public boolean apply(@Nullable Parameter parameter) { } })); operation.setParameters(parameters); - return super.fromOperation(path, httpMethod, operation, definitions, swagger); + return super.fromOperation(path, httpMethod, operation, definitions); } private static String normalizePath(String path) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index 0fa8953e7bf5..ee70b427bfdf 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -139,52 +139,4 @@ public void binaryDataTest() { Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.responses.get(0).isBinary); } - - @Test(description = "use operation consumes and produces") - public void localConsumesAndProducesTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/localConsumesAndProduces"; - final Operation p = model.getPaths().get(path).getGet(); - CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - - Assert.assertTrue(op.hasConsumes); - Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json"); - Assert.assertTrue(op.hasProduces); - Assert.assertEquals(op.produces.size(), 1); - Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); - } - - @Test(description = "use spec consumes and produces") - public void globalConsumesAndProducesTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/globalConsumesAndProduces"; - final Operation p = model.getPaths().get(path).getGet(); - CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - - Assert.assertTrue(op.hasConsumes); - Assert.assertEquals(op.consumes.size(), 1); - Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes"); - Assert.assertTrue(op.hasProduces); - Assert.assertEquals(op.produces.size(), 1); - Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); - } - - @Test(description = "use operation consumes and produces (reset in operation with empty array)") - public void localResetConsumesAndProducesTest() { - final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); - final DefaultCodegen codegen = new DefaultCodegen(); - final String path = "/tests/localResetConsumesAndProduces"; - final Operation p = model.getPaths().get(path).getGet(); - CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); - - Assert.assertNotNull(op); - Assert.assertFalse(op.hasConsumes); - Assert.assertNull(op.consumes); - Assert.assertFalse(op.hasProduces); - Assert.assertNull(op.produces); - - } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json deleted file mode 100644 index 520218ed707e..000000000000 --- a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json +++ /dev/null @@ -1,130 +0,0 @@ -{ - "swagger": "2.0", - "info": { - "description": "Spec for testing global consumes and produces", - "version": "1.0.0", - "title": "Swagger Petstore", - "termsOfService": "http://swagger.io/terms/", - "contact": { - "email": "apiteam@swagger.io" - }, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - } - }, - "host": "petstore.swagger.io", - "basePath": "/v2", - "consumes": ["application/global_consumes"], - "produces": ["application/global_produces"], - "schemes": [ - "http" - ], - "paths": { - "/tests/localConsumesAndProduces": { - "get": { - "tags": [ - "tests" - ], - "summary": "Operation with local consumes and produces", - "description": "", - "operationId": "localConsumesAndProduces", - "produces": [ - "application/json" - ], - "consumes": [ - "application/json" - ], - "parameters": [ - ], - "responses": { - "200": { - "description": "successful operation. Returning a simple int.", - "schema": { - "type": "integer", - "format": "int64" - } - } - } - } - }, - "/tests/globalConsumesAndProduces": { - "get": { - "tags": [ - "tests" - ], - "summary": "Operation with global consumes and produces", - "description": "", - "operationId": "globalConsumesAndProduces", - "parameters": [ - ], - "responses": { - "200": { - "description": "successful operation. Returning a simple int.", - "schema": { - "type": "integer", - "format": "int64" - } - } - } - } - }, - "/tests/localResetConsumesAndProduces": { - "get": { - "tags": [ - "tests" - ], - "summary": "Operation with local consumes and produces set to empty (reset)", - "description": "", - "operationId": "localResetConsumesAndProduces", - "parameters": [ - ], - "consumes": [], - "produces": [], - "responses": { - "200": { - "description": "successful operation. Returning a simple int.", - "schema": { - "type": "integer", - "format": "int64" - } - } - } - } - } - - }, - "securityDefinitions": { - "api_key": { - "type": "apiKey", - "name": "api_key", - "in": "header" - }, - "petstore_auth": { - "type": "oauth2", - "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", - "flow": "implicit", - "scopes": { - "write:pets": "modify pets in your account", - "read:pets": "read your pets" - } - } - }, - "definitions": { - "CustomModel": { - "required": [ - "id" - ], - "properties": { - "id": { - "type": "integer", - "format": "int64" - }, - "name": { - "type": "string", - "example": "doggie" - } - } - } - } -} From e4e77d03f561ad380f8d801d41bf4ae645797452 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 14 Oct 2015 20:40:10 +0800 Subject: [PATCH 198/219] Add test cases for global security --- .../swagger/codegen/DefaultGeneratorTest.java | 103 ++ .../test/resources/2_0/globalSecurity.json | 983 ++++++++++++++++++ 2 files changed, 1086 insertions(+) create mode 100644 modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index 5da6a01763c5..18a115c65273 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -17,11 +17,14 @@ import java.io.Writer; import java.nio.charset.StandardCharsets; import java.util.Arrays; +import java.util.List; +import java.util.Map; import static java.nio.charset.StandardCharsets.UTF_8; import static org.junit.Assert.fail; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; +import static org.testng.Assert.assertNull; /** * Tests for DefaultGenerator logic @@ -44,6 +47,95 @@ public void tearDown() throws Exception { folder.delete(); } + @Test + public void testSecurityWithoutGlobal() throws Exception { + final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/petstore.json"); + CodegenConfig codegenConfig = new JavaClientCodegen(); + + ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + + DefaultGenerator gen = new DefaultGenerator(); + gen.opts(clientOptInput); + Map> paths = gen.processPaths(swagger.getPaths()); + + CodegenSecurity cs, apiKey, petstoreAuth; + + // security of "getPetById": api_key, petstore_auth + CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); + assertEquals(getPetById.authMethods.size(), 2); + cs = getPetById.authMethods.get(0); + if ("api_key".equals(cs.name)) { + apiKey = cs; + petstoreAuth = getPetById.authMethods.get(1); + } else { + petstoreAuth = cs; + apiKey = getPetById.authMethods.get(1); + } + assertEquals(apiKey.name, "api_key"); + assertEquals(apiKey.type, "apiKey"); + assertEquals(petstoreAuth.name, "petstore_auth"); + assertEquals(petstoreAuth.type, "oauth2"); + + // security of "updatePetWithForm": petstore_auth + CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); + assertEquals(updatePetWithForm.authMethods.size(), 1); + petstoreAuth = updatePetWithForm.authMethods.iterator().next(); + assertEquals(petstoreAuth.name, "petstore_auth"); + assertEquals(petstoreAuth.type, "oauth2"); + + // security of "loginUser": null (no global security either) + CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser"); + assertNull(loginUser.authMethods); + } + + @Test + public void testSecurityWithGlobal() throws Exception { + final Swagger swagger = new SwaggerParser().read("src/test/resources/2_0/globalSecurity.json"); + CodegenConfig codegenConfig = new JavaClientCodegen(); + + ClientOptInput clientOptInput = new ClientOptInput().opts(new ClientOpts()).swagger(swagger).config(codegenConfig); + + DefaultGenerator gen = new DefaultGenerator(); + gen.opts(clientOptInput); + Map> paths = gen.processPaths(swagger.getPaths()); + + CodegenSecurity cs, apiKey, petstoreAuth; + + // security of "getPetById": api_key, petstore_auth + CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); + assertEquals(getPetById.authMethods.size(), 2); + cs = getPetById.authMethods.get(0); + if ("api_key".equals(cs.name)) { + apiKey = cs; + petstoreAuth = getPetById.authMethods.get(1); + } else { + petstoreAuth = cs; + apiKey = getPetById.authMethods.get(1); + } + assertEquals(apiKey.name, "api_key"); + assertEquals(apiKey.type, "apiKey"); + assertEquals(petstoreAuth.name, "petstore_auth"); + assertEquals(petstoreAuth.type, "oauth2"); + + // security of "updatePetWithForm": petstore_auth + CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); + assertEquals(updatePetWithForm.authMethods.size(), 1); + petstoreAuth = updatePetWithForm.authMethods.iterator().next(); + assertEquals(petstoreAuth.name, "petstore_auth"); + assertEquals(petstoreAuth.type, "oauth2"); + + // security of "loginUser": api_key (from global security) + CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser"); + assertEquals(loginUser.authMethods.size(), 1); + apiKey = loginUser.authMethods.iterator().next(); + assertEquals(apiKey.name, "api_key"); + assertEquals(apiKey.type, "apiKey"); + + // security of "logoutUser": null (override global security) + CodegenOperation logoutUser = findCodegenOperationByOperationId(paths, "logoutUser"); + assertNull(logoutUser.authMethods); + } + @Test public void testSkipOverwrite() throws Exception { final File output = folder.getRoot(); @@ -89,4 +181,15 @@ private void changeContent(File file) throws IOException { out.close(); } + private CodegenOperation findCodegenOperationByOperationId(Map> paths, String operationId) { + for (List ops : paths.values()) { + for (CodegenOperation co : ops) { + if (operationId.equals(co.operationId)) { + return co; + } + } + } + return null; + } + } diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json new file mode 100644 index 000000000000..3d1548e769cc --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json @@ -0,0 +1,983 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/pet": { + "post": { + "tags": [ + "pet" + ], + "summary": "Add a new pet to the store", + "description": "", + "operationId": "addPet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "put": { + "tags": [ + "pet" + ], + "summary": "Update an existing pet", + "description": "", + "operationId": "updatePet", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object that needs to be added to the store", + "required": false, + "schema": { + "$ref": "#/definitions/Pet" + } + } + ], + "responses": { + "405": { + "description": "Validation exception" + }, + "404": { + "description": "Pet not found" + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByStatus": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by status", + "description": "Multiple status values can be provided with comma seperated strings", + "operationId": "findPetsByStatus", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "status", + "in": "query", + "description": "Status values that need to be considered for filter", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi", + "default": "available" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid status value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/findByTags": { + "get": { + "tags": [ + "pet" + ], + "summary": "Finds Pets by tags", + "description": "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", + "operationId": "findPetsByTags", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "tags", + "in": "query", + "description": "Tags to filter by", + "required": false, + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "multi" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/Pet" + } + } + }, + "400": { + "description": "Invalid tag value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}": { + "get": { + "tags": [ + "pet" + ], + "summary": "Find pet by ID", + "description": "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "operationId": "getPetById", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "404": { + "description": "Pet not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Pet" + } + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "api_key": [] + }, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "post": { + "tags": [ + "pet" + ], + "summary": "Updates a pet in the store with form data", + "description": "", + "operationId": "updatePetWithForm", + "consumes": [ + "application/x-www-form-urlencoded" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet that needs to be updated", + "required": true, + "type": "string" + }, + { + "name": "name", + "in": "formData", + "description": "Updated name of the pet", + "required": false, + "type": "string" + }, + { + "name": "status", + "in": "formData", + "description": "Updated status of the pet", + "required": false, + "type": "string" + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + }, + "delete": { + "tags": [ + "pet" + ], + "summary": "Deletes a pet", + "description": "", + "operationId": "deletePet", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "api_key", + "in": "header", + "description": "", + "required": false, + "type": "string" + }, + { + "name": "petId", + "in": "path", + "description": "Pet id to delete", + "required": true, + "type": "integer", + "format": "int64" + } + ], + "responses": { + "400": { + "description": "Invalid pet value" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/pet/{petId}/uploadImage": { + "post": { + "tags": [ + "pet" + ], + "summary": "uploads an image", + "description": "", + "operationId": "uploadFile", + "consumes": [ + "multipart/form-data" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "petId", + "in": "path", + "description": "ID of pet to update", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "additionalMetadata", + "in": "formData", + "description": "Additional data to pass to server", + "required": false, + "type": "string" + }, + { + "name": "file", + "in": "formData", + "description": "file to upload", + "required": false, + "type": "file" + } + ], + "responses": { + "default": { + "description": "successful operation" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, + "/store/inventory": { + "get": { + "tags": [ + "store" + ], + "summary": "Returns pet inventories by status", + "description": "Returns a map of status codes to quantities", + "operationId": "getInventory", + "produces": [ + "application/json", + "application/xml" + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "object", + "additionalProperties": { + "type": "integer", + "format": "int32" + } + } + } + }, + "security": [ + { + "api_key": [] + } + ] + } + }, + "/store/order": { + "post": { + "tags": [ + "store" + ], + "summary": "Place an order for a pet", + "description": "", + "operationId": "placeOrder", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "order placed for purchasing the pet", + "required": false, + "schema": { + "$ref": "#/definitions/Order" + } + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid Order" + } + } + } + }, + "/store/order/{orderId}": { + "get": { + "tags": [ + "store" + ], + "summary": "Find purchase order by ID", + "description": "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", + "operationId": "getOrderById", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of pet that needs to be fetched", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/Order" + } + }, + "400": { + "description": "Invalid ID supplied" + } + } + }, + "delete": { + "tags": [ + "store" + ], + "summary": "Delete purchase order by ID", + "description": "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", + "operationId": "deleteOrder", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "orderId", + "in": "path", + "description": "ID of the order that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "Order not found" + }, + "400": { + "description": "Invalid ID supplied" + } + } + } + }, + "/user": { + "post": { + "tags": [ + "user" + ], + "summary": "Create user", + "description": "This can only be done by the logged in user.", + "operationId": "createUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Created user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithArray": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithArrayInput", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/createWithList": { + "post": { + "tags": [ + "user" + ], + "summary": "Creates list of users with given input array", + "description": "", + "operationId": "createUsersWithListInput", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "List of user object", + "required": false, + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/User" + } + } + } + ], + "responses": { + "default": { + "description": "successful operation" + } + } + } + }, + "/user/login": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs user into the system", + "description": "", + "operationId": "loginUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "query", + "description": "The user name for login", + "required": false, + "type": "string" + }, + { + "name": "password", + "in": "query", + "description": "The password for login in clear text", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation", + "schema": { + "type": "string" + } + }, + "400": { + "description": "Invalid username/password supplied" + } + } + } + }, + "/user/logout": { + "get": { + "tags": [ + "user" + ], + "summary": "Logs out current logged in user session", + "description": "", + "operationId": "logoutUser", + "produces": [ + "application/json", + "application/xml" + ], + "responses": { + "default": { + "description": "successful operation" + } + }, + "security": [] + } + }, + "/user/{username}": { + "get": { + "tags": [ + "user" + ], + "summary": "Get user by user name", + "description": "", + "operationId": "getUserByName", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be fetched. Use user1 for testing. ", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "200": { + "description": "successful operation", + "schema": { + "$ref": "#/definitions/User" + }, + "examples": { + "application/json": { + "id": 1, + "username": "johnp", + "firstName": "John", + "lastName": "Public", + "email": "johnp@swagger.io", + "password": "-secret-", + "phone": "0123456789", + "userStatus": 0 + } + } + }, + "400": { + "description": "Invalid username supplied" + } + } + }, + "put": { + "tags": [ + "user" + ], + "summary": "Updated user", + "description": "This can only be done by the logged in user.", + "operationId": "updateUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "name that need to be deleted", + "required": true, + "type": "string" + }, + { + "in": "body", + "name": "body", + "description": "Updated user object", + "required": false, + "schema": { + "$ref": "#/definitions/User" + } + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid user supplied" + } + } + }, + "delete": { + "tags": [ + "user" + ], + "summary": "Delete user", + "description": "This can only be done by the logged in user.", + "operationId": "deleteUser", + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "name": "username", + "in": "path", + "description": "The name that needs to be deleted", + "required": true, + "type": "string" + } + ], + "responses": { + "404": { + "description": "User not found" + }, + "400": { + "description": "Invalid username supplied" + } + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + }, + "security": [ + { + "api_key": [] + } + ], + "definitions": { + "User": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "username": { + "type": "string" + }, + "firstName": { + "type": "string" + }, + "lastName": { + "type": "string" + }, + "email": { + "type": "string" + }, + "password": { + "type": "string" + }, + "phone": { + "type": "string" + }, + "userStatus": { + "type": "integer", + "format": "int32", + "description": "User Status" + } + }, + "xml": { + "name": "User" + } + }, + "Category": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Category" + } + }, + "Pet": { + "required": [ + "name", + "photoUrls" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "category": { + "$ref": "#/definitions/Category" + }, + "name": { + "type": "string", + "example": "doggie" + }, + "photoUrls": { + "type": "array", + "xml": { + "name": "photoUrl", + "wrapped": true + }, + "items": { + "type": "string" + } + }, + "tags": { + "type": "array", + "xml": { + "name": "tag", + "wrapped": true + }, + "items": { + "$ref": "#/definitions/Tag" + } + }, + "status": { + "type": "string", + "description": "pet status in the store", + "enum": [ + "available", + "pending", + "sold" + ] + } + }, + "xml": { + "name": "Pet" + } + }, + "Tag": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string" + } + }, + "xml": { + "name": "Tag" + } + }, + "Order": { + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "petId": { + "type": "integer", + "format": "int64" + }, + "quantity": { + "type": "integer", + "format": "int32" + }, + "shipDate": { + "type": "string", + "format": "date-time" + }, + "status": { + "type": "string", + "description": "Order Status", + "enum": [ + "placed", + "approved", + "delivered" + ] + }, + "complete": { + "type": "boolean" + } + }, + "xml": { + "name": "Order" + } + } + } +} From 6cc17d8508c66e3d5b6f0a90388301319cb63ffa Mon Sep 17 00:00:00 2001 From: Nick Bruno Date: Wed, 14 Oct 2015 22:07:43 -0400 Subject: [PATCH 199/219] Add authorization scope data to CodegenSecurity, demo use in JAXRS --- .../io/swagger/codegen/CodegenOperation.java | 2 +- .../io/swagger/codegen/CodegenSecurity.java | 5 +++-- .../io/swagger/codegen/DefaultCodegen.java | 18 +++++++++++++++++- .../io/swagger/codegen/DefaultGenerator.java | 1 + .../src/main/resources/JavaJaxRS/api.mustache | 8 +++++++- 5 files changed, 29 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java index 373c5b2b7857..871b3f261c0f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenOperation.java @@ -10,7 +10,7 @@ public class CodegenOperation { public final List responseHeaders = new ArrayList(); - public Boolean hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, + public Boolean hasAuthMethods, hasConsumes, hasProduces, hasParams, returnTypeIsPrimitive, returnSimpleType, subresourceOperation, isMapContainer, isListContainer, hasMore = Boolean.TRUE, isMultipart, isResponseBinary = Boolean.FALSE; public String path, operationId, returnType, httpMethod, returnBaseType, diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java index edd65cc06034..101182063839 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenSecurity.java @@ -1,6 +1,7 @@ package io.swagger.codegen; -import java.util.Set; +import java.util.List; +import java.util.Map; public class CodegenSecurity { public String name; @@ -11,5 +12,5 @@ public class CodegenSecurity { public Boolean isKeyInQuery, isKeyInHeader; // Oauth specific public String flow, authorizationUrl, tokenUrl; - public Set scopes; + public List> scopes; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 69d7cadbf0ad..021e6a6662da 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1307,7 +1307,23 @@ public List fromSecurity(Map sec.authorizationUrl = oauth2Definition.getAuthorizationUrl(); sec.tokenUrl = oauth2Definition.getTokenUrl(); if (oauth2Definition.getScopes() != null) { - sec.scopes = oauth2Definition.getScopes().keySet(); + List> scopes = new ArrayList>(); + int count = 0, numScopes = oauth2Definition.getScopes().size(); + for(Map.Entry scopeEntry : oauth2Definition.getScopes().entrySet()) { + Map scope = new HashMap(); + scope.put("scope", scopeEntry.getKey()); + scope.put("description", scopeEntry.getValue()); + + count += 1; + if (count < numScopes) { + scope.put("hasMore", "true"); + } else { + scope.put("hasMore", null); + } + + scopes.add(scope); + } + sec.scopes = scopes; } } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index a785f45bdf21..9fa1b28cad2b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -509,6 +509,7 @@ public void processOperation(String resourcePath, String httpMethod, Operation o } if (!authMethods.isEmpty()) { co.authMethods = config.fromSecurity(authMethods); + co.hasAuthMethods = true; } } catch (Exception ex) { diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index 65dfa6835bfd..8bd9b2ca1083 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -37,7 +37,13 @@ public class {{classname}} { {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @io.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@io.swagger.annotations.Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@io.swagger.annotations.AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}) @io.swagger.annotations.ApiResponses(value = { {{#responses}} @io.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}){{#hasMore}}, {{/hasMore}}{{/responses}} }) From 6d50ce6a774f1545234b7f8244921226824a6aca Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 15 Oct 2015 10:34:45 +0800 Subject: [PATCH 200/219] Fix a typo --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 5d61f1b59324..c559cf83f237 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 @@ -83,7 +83,7 @@ public JavaClientCodegen() { cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC)); cliOptions.add(new CliOption(CodegenConstants.LOCAL_VARIABLE_PREFIX, CodegenConstants.LOCAL_VARIABLE_PREFIX_DESC)); cliOptions.add(new CliOption(CodegenConstants.SERIALIZABLE_MODEL, CodegenConstants.SERIALIZABLE_MODEL_DESC)); - cliOptions.add(new CliOption("fullJavaUtil", "whether to use full qualified name for classes under java.util (default to false)")); + cliOptions.add(new CliOption("fullJavaUtil", "whether to use fully qualified name for classes under java.util (default to false)")); supportedLibraries.put("", "HTTP client: Jersey client 1.18. JSON processing: Jackson 2.4.2"); supportedLibraries.put("jersey2", "HTTP client: Jersey client 2.6"); From 300a0dc82cca6901ff32b2c032cfc3105af3f12e Mon Sep 17 00:00:00 2001 From: Nick Bruno Date: Wed, 14 Oct 2015 22:50:58 -0400 Subject: [PATCH 201/219] Update retrofit library for changes to OAuth scope handling --- .../main/resources/Java/libraries/retrofit/ApiClient.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index 4046f9f107ca..88f0734ce8df 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -54,7 +54,7 @@ public class ApiClient { if (authName == "{{name}}") { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} - auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{^-first}}, {{/-first}}{{this}}{{/scopes}}");{{/isOAuth}} + auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} } else {{/authMethods}}{ throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } From bc5a6105676ec32c2f6db5ed30d446d1281acc66 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 15 Oct 2015 15:17:30 +0800 Subject: [PATCH 202/219] Use the first security requirement from the array According to swagger spec, "there is a logical OR between the security requirements". The original behavior was to apply the security requirements as the logic AND and skip security requirements that include more that 1 security. --- .../io/swagger/codegen/DefaultGenerator.java | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 94f57d144c5c..1ec9aeb2c576 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -483,16 +483,16 @@ public void processOperation(String resourcePath, String httpMethod, Operation o securities.add(sr.getRequirements()); } } - if (securities == null) { + if (securities == null || securities.isEmpty()) { continue; } Map authMethods = new HashMap(); - for (Map> security : securities) { - if (security.size() != 1) { - //Not sure what to do - continue; - } - String securityName = security.keySet().iterator().next(); + // NOTE: Use only the first security requirement for now. + // See the "security" field of "Swagger Object": + // https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object + // "there is a logical OR between the security requirements" + Map> security = securities.get(0); + for (String securityName : security.keySet()) { SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); if (securityDefinition != null) { if(securityDefinition instanceof OAuth2Definition) { @@ -503,7 +503,7 @@ public void processOperation(String resourcePath, String httpMethod, Operation o oauth2Operation.setFlow(oauth2Definition.getFlow()); oauth2Operation.setTokenUrl(oauth2Definition.getTokenUrl()); oauth2Operation.setScopes(new HashMap()); - for (String scope : security.values().iterator().next()) { + for (String scope : security.get(securityName)) { if (oauth2Definition.getScopes().containsKey(scope)) { oauth2Operation.addScope(scope, oauth2Definition.getScopes().get(scope)); } From 5a76a1b1551f1a83af37f8de32b79b4094c76a2c Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 15 Oct 2015 16:51:43 +0800 Subject: [PATCH 203/219] Fix tests regarding security --- .../swagger/codegen/DefaultGeneratorTest.java | 34 +++++-------------- 1 file changed, 8 insertions(+), 26 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index 18a115c65273..2828d8994d72 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -58,23 +58,14 @@ public void testSecurityWithoutGlobal() throws Exception { gen.opts(clientOptInput); Map> paths = gen.processPaths(swagger.getPaths()); - CodegenSecurity cs, apiKey, petstoreAuth; + CodegenSecurity apiKey, petstoreAuth; - // security of "getPetById": api_key, petstore_auth + // security of "getPetById": api_key CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); - assertEquals(getPetById.authMethods.size(), 2); - cs = getPetById.authMethods.get(0); - if ("api_key".equals(cs.name)) { - apiKey = cs; - petstoreAuth = getPetById.authMethods.get(1); - } else { - petstoreAuth = cs; - apiKey = getPetById.authMethods.get(1); - } + assertEquals(getPetById.authMethods.size(), 1); + apiKey = getPetById.authMethods.iterator().next(); assertEquals(apiKey.name, "api_key"); assertEquals(apiKey.type, "apiKey"); - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(petstoreAuth.type, "oauth2"); // security of "updatePetWithForm": petstore_auth CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); @@ -99,23 +90,14 @@ public void testSecurityWithGlobal() throws Exception { gen.opts(clientOptInput); Map> paths = gen.processPaths(swagger.getPaths()); - CodegenSecurity cs, apiKey, petstoreAuth; + CodegenSecurity apiKey, petstoreAuth; - // security of "getPetById": api_key, petstore_auth + // security of "getPetById": api_key CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); - assertEquals(getPetById.authMethods.size(), 2); - cs = getPetById.authMethods.get(0); - if ("api_key".equals(cs.name)) { - apiKey = cs; - petstoreAuth = getPetById.authMethods.get(1); - } else { - petstoreAuth = cs; - apiKey = getPetById.authMethods.get(1); - } + assertEquals(getPetById.authMethods.size(), 1); + apiKey = getPetById.authMethods.iterator().next(); assertEquals(apiKey.name, "api_key"); assertEquals(apiKey.type, "apiKey"); - assertEquals(petstoreAuth.name, "petstore_auth"); - assertEquals(petstoreAuth.type, "oauth2"); // security of "updatePetWithForm": petstore_auth CodegenOperation updatePetWithForm = findCodegenOperationByOperationId(paths, "updatePetWithForm"); From 1c217306076be110bc12752e6df33df0553c2caa Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 15 Oct 2015 17:56:38 +0800 Subject: [PATCH 204/219] Log a warning on more than 1 security requirements --- .../src/main/java/io/swagger/codegen/DefaultGenerator.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 1ec9aeb2c576..6fc8eecd045b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -491,6 +491,9 @@ public void processOperation(String resourcePath, String httpMethod, Operation o // See the "security" field of "Swagger Object": // https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object // "there is a logical OR between the security requirements" + if (securities.size() > 1) { + LOGGER.warn("More than 1 security requirements are found, using only the first one"); + } Map> security = securities.get(0); for (String securityName : security.keySet()) { SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); From 21eb4061408b5a27a065bac15946688123298c47 Mon Sep 17 00:00:00 2001 From: gwen15 Date: Thu, 8 Oct 2015 10:00:59 +0200 Subject: [PATCH 205/219] Fix default long value in java client code generation The generated java code for a Long was "Long id=1;" which is not compilable by javac because "1" is a primitive integer that cannot be cast to a Long object. This fix generates now "Long id=1l;". --- .../io/swagger/codegen/languages/JavaClientCodegen.java | 7 +++++++ 1 file changed, 7 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 ec157e6ddff8..5f786ca7a3ef 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 @@ -12,6 +12,7 @@ import io.swagger.codegen.SupportingFile; import io.swagger.models.Model; import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; @@ -340,6 +341,12 @@ public String toDefaultValue(Property p) { pattern = "new HashMap()"; } return String.format(pattern, getTypeDeclaration(ap.getAdditionalProperties())); + } else if (p instanceof LongProperty) { + LongProperty dp = (LongProperty) p; + if (dp.getDefault() != null) { + return dp.getDefault().toString()+"l"; + } + return "null"; } return super.toDefaultValue(p); } From 0802f94d949c8a470eea0c0d0cc5dd8b050e637a Mon Sep 17 00:00:00 2001 From: gwen15 Date: Tue, 13 Oct 2015 09:41:02 +0200 Subject: [PATCH 206/219] Bug fix: some character replacement where done on the local directories names. The dot character was replaced by the file separator on the whole paths, not only on the package name based part. --- .../codegen/languages/CSharpClientCodegen.java | 13 ++++++------- .../languages/CsharpDotNet2ClientCodegen.java | 10 +++++----- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java index 4b17715e6653..bd3487d06df7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CSharpClientCodegen.java @@ -104,13 +104,13 @@ public void processOpts() { } additionalProperties.put("clientPackage", clientPackage); - + supportingFiles.add(new SupportingFile("Configuration.mustache", - (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs")); + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", - (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs")); supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs")); + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs")); supportingFiles.add(new SupportingFile("Newtonsoft.Json.dll", "bin", "Newtonsoft.Json.dll")); supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); @@ -137,12 +137,11 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - - return outputFolder + File.separator + (sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); } public String modelFileFolder() { - return outputFolder + File.separator + (sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); } @Override diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java index 432e7ae3fa23..9d9757a91319 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/CsharpDotNet2ClientCodegen.java @@ -108,11 +108,11 @@ public void processOpts() { } supportingFiles.add(new SupportingFile("Configuration.mustache", - (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "Configuration.cs")); + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", - (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiClient.cs")); + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiClient.cs")); supportingFiles.add(new SupportingFile("ApiException.mustache", - (sourceFolder + File.separator + clientPackage).replace(".", java.io.File.separator), "ApiException.cs")); + sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "ApiException.cs")); supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor", "packages.config")); supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); @@ -142,11 +142,11 @@ public String escapeReservedWord(String name) { @Override public String apiFileFolder() { - return (outputFolder + File.separator + sourceFolder + File.separator + apiPackage()).replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); } public String modelFileFolder() { - return (outputFolder + File.separator + sourceFolder + File.separator + modelPackage()).replace('.', File.separatorChar); + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); } @Override From 97a5a8922fcd8b925eddc1325adbe3cb8936a882 Mon Sep 17 00:00:00 2001 From: akkie Date: Thu, 15 Oct 2015 16:07:35 +0200 Subject: [PATCH 207/219] Allow to disable SSL verification This pull request adds the possibility to disable SSL verification for hosts using a self-signed SSL certificate --- .../src/main/resources/php/ApiClient.mustache | 82 +++++------ .../main/resources/php/configuration.mustache | 128 +++++++++++------- 2 files changed, 124 insertions(+), 86 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index 8927cbbecb38..9db41df2aeec 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -1,11 +1,11 @@ config = $config; $this->serializer = new ObjectSerializer(); } - + /** * Get the config * @return Configuration @@ -87,7 +87,7 @@ class ApiClient { return $this->config; } - + /** * Get the serializer * @return ObjectSerializer @@ -96,7 +96,7 @@ class ApiClient { return $this->serializer; } - + /** * Get API key (with prefix if set) * @param string $apiKeyIdentifier name of apikey @@ -106,20 +106,20 @@ class ApiClient { $prefix = $this->config->getApiKeyPrefix($apiKeyIdentifier); $apiKey = $this->config->getApiKey($apiKeyIdentifier); - + if (!isset($apiKey)) { return null; } - + if (isset($prefix)) { $keyWithPrefix = $prefix." ".$apiKey; } else { $keyWithPrefix = $apiKey; } - + return $keyWithPrefix; } - + /** * Make the HTTP call (Sync) * @param string $resourcePath path to method endpoint @@ -133,28 +133,28 @@ class ApiClient */ public function callApi($resourcePath, $method, $queryParams, $postData, $headerParams, $responseType=null) { - + $headers = array(); - + // construct the http header $headerParams = array_merge( - (array)$this->config->getDefaultHeaders(), + (array)$this->config->getDefaultHeaders(), (array)$headerParams ); - + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; } - + // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { $postData = http_build_query($postData); } else if ((is_object($postData) or is_array($postData)) and !in_array('Content-Type: multipart/form-data', $headers)) { // json model $postData = json_encode($this->serializer->sanitizeForSerialization($postData)); } - + $url = $this->config->getHost() . $resourcePath; - + $curl = curl_init(); // set timeout, if needed if ($this->config->getCurlTimeout() != 0) { @@ -162,13 +162,19 @@ class ApiClient } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); - + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); - + + // disable SSL verification, if needed + if ($this->config->getSSLVerification() == false) { + curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); + curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0); + } + if (! empty($queryParams)) { $url = ($url . '?' . http_build_query($queryParams)); } - + if ($method == self::$POST) { curl_setopt($curl, CURLOPT_POST, true); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); @@ -190,44 +196,44 @@ class ApiClient throw new ApiException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); - + // Set user agent curl_setopt($curl, CURLOPT_USERAGENT, $this->config->getUserAgent()); - + // debugging for curl if ($this->config->getDebug()) { error_log("[DEBUG] HTTP Request body ~BEGIN~\n".print_r($postData, true)."\n~END~\n", 3, $this->config->getDebugFile()); - + curl_setopt($curl, CURLOPT_VERBOSE, 1); curl_setopt($curl, CURLOPT_STDERR, fopen($this->config->getDebugFile(), 'a')); } else { curl_setopt($curl, CURLOPT_VERBOSE, 0); } - + // obtain the HTTP response headers curl_setopt($curl, CURLOPT_HEADER, 1); - + // Make the request $response = curl_exec($curl); $http_header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE); $http_header = substr($response, 0, $http_header_size); $http_body = substr($response, $http_header_size); $response_info = curl_getinfo($curl); - + // debug HTTP response body if ($this->config->getDebug()) { error_log("[DEBUG] HTTP Response body ~BEGIN~\n".print_r($http_body, true)."\n~END~\n", 3, $this->config->getDebugFile()); } - + // Handle the response if ($response_info['http_code'] == 0) { throw new ApiException("API call to $url timed out: ".serialize($response_info), 0, null, null); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { - // return raw body if response is a file + // return raw body if response is a file if ($responseType == '\SplFileObject') { return array($http_body, $http_header); } - + $data = json_decode($http_body); if (json_last_error() > 0) { // if response is a string $data = $http_body; @@ -240,7 +246,7 @@ class ApiClient } return array($data, $http_header); } - + /** * Return the header 'Accept' based on an array of Accept provided * @@ -258,7 +264,7 @@ class ApiClient return implode(',', $accept); } } - + /** * Return the content type based on an array of content-type provided * diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 981085c63787..96bc8a1b6608 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -27,8 +27,8 @@ */ /** - * NOTE: This class is auto generated by the swagger code generator program. - * https://github.com/swagger-api/swagger-codegen + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen * Do not edit the class manually. */ @@ -48,70 +48,70 @@ class Configuration { private static $_defaultConfiguration = null; - - /** + + /** * Associate array to store API key(s) * * @var string[] */ protected $apiKeys = array(); - + /** * Associate array to store API prefix (e.g. Bearer) * * @var string[] */ protected $apiKeyPrefixes = array(); - - /** + + /** * Username for HTTP basic authentication * * @var string */ protected $username = ''; - + /** * Password for HTTP basic authentication * * @var string */ protected $password = ''; - + /** * The default instance of ApiClient * * @var \{{invokerPackage}}\ApiClient */ protected $defaultHeaders = array(); - + /** * The host * * @var string */ protected $host = '{{basePath}}'; - + /** * Timeout (second) of the HTTP request, by default set to 0, no timeout * - * @var string + * @var string */ protected $curlTimeout = 0; - + /** * User agent of the HTTP request, set to "PHP-Swagger" by default * * @var string */ protected $userAgent = "PHP-Swagger/{{artifactVersion}}"; - + /** * Debug switch (default set to false) * * @var bool */ protected $debug = false; - + /** * Debug file location (log to STDOUT by default) * @@ -126,6 +126,15 @@ class Configuration */ protected $tempFolderPath; + /** + * Indicates if SSL verification should be enabled or disabled. + * + * This is useful if the host uses a self-signed SSL certificate. + * + * @var boolean True if the certificate should be validated, false otherwise. + */ + protected $sslVerification = true; + /** * Constructor */ @@ -133,7 +142,7 @@ class Configuration { $this->tempFolderPath = sys_get_temp_dir(); } - + /** * Sets API key * @@ -147,7 +156,7 @@ class Configuration $this->apiKeys[$apiKeyIdentifier] = $key; return $this; } - + /** * Gets API key * @@ -159,7 +168,7 @@ class Configuration { return isset($this->apiKeys[$apiKeyIdentifier]) ? $this->apiKeys[$apiKeyIdentifier] : null; } - + /** * Sets the prefix for API key (e.g. Bearer) * @@ -173,7 +182,7 @@ class Configuration $this->apiKeyPrefixes[$apiKeyIdentifier] = $prefix; return $this; } - + /** * Gets API key prefix * @@ -185,7 +194,7 @@ class Configuration { return isset($this->apiKeyPrefixes[$apiKeyIdentifier]) ? $this->apiKeyPrefixes[$apiKeyIdentifier] : null; } - + /** * Sets the username for HTTP basic authentication * @@ -198,7 +207,7 @@ class Configuration $this->username = $username; return $this; } - + /** * Gets the username for HTTP basic authentication * @@ -208,7 +217,7 @@ class Configuration { return $this->username; } - + /** * Sets the password for HTTP basic authentication * @@ -221,7 +230,7 @@ class Configuration $this->password = $password; return $this; } - + /** * Gets the password for HTTP basic authentication * @@ -231,7 +240,7 @@ class Configuration { return $this->password; } - + /** * Adds a default header * @@ -245,11 +254,11 @@ class Configuration if (!is_string($headerName)) { throw new \InvalidArgumentException('Header name must be a string.'); } - + $this->defaultHeaders[$headerName] = $headerValue; return $this; } - + /** * Gets the default header * @@ -259,7 +268,7 @@ class Configuration { return $this->defaultHeaders; } - + /** * Deletes a default header * @@ -271,7 +280,7 @@ class Configuration { unset($this->defaultHeaders[$headerName]); } - + /** * Sets the host * @@ -284,7 +293,7 @@ class Configuration $this->host = $host; return $this; } - + /** * Gets the host * @@ -294,7 +303,7 @@ class Configuration { return $this->host; } - + /** * Sets the user agent of the api client * @@ -307,11 +316,11 @@ class Configuration if (!is_string($userAgent)) { throw new \InvalidArgumentException('User-agent must be a string.'); } - + $this->userAgent = $userAgent; return $this; } - + /** * Gets the user agent of the api client * @@ -321,7 +330,7 @@ class Configuration { return $this->userAgent; } - + /** * Sets the HTTP timeout value * @@ -334,11 +343,11 @@ class Configuration if (!is_numeric($seconds) || $seconds < 0) { throw new \InvalidArgumentException('Timeout value must be numeric and a non-negative number.'); } - + $this->curlTimeout = $seconds; return $this; } - + /** * Gets the HTTP timeout value * @@ -348,10 +357,10 @@ class Configuration { return $this->curlTimeout; } - + /** * Sets debug flag - * + * * @param bool $debug Debug flag * * @return Configuration @@ -361,7 +370,7 @@ class Configuration $this->debug = $debug; return $this; } - + /** * Gets the debug flag * @@ -371,7 +380,7 @@ class Configuration { return $this->debug; } - + /** * Sets the debug file * @@ -384,7 +393,7 @@ class Configuration $this->debugFile = $debugFile; return $this; } - + /** * Gets the debug file * @@ -394,7 +403,7 @@ class Configuration { return $this->debugFile; } - + /** * Sets the temp folder path * @@ -407,7 +416,7 @@ class Configuration $this->tempFolderPath = $tempFolderPath; return $this; } - + /** * Gets the temp folder path * @@ -417,7 +426,30 @@ class Configuration { return $this->tempFolderPath; } - + + /** + * Sets if SSL verification should be enabled or disabled + * + * @param boolean $sslVerification True if the certificate should be validated, false otherwise + * + * @return Configuration + */ + public function setSSLVerification($sslVerification) + { + $this->sslVerification = $sslVerification; + return $this; + } + + /** + * Gets if SSL verification should be enabled or disabled + * + * @return boolean True if the certificate should be validated, false otherwise + */ + public function getSSLVerification() + { + return $this->sslVerification; + } + /** * Gets the default configuration instance * @@ -428,10 +460,10 @@ class Configuration if (self::$_defaultConfiguration == null) { self::$_defaultConfiguration = new Configuration(); } - + return self::$_defaultConfiguration; } - + /** * Sets the detault configuration instance * @@ -443,7 +475,7 @@ class Configuration { self::$_defaultConfiguration = $config; } - + /** * Gets the essential information for debugging * @@ -457,8 +489,8 @@ class Configuration $report .= " Swagger Spec Version: {{version}}\n"; $report .= " SDK Package Version: {{artifactVersion}}\n"; $report .= " Temp Folder Path: ".self::getDefaultConfiguration()->getTempFolderPath()."\n"; - + return $report; } - + } From 02a9fe2618dab090b4572c8a0c247f51df96330d Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 16 Oct 2015 10:30:26 +0800 Subject: [PATCH 208/219] Add more test cases for global security --- .../swagger/codegen/DefaultGeneratorTest.java | 33 ++++++++++++++++--- .../test/resources/2_0/globalSecurity.json | 19 +++++++++-- 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java index 2828d8994d72..3ed3b131c85b 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/DefaultGeneratorTest.java @@ -90,7 +90,7 @@ public void testSecurityWithGlobal() throws Exception { gen.opts(clientOptInput); Map> paths = gen.processPaths(swagger.getPaths()); - CodegenSecurity apiKey, petstoreAuth; + CodegenSecurity cs, apiKey, apiKey2, petstoreAuth; // security of "getPetById": api_key CodegenOperation getPetById = findCodegenOperationByOperationId(paths, "getPetById"); @@ -106,16 +106,41 @@ public void testSecurityWithGlobal() throws Exception { assertEquals(petstoreAuth.name, "petstore_auth"); assertEquals(petstoreAuth.type, "oauth2"); - // security of "loginUser": api_key (from global security) + // security of "loginUser": api_key, petstore_auth (from global security) CodegenOperation loginUser = findCodegenOperationByOperationId(paths, "loginUser"); - assertEquals(loginUser.authMethods.size(), 1); - apiKey = loginUser.authMethods.iterator().next(); + assertEquals(loginUser.authMethods.size(), 2); + cs = loginUser.authMethods.get(0); + if ("api_key".equals(cs.name)) { + apiKey = cs; + petstoreAuth = loginUser.authMethods.get(1); + } else { + petstoreAuth = cs; + apiKey = loginUser.authMethods.get(1); + } assertEquals(apiKey.name, "api_key"); assertEquals(apiKey.type, "apiKey"); + assertEquals(petstoreAuth.name, "petstore_auth"); + assertEquals(petstoreAuth.type, "oauth2"); // security of "logoutUser": null (override global security) CodegenOperation logoutUser = findCodegenOperationByOperationId(paths, "logoutUser"); assertNull(logoutUser.authMethods); + + // security of "getUserByName": api_key, api_key2 (override global security) + CodegenOperation getUserByName = findCodegenOperationByOperationId(paths, "getUserByName"); + assertEquals(getUserByName.authMethods.size(), 2); + cs = getUserByName.authMethods.get(0); + if ("api_key".equals(cs.name)) { + apiKey = cs; + apiKey2 = getUserByName.authMethods.get(1); + } else { + apiKey2 = cs; + apiKey = getUserByName.authMethods.get(1); + } + assertEquals(apiKey.name, "api_key"); + assertEquals(apiKey.type, "apiKey"); + assertEquals(apiKey2.name, "api_key2"); + assertEquals(apiKey2.type, "apiKey"); } @Test diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json index 3d1548e769cc..36fa87664aef 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json +++ b/modules/swagger-codegen/src/test/resources/2_0/globalSecurity.json @@ -738,7 +738,13 @@ "400": { "description": "Invalid username supplied" } - } + }, + "security": [ + { + "api_key": [], + "api_key2": [] + } + ] }, "put": { "tags": [ @@ -815,6 +821,11 @@ "name": "api_key", "in": "header" }, + "api_key2": { + "type": "apiKey", + "name": "api_key2", + "in": "query" + }, "petstore_auth": { "type": "oauth2", "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", @@ -827,7 +838,11 @@ }, "security": [ { - "api_key": [] + "api_key": [], + "petstore_auth": [ + "write:pets", + "read:pets" + ] } ], "definitions": { From a1fa0b0834ce433a1f1437802d4d646e8907354d Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 16 Oct 2015 10:47:00 +0800 Subject: [PATCH 209/219] Rebuild Petstore samples --- .../default/src/main/java/io/swagger/client/api/PetApi.java | 4 ++-- .../jersey2/src/main/java/io/swagger/client/api/PetApi.java | 4 ++-- .../src/main/java/io/swagger/client/api/PetApi.java | 2 +- samples/client/petstore/ruby/lib/petstore/api/pet_api.rb | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java index 8715238ae148..8afd143cd91f 100644 --- a/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/default/src/main/java/io/swagger/client/api/PetApi.java @@ -11,7 +11,7 @@ import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:27.235+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-16T10:32:51.872+08:00") public class PetApi { private ApiClient apiClient; @@ -266,7 +266,7 @@ public Pet getPetById (Long petId) throws ApiException { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key" }; diff --git a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java index b979fd081340..4095cb036330 100644 --- a/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/jersey2/src/main/java/io/swagger/client/api/PetApi.java @@ -11,7 +11,7 @@ import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-09T21:30:19.416+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-16T10:40:45.419+08:00") public class PetApi { private ApiClient apiClient; @@ -237,7 +237,7 @@ public Pet getPetById (Long petId) throws ApiException { }; final String contentType = apiClient.selectHeaderContentType(contentTypes); - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key" }; TypeRef returnType = new TypeRef() {}; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java index 596596b935ac..39154cf855eb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/io/swagger/client/api/PetApi.java @@ -290,7 +290,7 @@ private Call getPetByIdCall(Long petId) throws ApiException { final String contentType = apiClient.selectHeaderContentType(contentTypes); headerParams.put("Content-Type", contentType); - String[] authNames = new String[] { "petstore_auth", "api_key" }; + String[] authNames = new String[] { "api_key" }; return apiClient.buildCall(path, "GET", queryParams, postBody, headerParams, formParams, authNames); } diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index a9d30a00147c..26f7482b3848 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -237,7 +237,7 @@ def get_pet_by_id(pet_id, opts = {}) post_body = nil - auth_names = ['petstore_auth', 'api_key'] + auth_names = ['api_key'] result = @api_client.call_api(:GET, path, :header_params => header_params, :query_params => query_params, From 7db67aa192235b8af3d3ce0db08455f694f5da21 Mon Sep 17 00:00:00 2001 From: Nat Luengnaruemitchai Date: Thu, 15 Oct 2015 20:44:20 -0700 Subject: [PATCH 210/219] add library in the additional option --- .../java/io/swagger/codegen/languages/JavaClientCodegen.java | 4 ++++ 1 file changed, 4 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 ec157e6ddff8..934238c3def6 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 @@ -152,6 +152,10 @@ public void processOpts() { this.setSerializableModel(Boolean.valueOf((String)additionalProperties.get(CodegenConstants.SERIALIZABLE_MODEL).toString())); } + if (additionalProperties.containsKey(CodegenConstants.LIBRARY)) { + this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); + } + // need to put back serializableModel (boolean) into additionalProperties as value in additionalProperties is string additionalProperties.put(CodegenConstants.SERIALIZABLE_MODEL, serializableModel); From e0dfc1b43d5c2cb84e6fb39a161fbe6f30e2eede Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 16 Oct 2015 12:02:30 +0800 Subject: [PATCH 211/219] Ruby client: remove trailing slashes from base_url Closes #1399 --- .../resources/ruby/configuration.mustache | 2 +- .../ruby/lib/petstore/configuration.rb | 2 +- .../petstore/ruby/spec/configuration_spec.rb | 25 +++++++++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 samples/client/petstore/ruby/spec/configuration_spec.rb diff --git a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache index e74cc17573cc..0385aaffd838 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/configuration.mustache @@ -138,7 +138,7 @@ module {{moduleName}} end def base_url - url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" + url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') URI.encode(url) end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 008be48ee4da..04479b53db0a 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -138,7 +138,7 @@ def base_path=(base_path) end def base_url - url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}" + url = "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') URI.encode(url) end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb new file mode 100644 index 000000000000..9f86f5602b74 --- /dev/null +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -0,0 +1,25 @@ +require 'spec_helper' + +describe Petstore::Configuration do + let(:config) { Petstore::Configuration.instance } + + before(:each) do + Petstore.configure do |c| + c.host = 'petstore.swagger.io' + c.base_path = 'v2' + end + end + + describe '#base_url' do + it 'should have the default value' do + config.base_url.should == 'http://petstore.swagger.io/v2' + end + + it 'should remove trailing slashes' do + [nil, '', '/', '//'].each do |base_path| + config.base_path = base_path + config.base_url.should == 'http://petstore.swagger.io' + end + end + end +end From 71c5160739f8f2ddb93e1596827bed3f5e152d2a Mon Sep 17 00:00:00 2001 From: cbornet Date: Sun, 11 Oct 2015 00:18:10 +0200 Subject: [PATCH 212/219] add colllectionFormat support to retrofit Fix #1364 --- .../io/swagger/codegen/CodegenParameter.java | 4 +- .../io/swagger/codegen/DefaultCodegen.java | 3 + .../codegen/languages/JavaClientCodegen.java | 1 + .../retrofit/CollectionFormats.mustache | 95 +++++++++++++++++++ .../Java/libraries/retrofit/api.mustache | 4 + .../libraries/retrofit/queryParams.mustache | 2 +- .../io/swagger/client/CollectionFormats.java | 95 +++++++++++++++++++ .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 4 + .../java/io/swagger/client/api/StoreApi.java | 4 + .../java/io/swagger/client/api/UserApi.java | 4 + 11 files changed, 215 insertions(+), 3 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache create mode 100644 samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index 6dd85d10c272..38c70fcc82e9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -7,7 +7,8 @@ public class CodegenParameter { public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, - isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam, isBinary; + isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, + secondaryParam, isBinary, isCollectionFormatMulti; public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; public String jsonSchema; public boolean isEnum; @@ -33,6 +34,7 @@ public CodegenParameter copy() { output.paramName = this.paramName; output.dataType = this.dataType; output.collectionFormat = this.collectionFormat; + output.isCollectionFormatMulti = this.isCollectionFormatMulti; output.description = this.description; output.baseType = this.baseType; output.isFormParam = this.isFormParam; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 840e646b5d82..575f9742f507 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1205,6 +1205,9 @@ public CodegenParameter fromParameter(Parameter param, Set imports) { p._enum = model._enum; p.allowableValues = model.allowableValues; p.collectionFormat = collectionFormat; + if(collectionFormat != null && collectionFormat.equals("multi")) { + p.isCollectionFormatMulti = true; + } p.paramName = toParamName(qp.getName()); if (model.complexType != null) { 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 cdcd15f9a5db..d265e5a72327 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 @@ -218,6 +218,7 @@ public void processOpts() { supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); } else if ("retrofit".equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); + supportingFiles.add(new SupportingFile("CollectionFormats.mustache", invokerFolder, "CollectionFormats.java")); } else { supportingFiles.add(new SupportingFile("TypeRef.mustache", invokerFolder, "TypeRef.java")); } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache new file mode 100644 index 000000000000..5e165a2bd53b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache @@ -0,0 +1,95 @@ +package {{invokerPackage}}; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return String.join(",", params); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return String.join(" ", params); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return String.join("\t", params); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return String.join("|", params); + } + } + +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index b41e18aff47c..dc560e64e4df 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -1,5 +1,9 @@ package {{package}}; +import {{invokerPackage}}.CollectionFormats.*; + +import {{modelPackage}}.*; + import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache index e0a58533e5fa..3c5b1bb7e69d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@Query("{{baseName}}") {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@Query("{{baseName}}") {{#collectionFormat}}{{#isCollectionFormatMulti}}{{{dataType}}}{{/isCollectionFormatMulti}}{{^isCollectionFormatMulti}}{{{collectionFormat.toUpperCase}}}Params{{/isCollectionFormatMulti}}{{/collectionFormat}}{{^collectionFormat}}{{{dataType}}}{{/collectionFormat}} {{paramName}}{{/isQueryParam}} \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java new file mode 100644 index 000000000000..621261891995 --- /dev/null +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java @@ -0,0 +1,95 @@ +package io.swagger.client; + +import java.util.Arrays; +import java.util.List; + +public class CollectionFormats { + + public static class CSVParams { + + protected List params; + + public CSVParams() { + } + + public CSVParams(List params) { + this.params = params; + } + + public CSVParams(String... params) { + this.params = Arrays.asList(params); + } + + public List getParams() { + return params; + } + + public void setParams(List params) { + this.params = params; + } + + @Override + public String toString() { + return String.join(",", params); + } + + } + + public static class SSVParams extends CSVParams { + + public SSVParams() { + } + + public SSVParams(List params) { + super(params); + } + + public SSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return String.join(" ", params); + } + } + + public static class TSVParams extends CSVParams { + + public TSVParams() { + } + + public TSVParams(List params) { + super(params); + } + + public TSVParams(String... params) { + super(params); + } + + @Override + public String toString() { + return String.join("\t", params); + } + } + + public static class PIPESParams extends CSVParams { + + public PIPESParams() { + } + + public PIPESParams(List params) { + super(params); + } + + public PIPESParams(String... params) { + super(params); + } + + @Override + public String toString() { + return String.join("|", params); + } + } + +} diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java index 27a06a7cfc2d..5f09a3edfebf 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/StringUtil.java @@ -1,6 +1,6 @@ package io.swagger.client; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-09-18T14:07:38.326+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2015-10-11T00:10:38.251+02:00") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index f6b29f11a2af..49e1657e0e54 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -1,5 +1,9 @@ package io.swagger.client.api; +import io.swagger.client.CollectionFormats.*; + +import io.swagger.client.model.*; + import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index 16819d04a94d..abdf952631b4 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -1,5 +1,9 @@ package io.swagger.client.api; +import io.swagger.client.CollectionFormats.*; + +import io.swagger.client.model.*; + import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index a5bc4d03477d..f56ad5aabb33 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -1,5 +1,9 @@ package io.swagger.client.api; +import io.swagger.client.CollectionFormats.*; + +import io.swagger.client.model.*; + import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; From 92d1e8a1d92f7439bd2ac2a860aff12aebbc258a Mon Sep 17 00:00:00 2001 From: cbornet Date: Tue, 13 Oct 2015 11:11:52 +0200 Subject: [PATCH 213/219] use StringUtil to format csv --- .../Java/libraries/retrofit/CollectionFormats.mustache | 8 ++++---- .../main/java/io/swagger/client/CollectionFormats.java | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache index 5e165a2bd53b..a549ea59d1c2 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/CollectionFormats.mustache @@ -30,7 +30,7 @@ public class CollectionFormats { @Override public String toString() { - return String.join(",", params); + return StringUtil.join(params.toArray(new String[0]), ","); } } @@ -50,7 +50,7 @@ public class CollectionFormats { @Override public String toString() { - return String.join(" ", params); + return StringUtil.join(params.toArray(new String[0]), " "); } } @@ -69,7 +69,7 @@ public class CollectionFormats { @Override public String toString() { - return String.join("\t", params); + return StringUtil.join( params.toArray(new String[0]), "\t"); } } @@ -88,7 +88,7 @@ public class CollectionFormats { @Override public String toString() { - return String.join("|", params); + return StringUtil.join(params.toArray(new String[0]), "|"); } } diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java index 621261891995..c3cf52575143 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/CollectionFormats.java @@ -30,7 +30,7 @@ public void setParams(List params) { @Override public String toString() { - return String.join(",", params); + return StringUtil.join(params.toArray(new String[0]), ","); } } @@ -50,7 +50,7 @@ public SSVParams(String... params) { @Override public String toString() { - return String.join(" ", params); + return StringUtil.join(params.toArray(new String[0]), " "); } } @@ -69,7 +69,7 @@ public TSVParams(String... params) { @Override public String toString() { - return String.join("\t", params); + return StringUtil.join( params.toArray(new String[0]), "\t"); } } @@ -88,7 +88,7 @@ public PIPESParams(String... params) { @Override public String toString() { - return String.join("|", params); + return StringUtil.join(params.toArray(new String[0]), "|"); } } From 3debd08a32ce943199903371864ac273a66239ea Mon Sep 17 00:00:00 2001 From: cbornet Date: Fri, 16 Oct 2015 12:47:25 +0200 Subject: [PATCH 214/219] remove useless import --- .../src/main/resources/Java/libraries/retrofit/api.mustache | 2 -- .../retrofit/src/main/java/io/swagger/client/api/PetApi.java | 2 -- .../retrofit/src/main/java/io/swagger/client/api/StoreApi.java | 2 -- .../retrofit/src/main/java/io/swagger/client/api/UserApi.java | 2 -- 4 files changed, 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache index dc560e64e4df..84c799d62520 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/api.mustache @@ -2,8 +2,6 @@ package {{package}}; import {{invokerPackage}}.CollectionFormats.*; -import {{modelPackage}}.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java index 49e1657e0e54..1746009aa777 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/PetApi.java @@ -2,8 +2,6 @@ import io.swagger.client.CollectionFormats.*; -import io.swagger.client.model.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java index abdf952631b4..4d6d3aa7c00c 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/StoreApi.java @@ -2,8 +2,6 @@ import io.swagger.client.CollectionFormats.*; -import io.swagger.client.model.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; diff --git a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java index f56ad5aabb33..ff4b45629779 100644 --- a/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit/src/main/java/io/swagger/client/api/UserApi.java @@ -2,8 +2,6 @@ import io.swagger.client.CollectionFormats.*; -import io.swagger.client.model.*; - import retrofit.Callback; import retrofit.http.*; import retrofit.mime.*; From 9ac980298f970670c378523de6088f4d57b4a084 Mon Sep 17 00:00:00 2001 From: Kosta Krauth Date: Fri, 16 Oct 2015 16:45:34 -0400 Subject: [PATCH 215/219] Fix syntax issue when no auth methods defined When no authentication methods are defined, the generated code does not compile due to where the authMethods closing tag is located. Moved the closing tag further down and opening tag further up so that the generated code is correct both when authentication are and aren't present. --- .../resources/Java/libraries/retrofit/ApiClient.mustache | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache index 4046f9f107ca..4df0fce7d893 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/retrofit/ApiClient.mustache @@ -49,16 +49,16 @@ public class ApiClient { for(String authName : authNames) { if (apiAuthorizations.containsKey(authName)) { throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); - } - Interceptor auth;{{#authMethods}} + }{{#authMethods}} + Interceptor auth; if (authName == "{{name}}") { {{#isBasic}} auth = new HttpBasicAuth();{{/isBasic}}{{#isApiKey}} auth = new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}");{{/isApiKey}}{{#isOAuth}} auth = new OAuth(OAuthFlow.{{flow}}, "{{authorizationUrl}}", "{{tokenUrl}}", "{{#scopes}}{{^-first}}, {{/-first}}{{this}}{{/scopes}}");{{/isOAuth}} - } else {{/authMethods}}{ + } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } - apiAuthorizations.put(authName, auth); + apiAuthorizations.put(authName, auth);{{/authMethods}} } addAuthsToOkClient(okClient); } From 6477a27579fac9b8eb32a5ac62c7adf0abbffc52 Mon Sep 17 00:00:00 2001 From: Nick Bruno Date: Fri, 16 Oct 2015 21:24:17 -0400 Subject: [PATCH 216/219] Update SpringMVC template to include Authorization annotations --- .../src/main/resources/JavaSpringMVC/api.mustache | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache index 695d1c5525b6..6eb6358a7026 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/api.mustache @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -35,7 +37,13 @@ import static org.springframework.http.MediaType.*; public class {{classname}} { {{#operation}} - @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { + {{#authMethods}}@Authorization(value = "{{name}}"{{#isOAuth}}, scopes = { + {{#scopes}}@AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{#hasMore}}, + {{/hasMore}}{{/scopes}} + }{{/isOAuth}}){{#hasMore}}, + {{/hasMore}}{{/authMethods}} + }{{/hasAuthMethods}}) @ApiResponses(value = { {{#responses}} @ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}},{{/hasMore}}{{/responses}} }) @RequestMapping(value = "{{path}}", From 7bbb883a001cdf1ffe8a271a4c78b34c5d3380c9 Mon Sep 17 00:00:00 2001 From: Nick Bruno Date: Fri, 16 Oct 2015 21:25:54 -0400 Subject: [PATCH 217/219] Generate JAXRS and SpringMVC samples to demo Authorization annotations --- samples/server/petstore/jaxrs/README.md | 8 +- .../gen/java/io/swagger/api/ApiException.java | 2 +- .../java/io/swagger/api/ApiOriginFilter.java | 2 +- .../io/swagger/api/ApiResponseMessage.java | 2 +- .../io/swagger/api/NotFoundException.java | 2 +- .../src/gen/java/io/swagger/api/PetApi.java | 85 ++++++++++++++----- .../java/io/swagger/api/PetApiService.java | 2 +- .../src/gen/java/io/swagger/api/StoreApi.java | 24 +++--- .../java/io/swagger/api/StoreApiService.java | 2 +- .../src/gen/java/io/swagger/api/UserApi.java | 34 ++++---- .../java/io/swagger/api/UserApiService.java | 2 +- .../gen/java/io/swagger/model/Category.java | 2 +- .../src/gen/java/io/swagger/model/Order.java | 2 +- .../src/gen/java/io/swagger/model/Pet.java | 2 +- .../src/gen/java/io/swagger/model/Tag.java | 2 +- .../src/gen/java/io/swagger/model/User.java | 2 +- .../java/io/swagger/api/ApiException.java | 2 +- .../java/io/swagger/api/ApiOriginFilter.java | 2 +- .../io/swagger/api/ApiResponseMessage.java | 2 +- .../io/swagger/api/NotFoundException.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 69 ++++++++++++--- .../main/java/io/swagger/api/StoreApi.java | 16 ++-- .../src/main/java/io/swagger/api/UserApi.java | 16 ++-- .../swagger/configuration/SwaggerConfig.java | 2 +- .../configuration/SwaggerUiConfiguration.java | 2 +- .../swagger/configuration/WebApplication.java | 2 +- .../configuration/WebMvcConfiguration.java | 2 +- .../main/java/io/swagger/model/Category.java | 2 +- .../src/main/java/io/swagger/model/Order.java | 2 +- .../src/main/java/io/swagger/model/Pet.java | 2 +- .../src/main/java/io/swagger/model/Tag.java | 2 +- .../src/main/java/io/swagger/model/User.java | 2 +- 32 files changed, 196 insertions(+), 106 deletions(-) diff --git a/samples/server/petstore/jaxrs/README.md b/samples/server/petstore/jaxrs/README.md index 3ffa01fb2571..3f0809d4734d 100644 --- a/samples/server/petstore/jaxrs/README.md +++ b/samples/server/petstore/jaxrs/README.md @@ -1,10 +1,8 @@ # Swagger generated server ## Overview -This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This -is an example of building a swagger-enabled scalatra server. +is an example of building a swagger-enabled JAX-RS server. -This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: - -[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file +This example uses the [JAX-RS](https://jax-rs-spec.java.net/) framework. diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java index 300636842ba1..12cb749d46ee 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java index e7ad9b521ac4..e82f34c2b620 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class ApiOriginFilter implements javax.servlet.Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java index 6d6958c1c907..8a36255be29b 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java index c3eab326e644..bb483dfc8780 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java index f583f1e64cfc..4f440e006710 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApi.java @@ -26,7 +26,7 @@ @io.swagger.annotations.Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class PetApi { private final PetApiService delegate = PetApiServiceFactory.getPetApi(); @@ -35,35 +35,50 @@ public class PetApi { @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) public Response updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { - return delegate.updatePet(body); + return delegate.updatePet(body); } @POST @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) public Response addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { - return delegate.addPet(body); + return delegate.addPet(body); } @GET @Path("/findByStatus") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") + @io.swagger.annotations.ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @@ -71,13 +86,18 @@ public Response addPet(@ApiParam(value = "Pet object that needs to be added to t public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) throws NotFoundException { - return delegate.findPetsByStatus(status); + return delegate.findPetsByStatus(status); } @GET @Path("/findByTags") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") + @io.swagger.annotations.ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class, responseContainer = "List"), @@ -85,29 +105,40 @@ public Response findPetsByStatus(@ApiParam(value = "Status values that need to b public Response findPetsByTags(@ApiParam(value = "Tags to filter by") @QueryParam("tags") List tags) throws NotFoundException { - return delegate.findPetsByTags(tags); + return delegate.findPetsByTags(tags); } @GET @Path("/{petId}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) + @io.swagger.annotations.ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { + @io.swagger.annotations.Authorization(value = "api_key"), + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Pet.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class) }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) public Response getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("petId") Long petId) throws NotFoundException { - return delegate.getPetById(petId); + return delegate.getPetById(petId); } @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @@ -115,26 +146,36 @@ public Response updatePetWithForm(@ApiParam(value = "ID of pet that needs to be @ApiParam(value = "Updated name of the pet" )@FormParam("name") String name, @ApiParam(value = "Updated status of the pet" )@FormParam("status") String status) throws NotFoundException { - return delegate.updatePetWithForm(petId,name,status); + return delegate.updatePetWithForm(petId,name,status); } @DELETE @Path("/{petId}") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) public Response deletePet(@ApiParam(value = "Pet id to delete",required=true ) @PathParam("petId") Long petId, @ApiParam(value = "" )@HeaderParam("api_key") String apiKey) throws NotFoundException { - return delegate.deletePet(petId,apiKey); + return delegate.deletePet(petId,apiKey); } @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) + @io.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @io.swagger.annotations.Authorization(value = "petstore_auth", scopes = { + @io.swagger.annotations.AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @io.swagger.annotations.AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @@ -143,7 +184,7 @@ public Response uploadFile(@ApiParam(value = "ID of pet to update",required=true @FormDataParam("file") InputStream inputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) throws NotFoundException { - return delegate.uploadFile(petId,additionalMetadata,fileDetail); + return delegate.uploadFile(petId,additionalMetadata,fileDetail); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java index 708dc647f911..501f5aeca33e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/PetApiService.java @@ -18,7 +18,7 @@ import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public abstract class PetApiService { public abstract Response updatePet(Pet body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java index a487439cb3f9..3ff3886e0cbe 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApi.java @@ -26,7 +26,7 @@ @io.swagger.annotations.Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class StoreApi { private final StoreApiService delegate = StoreApiServiceFactory.getStoreApi(); @@ -35,13 +35,15 @@ public class StoreApi { @Path("/inventory") @Produces({ "application/json", "application/xml" }) - @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map") + @io.swagger.annotations.ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @io.swagger.annotations.Authorization(value = "api_key") + }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Integer.class, responseContainer = "Map") }) public Response getInventory() throws NotFoundException { - return delegate.getInventory(); + return delegate.getInventory(); } @POST @Path("/order") @@ -55,7 +57,7 @@ public Response getInventory() public Response placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { - return delegate.placeOrder(body); + return delegate.placeOrder(body); } @GET @Path("/order/{orderId}") @@ -63,15 +65,15 @@ public Response placeOrder(@ApiParam(value = "order placed for purchasing the pe @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Order.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class) }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Order.class) }) public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { - return delegate.getOrderById(orderId); + return delegate.getOrderById(orderId); } @DELETE @Path("/order/{orderId}") @@ -79,13 +81,13 @@ public Response getOrderById(@ApiParam(value = "ID of pet that needs to be fetch @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 404, message = "Order not found", response = Void.class) }) public Response deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathParam("orderId") String orderId) throws NotFoundException { - return delegate.deleteOrder(orderId); + return delegate.deleteOrder(orderId); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java index 955d640d1b5f..4f39bff11419 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/StoreApiService.java @@ -18,7 +18,7 @@ import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public abstract class StoreApiService { public abstract Response getInventory() diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java index d7bde1b17534..94b8e247e09e 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApi.java @@ -26,7 +26,7 @@ @io.swagger.annotations.Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class UserApi { private final UserApiService delegate = UserApiServiceFactory.getUserApi(); @@ -41,7 +41,7 @@ public class UserApi { public Response createUser(@ApiParam(value = "Created user object" ) User body) throws NotFoundException { - return delegate.createUser(body); + return delegate.createUser(body); } @POST @Path("/createWithArray") @@ -53,7 +53,7 @@ public Response createUser(@ApiParam(value = "Created user object" ) User body) public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { - return delegate.createUsersWithArrayInput(body); + return delegate.createUsersWithArrayInput(body); } @POST @Path("/createWithList") @@ -65,7 +65,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object public Response createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) throws NotFoundException { - return delegate.createUsersWithListInput(body); + return delegate.createUsersWithListInput(body); } @GET @Path("/login") @@ -80,7 +80,7 @@ public Response createUsersWithListInput(@ApiParam(value = "List of user object" public Response loginUser(@ApiParam(value = "The user name for login") @QueryParam("username") String username, @ApiParam(value = "The password for login in clear text") @QueryParam("password") String password) throws NotFoundException { - return delegate.loginUser(username,password); + return delegate.loginUser(username,password); } @GET @Path("/logout") @@ -92,7 +92,7 @@ public Response loginUser(@ApiParam(value = "The user name for login") @QueryPar public Response logoutUser() throws NotFoundException { - return delegate.logoutUser(); + return delegate.logoutUser(); } @GET @Path("/{username}") @@ -100,15 +100,15 @@ public Response logoutUser() @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Get user by user name", notes = "", response = User.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class), - @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = User.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class) }) + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), + + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = User.class) }) - public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathParam("username") String username) + public Response getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing.",required=true ) @PathParam("username") String username) throws NotFoundException { - return delegate.getUserByName(username); + return delegate.getUserByName(username); } @PUT @Path("/{username}") @@ -116,14 +116,14 @@ public Response getUserByName(@ApiParam(value = "The name that needs to be fetch @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) public Response updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathParam("username") String username, @ApiParam(value = "Updated user object" ) User body) throws NotFoundException { - return delegate.updateUser(username,body); + return delegate.updateUser(username,body); } @DELETE @Path("/{username}") @@ -131,13 +131,13 @@ public Response updateUser(@ApiParam(value = "name that need to be deleted",requ @Produces({ "application/json", "application/xml" }) @io.swagger.annotations.ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @io.swagger.annotations.ApiResponses(value = { - @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class), + @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), - @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class) }) + @io.swagger.annotations.ApiResponse(code = 404, message = "User not found", response = Void.class) }) public Response deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathParam("username") String username) throws NotFoundException { - return delegate.deleteUser(username); + return delegate.deleteUser(username); } } diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java index e838a00e2829..16b0e676ec51 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/api/UserApiService.java @@ -18,7 +18,7 @@ import javax.ws.rs.core.Response; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public abstract class UserApiService { public abstract Response createUser(User body) diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java index 57666c8444b8..312ece05b725 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Category.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java index 99b3c758473e..ae633dc2e859 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java index 0b01a065022e..d4a653c1bc67 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java index 935e04025c87..ff748500a0b4 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/Tag.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java index 6d6fb0c1d94e..679c39e879e6 100644 --- a/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java +++ b/samples/server/petstore/jaxrs/src/gen/java/io/swagger/model/User.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-08-23T23:29:16.812-07:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JaxRSServerCodegen", date = "2015-10-16T21:16:23.957-04:00") public class User { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java index f761d3871daf..b9eb20d65e53 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java index 432c49d5d5cd..9e2354cf2c56 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java index c606c9398f49..fc4136a37a21 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java index 9c93b025ef93..04e28c547541 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index ae731880a173..73849a0944ea 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -30,15 +32,20 @@ @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class PetApi { - @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) + @ApiOperation(value = "Update an existing pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { - @ApiResponse(code = 405, message = "Validation exception"), + @ApiResponse(code = 400, message = "Invalid ID supplied"), @ApiResponse(code = 404, message = "Pet not found"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 405, message = "Validation exception") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, consumes = { "application/json", "application/xml" }, @@ -54,7 +61,12 @@ public ResponseEntity updatePet( - @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) + @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "", @@ -72,7 +84,12 @@ public ResponseEntity addPet( - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List") + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid status value") }) @@ -91,7 +108,12 @@ public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status valu - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List") + @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation"), @ApiResponse(code = 400, message = "Invalid tag value") }) @@ -110,11 +132,17 @@ public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filte - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class) + @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { + @Authorization(value = "api_key"), + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { - @ApiResponse(code = 404, message = "Pet not found"), @ApiResponse(code = 200, message = "successful operation"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Pet not found") }) @RequestMapping(value = "/{petId}", produces = { "application/json", "application/xml" }, @@ -130,7 +158,12 @@ public ResponseEntity getPetById( - @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) + @ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/{petId}", @@ -158,7 +191,12 @@ public ResponseEntity updatePetWithForm( - @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class) + @ApiOperation(value = "Deletes a pet", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value") }) @RequestMapping(value = "/{petId}", @@ -180,7 +218,12 @@ public ResponseEntity deletePet( - @ApiOperation(value = "uploads an image", notes = "", response = Void.class) + @ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @Authorization(value = "petstore_auth", scopes = { + @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), + @AuthorizationScope(scope = "read:pets", description = "read your pets") + }) + }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 577052883c0e..802a44b0922a 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -30,11 +32,13 @@ @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class StoreApi { - @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map") + @ApiOperation(value = "Returns pet inventories by status", notes = "Returns a map of status codes to quantities", response = Integer.class, responseContainer = "Map", authorizations = { + @Authorization(value = "api_key") + }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) @RequestMapping(value = "/inventory", @@ -70,9 +74,9 @@ public ResponseEntity placeOrder( @ApiOperation(value = "Find purchase order by ID", notes = "For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions", response = Order.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "Order not found"), @ApiResponse(code = 200, message = "successful operation"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", produces = { "application/json", "application/xml" }, @@ -90,8 +94,8 @@ public ResponseEntity getOrderById( @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "Order not found"), - @ApiResponse(code = 400, message = "Invalid ID supplied") }) + @ApiResponse(code = 400, message = "Invalid ID supplied"), + @ApiResponse(code = 404, message = "Order not found") }) @RequestMapping(value = "/order/{orderId}", produces = { "application/json", "application/xml" }, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 6a68c27ae39f..45173ae4f332 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -10,6 +10,8 @@ import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; +import io.swagger.annotations.Authorization; +import io.swagger.annotations.AuthorizationScope; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -30,7 +32,7 @@ @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class UserApi { @@ -128,9 +130,9 @@ public ResponseEntity logoutUser() @ApiOperation(value = "Get user by user name", notes = "", response = User.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "User not found"), @ApiResponse(code = 200, message = "successful operation"), - @ApiResponse(code = 400, message = "Invalid username supplied") }) + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", produces = { "application/json", "application/xml" }, @@ -148,8 +150,8 @@ public ResponseEntity getUserByName( @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 400, message = "Invalid user supplied") }) + @ApiResponse(code = 400, message = "Invalid user supplied"), + @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", produces = { "application/json", "application/xml" }, @@ -171,8 +173,8 @@ public ResponseEntity updateUser( @ApiOperation(value = "Delete user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { - @ApiResponse(code = 404, message = "User not found"), - @ApiResponse(code = 400, message = "Invalid username supplied") }) + @ApiResponse(code = 400, message = "Invalid username supplied"), + @ApiResponse(code = 404, message = "User not found") }) @RequestMapping(value = "/{username}", produces = { "application/json", "application/xml" }, diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java index 58564e526261..cf98a04f667d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerConfig.java @@ -18,7 +18,7 @@ @EnableSwagger2 //Loads the spring beans required by the framework @PropertySource("classpath:swagger.properties") @Import(SwaggerUiConfiguration.class) -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class SwaggerConfig { @Bean ApiInfo apiInfo() { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java index ead813573312..fed9a6a40bb5 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/SwaggerUiConfiguration.java @@ -8,7 +8,7 @@ @Configuration @EnableWebMvc -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class SwaggerUiConfiguration extends WebMvcConfigurerAdapter { private static final String[] SERVLET_RESOURCE_LOCATIONS = { "/" }; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java index 3c42b3f838ae..594ac497275f 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebApplication.java @@ -2,7 +2,7 @@ import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class WebApplication extends AbstractAnnotationConfigDispatcherServletInitializer { @Override diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java index 4c973c218889..7873af49169d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/configuration/WebMvcConfiguration.java @@ -3,7 +3,7 @@ import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class WebMvcConfiguration extends WebMvcConfigurationSupport { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java index d023688b5e50..349904a1b3ac 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Category.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java index 87b8633767a5..68e95b043806 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Order.java @@ -7,7 +7,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class Order { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java index 5f4de45616e0..0f526087a96e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Pet.java @@ -9,7 +9,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java index 6b2b0e6c1163..f552fdbe5576 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/Tag.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java index 97044d2a1e7b..d1a0dc327a7d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/model/User.java @@ -6,7 +6,7 @@ @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-09-30T16:27:59.075+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringMVCServerCodegen", date = "2015-10-16T21:16:24.594-04:00") public class User { private Long id = null; From b82333aea4309019245d92bdc483d45e2bd996fd Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 17 Oct 2015 16:30:19 +0800 Subject: [PATCH 218/219] Add support for top-level consumes and produces This reverts commit 0b4b5e8839cd3f447fde86e4aa2a8db8fc2985f6. --- .../io/swagger/codegen/CodegenConfig.java | 2 + .../io/swagger/codegen/DefaultCodegen.java | 52 +++++-- .../io/swagger/codegen/DefaultGenerator.java | 2 +- .../codegen/languages/SwiftCodegen.java | 6 +- .../java/io/swagger/codegen/CodegenTest.java | 48 +++++++ .../2_0/globalConsumesAndProduces.json | 130 ++++++++++++++++++ 6 files changed, 229 insertions(+), 11 deletions(-) create mode 100644 modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java index 10d7363cc35a..b50147a6ff3e 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenConfig.java @@ -67,6 +67,8 @@ public interface CodegenConfig { CodegenModel fromModel(String name, Model model, Map allDefinitions); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions, Swagger swagger); + CodegenOperation fromOperation(String resourcePath, String httpMethod, Operation operation, Map definitions); List fromSecurity(Map schemes); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 575f9742f507..5a7a5f9506c7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -867,8 +867,12 @@ private Response findMethodResponse(Map responses) { } return responses.get(code); } - + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + return fromOperation(path, httpMethod, operation, definitions, null); + } + + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { CodegenOperation op = CodegenModelFactory.newInstance(CodegenModelType.OPERATION); Set imports = new HashSet(); op.vendorExtensions = operation.getVendorExtensions(); @@ -904,15 +908,32 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.summary = escapeText(operation.getSummary()); op.notes = escapeText(operation.getDescription()); op.tags = operation.getTags(); - - if (operation.getConsumes() != null && operation.getConsumes().size() > 0) { + op.hasConsumes = false; + op.hasProduces = false; + + List consumes = new ArrayList(); + if (operation.getConsumes() != null) { + if (operation.getConsumes().size() > 0) { + // use consumes defined in the operation + consumes = operation.getConsumes(); + } else { + // empty list, do nothing to override global setting + } + } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { + // use consumes defined globally + consumes = swagger.getConsumes(); + LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + } + + // if "consumes" is defined (per operation or using global definition) + if (consumes != null && consumes.size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : operation.getConsumes()) { + for (String key : consumes) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getConsumes().size()) { + if (count < consumes.size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); @@ -923,14 +944,29 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation op.hasConsumes = true; } - if (operation.getProduces() != null && operation.getProduces().size() > 0) { + List produces = new ArrayList(); + if (operation.getProduces() != null) { + if (operation.getProduces().size() > 0) { + // use produces defined in the operation + produces = operation.getProduces(); + } else { + // empty list, do nothing to override global setting + } + } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { + // use produces defined globally + produces = swagger.getProduces(); + LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + } + + // if "produces" is defined (per operation or using global definition) + if (produces != null && produces.size() > 0) { List> c = new ArrayList>(); int count = 0; - for (String key : operation.getProduces()) { + for (String key : produces) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getProduces().size()) { + if (count < produces.size()) { mediaType.put("hasMore", "true"); } else { mediaType.put("hasMore", null); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java index 6fc8eecd045b..e85adfed97fa 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultGenerator.java @@ -471,7 +471,7 @@ public void processOperation(String resourcePath, String httpMethod, Operation o for (String tag : tags) { CodegenOperation co = null; try { - co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions()); + co = config.fromOperation(resourcePath, httpMethod, operation, swagger.getDefinitions(), swagger); co.tags = new ArrayList(); co.tags.add(sanitizeTag(tag)); config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 55c3864adb7d..9bb1dfd61d47 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -1,9 +1,11 @@ package io.swagger.codegen.languages; import com.google.common.base.Predicate; + import com.google.common.collect.Iterators; import com.google.common.collect.Lists; import io.swagger.codegen.*; +import io.swagger.models.Swagger; import io.swagger.models.Model; import io.swagger.models.Operation; import io.swagger.models.parameters.HeaderParameter; @@ -256,7 +258,7 @@ public String toApiName(String name) { } @Override - public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions) { + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, Map definitions, Swagger swagger) { path = normalizePath(path); List parameters = operation.getParameters(); parameters = Lists.newArrayList(Iterators.filter(parameters.iterator(), new Predicate() { @@ -266,7 +268,7 @@ public boolean apply(@Nullable Parameter parameter) { } })); operation.setParameters(parameters); - return super.fromOperation(path, httpMethod, operation, definitions); + return super.fromOperation(path, httpMethod, operation, definitions, swagger); } private static String normalizePath(String path) { diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java index ee70b427bfdf..0fa8953e7bf5 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/CodegenTest.java @@ -139,4 +139,52 @@ public void binaryDataTest() { Assert.assertTrue(op.bodyParam.isBinary); Assert.assertTrue(op.responses.get(0).isBinary); } + + @Test(description = "use operation consumes and produces") + public void localConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/localConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/json"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 1); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/json"); + } + + @Test(description = "use spec consumes and produces") + public void globalConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/globalConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertTrue(op.hasConsumes); + Assert.assertEquals(op.consumes.size(), 1); + Assert.assertEquals(op.consumes.get(0).get("mediaType"), "application/global_consumes"); + Assert.assertTrue(op.hasProduces); + Assert.assertEquals(op.produces.size(), 1); + Assert.assertEquals(op.produces.get(0).get("mediaType"), "application/global_produces"); + } + + @Test(description = "use operation consumes and produces (reset in operation with empty array)") + public void localResetConsumesAndProducesTest() { + final Swagger model = new SwaggerParser().read("src/test/resources/2_0/globalConsumesAndProduces.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + final String path = "/tests/localResetConsumesAndProduces"; + final Operation p = model.getPaths().get(path).getGet(); + CodegenOperation op = codegen.fromOperation(path, "get", p, model.getDefinitions(), model); + + Assert.assertNotNull(op); + Assert.assertFalse(op.hasConsumes); + Assert.assertNull(op.consumes); + Assert.assertFalse(op.hasProduces); + Assert.assertNull(op.produces); + + } } diff --git a/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json new file mode 100644 index 000000000000..520218ed707e --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/globalConsumesAndProduces.json @@ -0,0 +1,130 @@ +{ + "swagger": "2.0", + "info": { + "description": "Spec for testing global consumes and produces", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://swagger.io/terms/", + "contact": { + "email": "apiteam@swagger.io" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "consumes": ["application/global_consumes"], + "produces": ["application/global_produces"], + "schemes": [ + "http" + ], + "paths": { + "/tests/localConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with local consumes and produces", + "description": "", + "operationId": "localConsumesAndProduces", + "produces": [ + "application/json" + ], + "consumes": [ + "application/json" + ], + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "/tests/globalConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with global consumes and produces", + "description": "", + "operationId": "globalConsumesAndProduces", + "parameters": [ + ], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + }, + "/tests/localResetConsumesAndProduces": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with local consumes and produces set to empty (reset)", + "description": "", + "operationId": "localResetConsumesAndProduces", + "parameters": [ + ], + "consumes": [], + "produces": [], + "responses": { + "200": { + "description": "successful operation. Returning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + } + + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + }, + "definitions": { + "CustomModel": { + "required": [ + "id" + ], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "example": "doggie" + } + } + } + } +} From e8fbdaabe3171776b648e868c42d737f0a92576c Mon Sep 17 00:00:00 2001 From: wing328 Date: Sat, 17 Oct 2015 16:44:55 +0800 Subject: [PATCH 219/219] replace tabs with spaces --- .../io/swagger/codegen/DefaultCodegen.java | 36 +++++++++---------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 5a7a5f9506c7..2a666c076277 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -913,16 +913,16 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation List consumes = new ArrayList(); if (operation.getConsumes() != null) { - if (operation.getConsumes().size() > 0) { - // use consumes defined in the operation - consumes = operation.getConsumes(); - } else { - // empty list, do nothing to override global setting - } + if (operation.getConsumes().size() > 0) { + // use consumes defined in the operation + consumes = operation.getConsumes(); + } else { + // empty list, do nothing to override global setting + } } else if (swagger != null && swagger.getConsumes() != null && swagger.getConsumes().size() > 0) { - // use consumes defined globally - consumes = swagger.getConsumes(); - LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); + // use consumes defined globally + consumes = swagger.getConsumes(); + LOGGER.debug("No consumes defined in operation. Using global consumes (" + swagger.getConsumes() + ") for " + op.operationId); } // if "consumes" is defined (per operation or using global definition) @@ -946,16 +946,16 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation List produces = new ArrayList(); if (operation.getProduces() != null) { - if (operation.getProduces().size() > 0) { - // use produces defined in the operation - produces = operation.getProduces(); - } else { - // empty list, do nothing to override global setting - } + if (operation.getProduces().size() > 0) { + // use produces defined in the operation + produces = operation.getProduces(); + } else { + // empty list, do nothing to override global setting + } } else if (swagger != null && swagger.getProduces() != null && swagger.getProduces().size() > 0) { - // use produces defined globally - produces = swagger.getProduces(); - LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); + // use produces defined globally + produces = swagger.getProduces(); + LOGGER.debug("No produces defined in operation. Using global produces (" + swagger.getProduces() + ") for " + op.operationId); } // if "produces" is defined (per operation or using global definition)