From 99842f646f90bdf69fb70a4cc1494421827a56ec Mon Sep 17 00:00:00 2001 From: David Bartle Date: Mon, 4 Jan 2016 20:38:07 -0800 Subject: [PATCH 01/47] more flexible perl module naming - No more presuming 'WWW::' is at the beginning (default is now "WWW::SwaggerClient" vs "SwaggerClient" in order to accomodate) - Test that module names Like::This write to the filesystem and in the mustache templates properly --- .gitignore | 2 + bin/perl-petstore.sh | 3 + .../codegen/languages/PerlClientCodegen.java | 24 +++-- .../main/resources/perl/ApiClient.mustache | 24 ++--- .../main/resources/perl/ApiFactory.mustache | 22 ++--- .../src/main/resources/perl/AutoDoc.mustache | 6 +- .../main/resources/perl/BaseObject.mustache | 2 +- .../resources/perl/Configuration.mustache | 2 +- .../src/main/resources/perl/README.mustache | 26 ++--- .../src/main/resources/perl/Role.mustache | 36 +++---- .../src/main/resources/perl/api.mustache | 8 +- .../resources/perl/autodoc.script.mustache | 4 +- .../src/main/resources/perl/object.mustache | 2 +- samples/client/petstore/perl/README.md | 4 +- .../perl/lib/WWW/SwaggerClient/ApiClient.pm | 14 +-- .../perl/lib/WWW/SwaggerClient/ApiFactory.pm | 4 +- .../perl/lib/WWW/SwaggerClient/Role.pm | 12 +-- .../lib/WWW/SwaggerClient/Role/AutoDoc.pm | 2 +- .../petstore/perl/t/05_long_module_name.t | 96 +++++++++++++++++++ 19 files changed, 200 insertions(+), 93 deletions(-) create mode 100644 samples/client/petstore/perl/t/05_long_module_name.t diff --git a/.gitignore b/.gitignore index 02ecb7220cd..15dbdc7db0d 100644 --- a/.gitignore +++ b/.gitignore @@ -55,6 +55,8 @@ samples/client/petstore/php/SwaggerClient-php/vendor/ samples/client/petstore/silex/SwaggerServer/composer.lock samples/client/petstore/silex/SwaggerServer/venodr/ +samples/client/petstore/perl/deep_module_test/ + samples/client/petstore/python/.projectile samples/client/petstore/python/.venv/ diff --git a/bin/perl-petstore.sh b/bin/perl-petstore.sh index 64d684e9ec8..b2eb1753d67 100755 --- a/bin/perl-petstore.sh +++ b/bin/perl-petstore.sh @@ -26,6 +26,9 @@ 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" +# complex module name used for testing ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l perl -o samples/client/petstore/perl" java $JAVA_OPTS -jar $executable $ags + +java $JAVA_OPTS -jar $executable $ags --additional-properties moduleName=Something::Deep -o samples/client/petstore/perl/deep_module_test diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java index 4f8a1fb2a9f..421c72f80d6 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PerlClientCodegen.java @@ -20,7 +20,8 @@ import org.apache.commons.lang.StringUtils; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; public static final String MODULE_VERSION = "moduleVersion"; - protected String moduleName = "SwaggerClient"; + protected String moduleName = "WWW::SwaggerClient"; + protected String modulePathPart = moduleName.replaceAll("::",String.valueOf(File.separatorChar)); protected String moduleVersion = "1.0.0"; public PerlClientCodegen() { @@ -72,7 +73,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "object"); cliOptions.clear(); - cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase).").defaultValue("SwaggerClient")); + cliOptions.add(new CliOption(MODULE_NAME, "Perl module name (convention: CamelCase or Long::Module).").defaultValue("SwaggerClient")); cliOptions.add(new CliOption(MODULE_VERSION, "Perl module version.").defaultValue("1.0.0")); cliOptions.add(CliOption.newBoolean(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); @@ -94,15 +95,16 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { if (additionalProperties.containsKey(MODULE_NAME)) { setModuleName((String) additionalProperties.get(MODULE_NAME)); + setModulePathPart(moduleName.replaceAll("::",String.valueOf(File.separatorChar))); } else { additionalProperties.put(MODULE_NAME, moduleName); } - supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiClient.pm")); - supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Configuration.pm")); - supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiFactory.pm")); - supportingFiles.add(new SupportingFile("Role.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Role.pm")); - supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/WWW/" + moduleName + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiClient.pm")); + supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Configuration.pm")); + supportingFiles.add(new SupportingFile("ApiFactory.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "ApiFactory.pm")); + supportingFiles.add(new SupportingFile("Role.mustache", ("lib/" + modulePathPart).replace('/', File.separatorChar), "Role.pm")); + supportingFiles.add(new SupportingFile("AutoDoc.mustache", ("lib/" + modulePathPart + "/Role").replace('/', File.separatorChar), "AutoDoc.pm")); supportingFiles.add(new SupportingFile("autodoc.script.mustache", "bin", "autodoc")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } @@ -129,12 +131,12 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return (outputFolder + "/lib/WWW/" + moduleName + apiPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/" + modulePathPart + apiPackage()).replace('/', File.separatorChar); } @Override public String modelFileFolder() { - return (outputFolder + "/lib/WWW/" + moduleName + modelPackage()).replace('/', File.separatorChar); + return (outputFolder + "/lib/" + modulePathPart + modelPackage()).replace('/', File.separatorChar); } @Override @@ -251,6 +253,10 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { this.moduleName = moduleName; } + public void setModulePathPart(String modulePathPart) { + this.modulePathPart = modulePathPart; + } + public void setModuleVersion(String moduleVersion) { this.moduleVersion = moduleVersion; } diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache index 4d7d5bb7088..401a33eddad 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::ApiClient; +package {{moduleName}}::ApiClient; use strict; use warnings; @@ -18,7 +18,7 @@ use Log::Any qw($log); use Carp; use Module::Runtime qw(use_module); -use WWW::{{moduleName}}::Configuration; +use {{moduleName}}::Configuration; use base 'Class::Singleton'; @@ -34,7 +34,7 @@ sub _new_instance return bless \%args, $class; } -sub _cfg {'WWW::{{moduleName}}::Configuration'} +sub _cfg {'{{moduleName}}::Configuration'} # Set the user agent of the API client # @@ -119,8 +119,8 @@ sub call_api { else { } - $self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout); - $self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent); + $self->{ua}->timeout($self->{http_timeout} || ${{moduleName}}::Configuration::http_timeout); + $self->{ua}->agent($self->{http_user_agent} || ${{moduleName}}::Configuration::http_user_agent); $log->debugf("REQUEST: %s", $_request->as_string); my $_response = $self->{ua}->request($_request); @@ -243,7 +243,7 @@ sub deserialize } elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) { return $data; } else { # model - my $_instance = use_module("WWW::{{moduleName}}::Object::$class")->new; + my $_instance = use_module("{{moduleName}}::Object::$class")->new; if (ref $data eq "HASH") { return $_instance->from_hash($data); } else { # string, need to json decode first @@ -294,11 +294,11 @@ sub get_api_key_with_prefix { my ($self, $key_name) = @_; - my $api_key = $WWW::{{moduleName}}::Configuration::api_key->{$key_name}; + my $api_key = ${{moduleName}}::Configuration::api_key->{$key_name}; return unless $api_key; - my $prefix = $WWW::{{moduleName}}::Configuration::api_key_prefix->{$key_name}; + my $prefix = ${{moduleName}}::Configuration::api_key_prefix->{$key_name}; return $prefix ? "$prefix $api_key" : $api_key; } @@ -329,11 +329,11 @@ sub update_params_for_auth { if ($api_key) { $query_params->{'{{keyParamName}}'} = $api_key; }{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}} - if ($WWW::{{moduleName}}::Configuration::username || $WWW::{{moduleName}}::Configuration::password) { - $header_params->{'Authorization'} = 'Basic ' . encode_base64($WWW::{{moduleName}}::Configuration::username . ":" . $WWW::{{moduleName}}::Configuration::password); + if (${{moduleName}}::Configuration::username || ${{moduleName}}::Configuration::password) { + $header_params->{'Authorization'} = 'Basic ' . encode_base64(${{moduleName}}::Configuration::username . ":" . ${{moduleName}}::Configuration::password); }{{/isBasic}}{{#isOAuth}} - if ($WWW::{{moduleName}}::Configuration::access_token) { - $header_params->{'Authorization'} = 'Bearer ' . $WWW::{{moduleName}}::Configuration::access_token; + if (${{moduleName}}::Configuration::access_token) { + $header_params->{'Authorization'} = 'Bearer ' . ${{moduleName}}::Configuration::access_token; }{{/isOAuth}} } {{/authMethods}} diff --git a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache index fc119f7a902..ef5f322a014 100644 --- a/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/ApiFactory.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::ApiFactory; +package {{moduleName}}::ApiFactory; use strict; use warnings; @@ -7,26 +7,26 @@ use utf8; use Carp; use Module::Find; -usesub WWW::{{moduleName}}::Object; +usesub {{moduleName}}::Object; -use WWW::{{moduleName}}::ApiClient; +use {{moduleName}}::ApiClient; =head1 Name - WWW::{{moduleName}}::ApiFactory - constructs APIs to retrieve {{moduleName}} objects + {{moduleName}}::ApiFactory - constructs APIs to retrieve {{moduleName}} objects =head1 Synopsis package My::Petstore::App; - use WWW::{{moduleName}}::ApiFactory; + use {{moduleName}}::ApiFactory; - my $api_factory = WWW::{{moduleName}}::ApiFactory->new( ... ); # any args for ApiClient constructor + my $api_factory = {{moduleName}}::ApiFactory->new( ... ); # any args for ApiClient constructor # later... my $pet_api = $api_factory->get_api('Pet'); - # $pet_api isa WWW::{{moduleName}}::PetApi + # $pet_api isa {{moduleName}}::PetApi my $pet = $pet_api->get_pet_by_id(pet_id => $pet_id); @@ -39,9 +39,9 @@ use WWW::{{moduleName}}::ApiClient; =cut # Load all the API classes and construct a lookup table at startup time -my %_apis = map { $_ =~ /^WWW::{{moduleName}}::(.*)$/; $1 => $_ } +my %_apis = map { $_ =~ /^{{moduleName}}::(.*)$/; $1 => $_ } grep {$_ =~ /Api$/} - usesub 'WWW::{{moduleName}}'; + usesub '{{moduleName}}'; =head1 new() @@ -54,7 +54,7 @@ my %_apis = map { $_ =~ /^WWW::{{moduleName}}::(.*)$/; $1 => $_ } sub new { my ($class, %p) = (shift, @_); - $p{api_client} = WWW::{{moduleName}}::ApiClient->instance(%p); + $p{api_client} = {{moduleName}}::ApiClient->instance(%p); return bless \%p, $class; } @@ -64,7 +64,7 @@ sub new { $which is a nickname for the class: - WWW::FooBarClient::BazApi has nickname 'Baz' + FooBarClient::BazApi has nickname 'Baz' =cut diff --git a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache index 76da048b069..3c10c2450fe 100644 --- a/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/AutoDoc.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::Role::AutoDoc; +package {{moduleName}}::Role::AutoDoc; use List::MoreUtils qw(uniq); use Moose::Role; @@ -40,7 +40,7 @@ sub _printisa { foreach my $role (@roles) { $rolepkg = $role->{package} || next; # some are anonymous, or something - next if $rolepkg eq 'WWW::{{moduleName}}::Role::AutoDoc'; + next if $rolepkg eq '{{moduleName}}::Role::AutoDoc'; $role_reqs = join ', ', keys %{$role->{required_methods}}; $role_reqs ||= ''; $~ = $how eq 'pod' ? 'ROLES_POD' : 'ROLES'; @@ -424,4 +424,4 @@ $attrname -1; \ No newline at end of file +1; diff --git a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache index aed1aec3118..9f262543acd 100644 --- a/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/BaseObject.mustache @@ -68,7 +68,7 @@ sub _deserialize { } elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) { return $data; } else { # hash(model) - my $_instance = eval "WWW::{{moduleName}}::Object::$type->new()"; + my $_instance = eval "{{moduleName}}::Object::$type->new()"; return $_instance->from_hash($data); } } diff --git a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache index 75a1ba7f61a..e0ed9bf3295 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Configuration.mustache @@ -1,4 +1,4 @@ -package WWW::{{moduleName}}::Configuration; +package {{moduleName}}::Configuration; use strict; use warnings; diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index ac94b5b0638..d6a7b379716 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -1,6 +1,6 @@ # NAME -WWW::{{moduleName}}::Role - a Moose role for the {{appName}} +{{moduleName}}::Role - a Moose role for the {{appName}} ## {{appName}} version: {{appVersion}} @@ -15,7 +15,7 @@ Automatically generated by the Perl Swagger Codegen project: ## A note on Moose This role is the only component of the library that uses Moose. See -WWW::{{moduleName}}::ApiFactory for non-Moosey usage. +{{moduleName}}::ApiFactory for non-Moosey usage. # SYNOPSIS @@ -29,7 +29,7 @@ role. package MyApp; use Moose; - with 'WWW::{{moduleName}}::Role'; + with '{{moduleName}}::Role'; package main; @@ -88,37 +88,37 @@ you are accessing. Usually `prefix` and `in` will be determined by the code gene the spec and you will not need to set them at run time. If not, `in` will default to 'head' and `prefix` to the empty string. -The tokens will be placed in the `WWW::{{moduleName}}::Configuration` namespace +The tokens will be placed in the `{{moduleName}}::Configuration` namespace as follows, but you don't need to know about this. -- `$WWW::{{moduleName}}::Configuration::username` +- `${{moduleName}}::Configuration::username` String. The username for basic auth. -- `$WWW::{{moduleName}}::Configuration::password` +- `${{moduleName}}::Configuration::password` String. The password for basic auth. -- `$WWW::{{moduleName}}::Configuration::api_key` +- `${{moduleName}}::Configuration::api_key` Hashref. Keyed on the name of each key (there can be multiple tokens). - $WWW::{{moduleName}}::Configuration::api_key = { + ${{moduleName}}::Configuration::api_key = { secretKey => 'aaaabbbbccccdddd', anotherKey => '1111222233334444', }; -- `$WWW::{{moduleName}}::Configuration::api_key_prefix` +- `${{moduleName}}::Configuration::api_key_prefix` Hashref. Keyed on the name of each key (there can be multiple tokens). Note not all api keys require a prefix. - $WWW::{{moduleName}}::Configuration::api_key_prefix = { + ${{moduleName}}::Configuration::api_key_prefix = { secretKey => 'string', anotherKey => 'same or some other string', }; -- `$WWW::{{moduleName}}::Configuration::access_token` +- `${{moduleName}}::Configuration::access_token` String. The OAuth access token. @@ -134,7 +134,7 @@ created yet) the current value of `base_url`. Returns an API factory object. You probably won't need to call this directly. - $self->api_factory('Pet'); # returns a WWW::{{moduleName}}::PetApi instance + $self->api_factory('Pet'); # returns a {{moduleName}}::PetApi instance $self->pet_api; # the same @@ -167,7 +167,7 @@ maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under `WWW::MyProjectName`. diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache index ac2298a08e9..499037dfea8 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Role.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -1,11 +1,11 @@ -package WWW::{{moduleName}}::Role; +package {{moduleName}}::Role; use utf8; use Moose::Role; use namespace::autoclean; use Class::Inspector; use Log::Any qw($log); -use WWW::{{moduleName}}::ApiFactory; +use {{moduleName}}::ApiFactory; has base_url => ( is => 'ro', required => 0, @@ -14,7 +14,7 @@ has base_url => ( is => 'ro', ); has api_factory => ( is => 'ro', - isa => 'WWW::{{moduleName}}::ApiFactory', + isa => '{{moduleName}}::ApiFactory', builder => '_build_af', lazy => 1, documentation => 'Builds an instance of the endpoint API class', @@ -29,7 +29,7 @@ has tokens => ( is => 'ro', has _cfg => ( is => 'ro', isa => 'Str', - default => 'WWW::{{moduleName}}::Configuration', + default => '{{moduleName}}::Configuration', ); has version_info => ( is => 'ro', @@ -88,12 +88,12 @@ sub _build_af { my $self = shift; my %args; $args{base_url} = $self->base_url if $self->base_url; - return WWW::{{moduleName}}::ApiFactory->new(%args); + return {{moduleName}}::ApiFactory->new(%args); } =head1 NAME -WWW::{{moduleName}}::Role - a Moose role for the {{appName}} +{{moduleName}}::Role - a Moose role for the {{appName}} =head2 {{appName}} version: {{appVersion}} @@ -114,7 +114,7 @@ Automatically generated by the Perl Swagger Codegen project: =head2 A note on Moose This role is the only component of the library that uses Moose. See -WWW::{{moduleName}}::ApiFactory for non-Moosey usage. +{{moduleName}}::ApiFactory for non-Moosey usage. =head1 SYNOPSIS @@ -128,7 +128,7 @@ role. package MyApp; use Moose; - with 'WWW::{{moduleName}}::Role'; + with '{{moduleName}}::Role'; package main; @@ -186,39 +186,39 @@ you are accessing. Usually C and C will be determined by the code ge the spec and you will not need to set them at run time. If not, C will default to 'head' and C to the empty string. -The tokens will be placed in the C namespace +The tokens will be placed in the C<{{moduleName}}::Configuration> namespace as follows, but you don't need to know about this. =over 4 -=item C<$WWW::{{moduleName}}::Configuration::username> +=item C<${{moduleName}}::Configuration::username> String. The username for basic auth. -=item C<$WWW::{{moduleName}}::Configuration::password> +=item C<${{moduleName}}::Configuration::password> String. The password for basic auth. -=item C<$WWW::{{moduleName}}::Configuration::api_key> +=item C<${{moduleName}}::Configuration::api_key> Hashref. Keyed on the name of each key (there can be multiple tokens). - $WWW::{{moduleName}}::Configuration::api_key = { + ${{moduleName}}::Configuration::api_key = { secretKey => 'aaaabbbbccccdddd', anotherKey => '1111222233334444', }; -=item C<$WWW::{{moduleName}}::Configuration::api_key_prefix> +=item C<${{moduleName}}::Configuration::api_key_prefix> Hashref. Keyed on the name of each key (there can be multiple tokens). Note not all api keys require a prefix. - $WWW::{{moduleName}}::Configuration::api_key_prefix = { + ${{moduleName}}::Configuration::api_key_prefix = { secretKey => 'string', anotherKey => 'same or some other string', }; -=item C<$WWW::{{moduleName}}::Configuration::access_token> +=item C<${{moduleName}}::Configuration::access_token> String. The OAuth access token. @@ -236,7 +236,7 @@ created yet) the current value of C. Returns an API factory object. You probably won't need to call this directly. - $self->api_factory('Pet'); # returns a WWW::{{moduleName}}::PetApi instance + $self->api_factory('Pet'); # returns a {{moduleName}}::PetApi instance $self->pet_api; # the same @@ -269,7 +269,7 @@ maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under C. diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index f25c63a528c..fa4f23d6218 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -17,7 +17,7 @@ # NOTE: This class is auto generated by the swagger code generator program. # Do not edit the class manually. # -package WWW::{{moduleName}}::{{classname}}; +package {{moduleName}}::{{classname}}; require 5.6.0; use strict; @@ -27,8 +27,8 @@ use Exporter; use Carp qw( croak ); use Log::Any qw($log); -use WWW::{{moduleName}}::ApiClient; -use WWW::{{moduleName}}::Configuration; +use {{moduleName}}::ApiClient; +use {{moduleName}}::Configuration; use base "Class::Data::Inheritable"; @@ -37,7 +37,7 @@ __PACKAGE__->mk_classdata('method_documentation' => {}); sub new { my $class = shift; my (%self) = ( - 'api_client' => WWW::{{moduleName}}::ApiClient->instance, + 'api_client' => {{moduleName}}::ApiClient->instance, @_ ); diff --git a/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache b/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache index 240936d9b51..35f8f65fc9f 100644 --- a/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/autodoc.script.mustache @@ -15,14 +15,14 @@ my $my_app = $options{c} || 'My::App'; if ($options{c}) { eval <{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; + } + } elsif ($auth eq 'api_key') { my $api_key = $self->get_api_key_with_prefix('api_key'); @@ -326,12 +332,6 @@ sub update_params_for_auth { $header_params->{'api_key'} = $api_key; } } - elsif ($auth eq 'petstore_auth') { - - if ($WWW::SwaggerClient::Configuration::access_token) { - $header_params->{'Authorization'} = 'Bearer ' . $WWW::SwaggerClient::Configuration::access_token; - } - } else { # TODO show warning about security definition not found @@ -341,7 +341,7 @@ sub update_params_for_auth { # The endpoint API class has not found any settings for auth. This may be deliberate, # in which case update_params_for_auth() will be a no-op. But it may also be that the -# swagger spec does not describe the intended authorization. So we check in the config for any +# OpenAPI Spec does not describe the intended authorization. So we check in the config for any # auth tokens and if we find any, we use them for all endpoints; sub _global_auth_setup { my ($self, $header_params, $query_params) = @_; diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm index f0846a9b594..0ffd5498420 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiFactory.pm @@ -13,7 +13,7 @@ use WWW::SwaggerClient::ApiClient; =head1 Name - WWW::SwaggerClient::ApiFactory - constructs APIs to retrieve SwaggerClient objects + WWW::SwaggerClient::ApiFactory - constructs APIs to retrieve WWW::SwaggerClient objects =head1 Synopsis @@ -64,7 +64,7 @@ sub new { $which is a nickname for the class: - WWW::FooBarClient::BazApi has nickname 'Baz' + FooBarClient::BazApi has nickname 'Baz' =cut diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm index 8c9e85ed506..8ad294d399d 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role.pm @@ -37,7 +37,7 @@ has version_info => ( is => 'ro', default => sub { { app_name => 'Swagger Petstore', app_version => '1.0.0', - generated_date => '2015-12-29T16:27:28.775+08:00', + generated_date => '2016-01-04T20:36:07.450-08:00', generator_class => 'class io.swagger.codegen.languages.PerlClientCodegen', } }, documentation => 'Information about the application version and the codegen codebase version' @@ -103,7 +103,7 @@ Automatically generated by the Perl Swagger Codegen project: =over 4 -=item Build date: 2015-12-29T16:27:28.775+08:00 +=item Build date: 2016-01-04T20:36:07.450-08:00 =item Build package: class io.swagger.codegen.languages.PerlClientCodegen @@ -119,7 +119,7 @@ WWW::SwaggerClient::ApiFactory for non-Moosey usage. =head1 SYNOPSIS The Perl Swagger Codegen project builds a library of Perl modules to interact with -a web service defined by a Swagger specification. See below for how to build the +a web service defined by a OpenAPI Specification. See below for how to build the library. This module provides an interface to the generated library. All the classes, @@ -154,7 +154,7 @@ For documentation of all these methods, see AUTOMATIC DOCUMENTATION below. =head2 Configuring authentication -In the normal case, the Swagger spec will describe what parameters are +In the normal case, the OpenAPI Spec will describe what parameters are required and where to put them. You just need to supply the tokens. my $tokens = { @@ -269,7 +269,7 @@ maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: - {"moduleName":"MyProjectName"} + {"moduleName":"WWW::MyProjectName"} Your library files will be built under C. @@ -304,7 +304,7 @@ output formats are supported: The C<-c> option allows you to load and inspect your own application. A dummy namespace is used if you don't supply your own class. -=head1 DOCUMENTATION FROM THE SWAGGER SPEC +=head1 DOCUMENTATION FROM THE OpenAPI Spec Additional documentation for each class and method may be provided by the Swagger spec. If so, this is available via the C and diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm index 0dc30dbfb90..d57c96c1798 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/Role/AutoDoc.pm @@ -424,4 +424,4 @@ $attrname -1; \ No newline at end of file +1; diff --git a/samples/client/petstore/perl/t/05_long_module_name.t b/samples/client/petstore/perl/t/05_long_module_name.t new file mode 100644 index 00000000000..5663e15e5ff --- /dev/null +++ b/samples/client/petstore/perl/t/05_long_module_name.t @@ -0,0 +1,96 @@ +use Test::More; +use Test::Exception; + +use lib 'deep_module_test/lib'; +use strict; +use warnings; + +if (! -d 'deep_module_test/lib' ) { + plan skip_all => 'bin/perl-petstore.sh needs to be run first'; +} +else { + plan tests => 38; +} + +use_ok('Something::Deep::PetApi'); +use_ok('Something::Deep::ApiClient'); +use_ok('Something::Deep::Object::Pet'); +use_ok('Something::Deep::Object::Tag'); +use_ok('Something::Deep::Object::Category'); + +my $api_client = Something::Deep::ApiClient->instance('base_url' => 'http://testing'); +my $pet_api = Something::Deep::PetApi->new('api_client' => $api_client); +is $pet_api->{api_client}->{base_url}, 'http://testing', 'get the proper base URL from api client'; + +my $api = Something::Deep::PetApi->new(); + +is $api->{api_client}->{base_url}, 'http://testing', 'we still get the original base URL from api client, because it\'s a singleton'; + +# reset the base_url - no direct access because an application shouldn't be changing +# its base URL halfway through +$api->{api_client}->{base_url} = 'http://petstore.swagger.io/v2'; + +is $api->{api_client}->{base_url}, 'http://petstore.swagger.io/v2', 'get the default base URL from api client'; + +# test select_header_content_type +is $api->{api_client}->select_header_content_type('application/xml', 'Application/JSON'), 'application/json', 'get the proper content type application/json but not application/xml'; +is $api->{api_client}->select_header_content_type('application/xml'), 'application/xml', 'get the proper content type application/json'; +is $api->{api_client}->select_header_content_type(''), 'application/json', 'get the proper content type application/json (default)'; + +# test select_header_accept +is $api->{api_client}->select_header_accept('application/xml', 'Application/JSON'), 'application/json', 'get the proper accept application/json but not application/xml'; +is $api->{api_client}->select_header_content_type('application/xml'), 'application/xml', 'get the proper accept application/json'; +is $api->{api_client}->select_header_accept(''), undef, 'get the proper accept "undef" (default)'; + +my $pet_id = 10008; + +my $category = Something::Deep::Object::Category->new('id' => '22', 'name' => 'perl'); +my $tag = Something::Deep::Object::Tag->new('id' => '11', 'name' => 'just kidding'); +my $pet = Something::Deep::Object::Pet->new('id' => $pet_id, 'name' => 'perl test', + "photoUrls" => ['123', 'oop'], 'tags' => [$tag], 'status' => 'pending', 'category' => $category); + +isa_ok($api, 'Something::Deep::PetApi'); +isa_ok($category, 'Something::Deep::Object::Category'); +isa_ok($tag, 'Something::Deep::Object::Tag'); +isa_ok($pet, 'Something::Deep::Object::Pet'); + +my $pet_hash = $pet->to_hash; + +is $pet_hash->{category}->{id}, '22', 'get the proper category id'; +is $pet_hash->{category}->{name}, 'perl', 'get the proper category name'; +is $pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag name'; +is $pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id'; + +my $add_pet = $api->add_pet(body => $pet); + +my $get_pet = $api->get_pet_by_id(pet_id => $pet_id); +my $get_pet_hash = $get_pet->to_hash; +is $get_pet_hash->{name}, 'perl test', 'get the proper pet name from get_pet_by_id'; +is $get_pet_hash->{id}, '10008', 'get the proper pet id from get_pet_by_id'; +is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category name from get_pet_by_id'; +is $get_pet_hash->{category}->{id}, '22', 'get the proper category id from get_pet_by_id'; +is $get_pet_hash->{category}->{name}, 'perl', 'get the proper category from get_pet_by_id'; +is $get_pet_hash->{tags}[0]->{name}, 'just kidding', 'get the proper tag from get_pet_by_id'; +is $get_pet_hash->{tags}[0]->{id}, '11', 'get the proper tag id from get_pet_by_id'; +is $get_pet_hash->{photoUrls}->[0], '123', 'get the proper photoUrl from get_pet_by_id'; +is $get_pet_hash->{photoUrls}->[1], 'oop', 'get the proper photoUrl from get_pet_by_id'; + + +my $update_pet_with_form = $api->update_pet_with_form(pet_id => $pet_id, name => 'test_name', status => 'sold'); +is $update_pet_with_form, undef, 'get the null response from update_pet_wth_form'; + +my $get_pet_after_update = $api->get_pet_by_id(pet_id => $pet_id); +is $get_pet_after_update->{status}, 'sold', 'get the updated status after update_pet_with_form'; + +my $upload_pet = $api->upload_file(pet_id => $pet_id, additional_metadata => 'testabc', file => 'test.pl'); +is $upload_pet, undef, 'get the null response from upload_pet'; + +my $delete_pet = $api->delete_pet(pet_id => $pet_id); +is $delete_pet, undef, 'get the null response from delete_pet'; +throws_ok{$api->get_pet_by_id(pet_id => $pet_id)} qr/API Exception\(404\): Not Found/, "throw 404 error about pet not found after delete"; +#is $get_pet_after_delete->{status}, undef, 'get the updated status after update_pet_with_form'; + +my $pets; +lives_ok {$pets = $api->find_pets_by_status(status => [qw(sold available)])} 'array query param processed correctly'; +isa_ok($pets->[0], 'Something::Deep::Object::Pet'); + From cc0d29f3ecb7b2cadf5de8cf047679630b8f6bec Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 6 Jan 2016 12:30:24 -0800 Subject: [PATCH 02/47] fixed javadoc plugin --- pom.xml | 87 +++++++++++++++++++++++++-------------------------------- 1 file changed, 38 insertions(+), 49 deletions(-) diff --git a/pom.xml b/pom.xml index 0f0e35a38c3..4badf5b42d6 100644 --- a/pom.xml +++ b/pom.xml @@ -151,54 +151,43 @@ maven-release-plugin 2.1 + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.10.3 + + true + 1.7 + UTF-8 + 1g + ${javadoc.package.exclude} + + + + attach-javadocs + verify + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + + attach-sources + verify + + jar-no-fork + + + + - - - - net.alchim31.maven - scala-maven-plugin - ${scala-maven-plugin-version} - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9 - - true - 1.6 - UTF-8 - 1g - - http://java.sun.com/javase/6/docs/api/ - - ${javadoc.package.exclude} - - - - attach-javadocs - verify - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - 2.1.2 - - - attach-sources - verify - - jar-no-fork - - - - - - @@ -530,10 +519,10 @@ - 1.0.15-SNAPSHOT + 1.0.15 2.11.1 2.3.4 - 1.5.5 + 1.5.6 2.4 1.2 4.8.1 From 3a2ad9e2e446f43a6cd71a0e03e3a88828311480 Mon Sep 17 00:00:00 2001 From: Ron Date: Wed, 6 Jan 2016 16:04:16 -0800 Subject: [PATCH 03/47] Happy new year! --- LICENSE | 2 +- README.md | 2 +- modules/swagger-codegen/src/main/resources/perl/api.mustache | 2 +- .../swagger-codegen/src/main/resources/php/ApiClient.mustache | 2 +- .../src/main/resources/php/ApiException.mustache | 2 +- .../src/main/resources/php/ObjectSerializer.mustache | 2 +- modules/swagger-codegen/src/main/resources/php/api.mustache | 2 +- .../src/main/resources/php/configuration.mustache | 2 +- modules/swagger-codegen/src/main/resources/php/model.mustache | 2 +- modules/swagger-codegen/src/main/resources/python/api.mustache | 2 +- .../src/main/resources/python/api_client.mustache | 2 +- .../src/main/resources/python/configuration.mustache | 2 +- .../swagger-codegen/src/main/resources/python/model.mustache | 2 +- modules/swagger-codegen/src/main/resources/python/rest.mustache | 2 +- .../src/main/java/io/swagger/generator/Bootstrap.java | 2 +- .../main/java/io/swagger/generator/exception/ApiException.java | 2 +- .../io/swagger/generator/exception/BadRequestException.java | 2 +- .../java/io/swagger/generator/exception/NotFoundException.java | 2 +- .../src/main/java/io/swagger/generator/model/ApiResponse.java | 2 +- .../src/main/java/io/swagger/generator/model/Generated.java | 2 +- .../src/main/java/io/swagger/generator/model/InputOption.java | 2 +- .../main/java/io/swagger/generator/util/ApiOriginFilter.java | 2 +- .../src/main/java/io/swagger/generator/util/ZipUtil.java | 2 +- samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm | 2 +- samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm | 2 +- samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/ApiException.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Configuration.php | 2 +- .../petstore/php/SwaggerClient-php/lib/Model/Category.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/Order.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php | 2 +- samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php | 2 +- .../client/petstore/php/SwaggerClient-php/lib/Model/User.php | 2 +- .../petstore/php/SwaggerClient-php/lib/ObjectSerializer.php | 2 +- samples/client/petstore/python/swagger_client/api_client.py | 2 +- samples/client/petstore/python/swagger_client/apis/pet_api.py | 2 +- samples/client/petstore/python/swagger_client/apis/store_api.py | 2 +- samples/client/petstore/python/swagger_client/apis/user_api.py | 2 +- samples/client/petstore/python/swagger_client/configuration.py | 2 +- .../client/petstore/python/swagger_client/models/category.py | 2 +- samples/client/petstore/python/swagger_client/models/order.py | 2 +- samples/client/petstore/python/swagger_client/models/pet.py | 2 +- samples/client/petstore/python/swagger_client/models/tag.py | 2 +- samples/client/petstore/python/swagger_client/models/user.py | 2 +- samples/client/petstore/python/swagger_client/rest.py | 2 +- 49 files changed, 49 insertions(+), 49 deletions(-) diff --git a/LICENSE b/LICENSE index 542991f9550..ebfd64c4931 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,4 @@ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/README.md b/README.md index 243ae836dbd..3296077ab2e 100644 --- a/README.md +++ b/README.md @@ -580,7 +580,7 @@ Please refer to this [page](https://github.com/swagger-api/swagger-codegen/blob/ License ------- -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/perl/api.mustache b/modules/swagger-codegen/src/main/resources/perl/api.mustache index f25c63a528c..774b530aba8 100644 --- a/modules/swagger-codegen/src/main/resources/perl/api.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/api.mustache @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# Copyright 2016 SmartBear Software # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache index be18e221972..f4d5c9401a7 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiClient.mustache @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache index b9022f42a90..eee688001ed 100644 --- a/modules/swagger-codegen/src/main/resources/php/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ApiException.mustache @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 8e224fd1a65..2dfdb06603c 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 2521cc61cff..29b08f80061 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache index 161affb1c9d..8fa5e1cb1f0 100644 --- a/modules/swagger-codegen/src/main/resources/php/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -11,7 +11,7 @@ */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/php/model.mustache b/modules/swagger-codegen/src/main/resources/php/model.mustache index 66cabf0122b..5b486c7fa62 100644 --- a/modules/swagger-codegen/src/main/resources/php/model.mustache +++ b/modules/swagger-codegen/src/main/resources/php/model.mustache @@ -13,7 +13,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 474cf84f356..77ece14d44b 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -2,7 +2,7 @@ """ {{classname}}.py -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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 f6e34f041e3..57ada23fb32 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index bab1d09d761..8f878f82318 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index aae43175a2e..105eefec095 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 0d1f4ce1da8..c5b9a4e6f91 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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 7d1c46c4362..995fc8c80e7 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 @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java index fe8b455ecb0..4ffc2348c27 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/ApiException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java index 7cab512b58c..14093f536d2 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/BadRequestException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java index b84985d51e1..cdae50ce9b6 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/exception/NotFoundException.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java index 8fe9d41fb7e..424b9dd2b0a 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/ApiResponse.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java index 614adcc61bc..f48be6a77da 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/Generated.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java index 45b3b7b7bbf..33df1bc5071 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/model/InputOption.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java index 07ee795f588..aca470bd89b 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ApiOriginFilter.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java index ca0a0e62018..c63f161b702 100644 --- a/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java +++ b/modules/swagger-generator/src/main/java/io/swagger/generator/util/ZipUtil.java @@ -1,5 +1,5 @@ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software *

* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm index 06ccfca98e8..e6182c4e952 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/PetApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# Copyright 2016 SmartBear Software # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm index abe936573e7..e28f8a6b260 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/StoreApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# Copyright 2016 SmartBear Software # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm index 9ba45815c8c..5e983e1aa7c 100644 --- a/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm +++ b/samples/client/petstore/perl/lib/WWW/SwaggerClient/UserApi.pm @@ -1,5 +1,5 @@ # -# Copyright 2015 SmartBear Software +# Copyright 2016 SmartBear Software # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. 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 a2ce3cac04b..53871de29ef 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. 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 6a03542dfb0..a9d9d7a3f83 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. 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 18d39efea28..3d4cdca78b9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php index 8730a8c0601..97c82f0051e 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiClient.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php index 0b8f5892a35..d6040a0ff20 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ApiException.php @@ -10,7 +10,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php index 7281f729985..108092f91b1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php @@ -11,7 +11,7 @@ */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php index 444c3c1ed7e..ae4d3e39db0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Category.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php index b803bd7325e..c9f2629e31b 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Order.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php index 6871ea9d9be..543041b0115 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Pet.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php index bcecb32fa7e..91bfa6aece9 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/Tag.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php index 1650635d8ce..8268f6da2b1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/User.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index 04b5cd0861b..de3c8e0a10c 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -11,7 +11,7 @@ * @link https://github.com/swagger-api/swagger-codegen */ /** - * Copyright 2015 SmartBear Software + * Copyright 2016 SmartBear Software * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/api_client.py b/samples/client/petstore/python/swagger_client/api_client.py index 63740a08745..00b901f3c4a 100644 --- a/samples/client/petstore/python/swagger_client/api_client.py +++ b/samples/client/petstore/python/swagger_client/api_client.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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 d7bc11daaaf..8e50474658c 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -2,7 +2,7 @@ """ PetApi.py -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/apis/store_api.py b/samples/client/petstore/python/swagger_client/apis/store_api.py index e3835990a30..af6e56d6928 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -2,7 +2,7 @@ """ StoreApi.py -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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 4394941b1d5..98111a84d9d 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -2,7 +2,7 @@ """ UserApi.py -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/configuration.py b/samples/client/petstore/python/swagger_client/configuration.py index ecbecf7e9f9..fe38630927e 100644 --- a/samples/client/petstore/python/swagger_client/configuration.py +++ b/samples/client/petstore/python/swagger_client/configuration.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index 7c36ea3ec47..d5156eee4ff 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 39081233b11..93126d98a86 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index eafb352f2d0..d7c425e3e0e 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 2041940dadf..81d27fa5e63 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index a3ad99fa4c5..6af36592c02 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/samples/client/petstore/python/swagger_client/rest.py b/samples/client/petstore/python/swagger_client/rest.py index 0d1f4ce1da8..c5b9a4e6f91 100644 --- a/samples/client/petstore/python/swagger_client/rest.py +++ b/samples/client/petstore/python/swagger_client/rest.py @@ -1,7 +1,7 @@ # coding: utf-8 """ -Copyright 2015 SmartBear Software +Copyright 2016 SmartBear Software Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. From 3465a746d3b3d48da5c20dabc45a6e5b37a0a7a1 Mon Sep 17 00:00:00 2001 From: Kevin Glinski Date: Wed, 6 Jan 2016 21:02:29 -0500 Subject: [PATCH 04/47] adding configurable options to the gemspec file --- .../codegen/languages/RubyClientCodegen.java | 83 ++++++++++++++++++- .../src/main/resources/ruby/gemspec.mustache | 13 +-- .../options/RubyClientOptionsProvider.java | 12 +++ .../codegen/ruby/RubyClientOptionsTest.java | 13 +++ 4 files changed, 114 insertions(+), 7 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 766e5f74f30..ddc4f35346f 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 @@ -19,10 +19,24 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String GEM_NAME = "gemName"; public static final String MODULE_NAME = "moduleName"; public static final String GEM_VERSION = "gemVersion"; + public static final String GEM_LICENSE = "gemLicense"; + public static final String GEM_HOMEPAGE = "gemHomepage"; + public static final String GEM_SUMMARY = "gemSummary"; + public static final String GEM_DESCRIPTION = "gemDescription"; + public static final String GEM_AUTHOR = "gemAuthor"; + public static final String GEM_AUTHOR_EMAIL = "gemAuthorEmail"; + protected String gemName; protected String moduleName; protected String gemVersion = "1.0.0"; protected String libFolder = "lib"; + protected String gemLicense = "Apache-2.0"; + protected String gemHomepage = "http://swagger.io"; + protected String gemSummary = "A ruby wrapper for the swagger APIs"; + protected String gemDescription = "This gem maps to a swagger API"; + protected String gemAuthor = ""; + protected String gemAuthorEmail = ""; + public RubyClientCodegen() { super(); @@ -87,6 +101,23 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { cliOptions.add(new CliOption(MODULE_NAME, "top module name (convention: CamelCase, usually corresponding" + " to gem name).").defaultValue("SwaggerClient")); cliOptions.add(new CliOption(GEM_VERSION, "gem version.").defaultValue("1.0.0")); + + cliOptions.add(new CliOption(GEM_LICENSE, "gem license. "). + defaultValue("Apache-2.0")); + + cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. "). + defaultValue("http://swagger.io")); + + cliOptions.add(new CliOption(GEM_SUMMARY, "gem summary. "). + defaultValue("A ruby wrapper for the swagger APIs")); + + cliOptions.add(new CliOption(GEM_DESCRIPTION, "gem description. "). + defaultValue("This gem maps to a swagger API")); + + cliOptions.add(new CliOption(GEM_AUTHOR, "gem author (only one is supported).")); + + cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); + } @Override @@ -114,11 +145,36 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if (additionalProperties.containsKey(GEM_VERSION)) { setGemVersion((String) additionalProperties.get(GEM_VERSION)); - } else { + }else { // not set, pass the default value to template additionalProperties.put(GEM_VERSION, gemVersion); } + if (additionalProperties.containsKey(GEM_LICENSE)) { + setGemLicense((String) additionalProperties.get(GEM_LICENSE)); + } + + if (additionalProperties.containsKey(GEM_HOMEPAGE)) { + setGemHomepage((String) additionalProperties.get(GEM_HOMEPAGE)); + } + + if (additionalProperties.containsKey(GEM_SUMMARY)) { + setGemSummary((String) additionalProperties.get(GEM_SUMMARY)); + } + + if (additionalProperties.containsKey(GEM_DESCRIPTION)) { + setGemDescription((String) additionalProperties.get(GEM_DESCRIPTION)); + } + + if (additionalProperties.containsKey(GEM_AUTHOR)) { + setGemAuthor((String) additionalProperties.get(GEM_AUTHOR)); + } + + if (additionalProperties.containsKey(GEM_AUTHOR_EMAIL)) { + setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL)); + } + + // use constant model/api package (folder path) setModelPackage("models"); setApiPackage("api"); @@ -133,6 +189,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { String modelFolder = gemFolder + File.separator + modelPackage.replace("/", File.separator); } + @Override public CodegenType getTag() { return CodegenType.CLIENT; @@ -354,4 +411,28 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public void setGemVersion(String gemVersion) { this.gemVersion = gemVersion; } + + public void setGemDescription(String gemDescription) { + this.gemDescription = gemDescription; + } + + public void setGemSummary(String gemSummary) { + this.gemSummary = gemSummary; + } + + public void setGemLicense(String gemLicense) { + this.gemLicense = gemLicense; + } + + public void setGemHomepage(String gemHomepage) { + this.gemHomepage = gemHomepage; + } + + public void setGemAuthor(String gemAuthor) { + this.gemAuthor = gemAuthor; + } + + public void setGemAuthorEmail(String gemAuthorEmail) { + this.gemAuthorEmail = gemAuthorEmail; + } } diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 5c9c1c1a497..c7bda3741cc 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -6,12 +6,13 @@ Gem::Specification.new do |s| s.name = "{{gemName}}" s.version = {{moduleName}}::VERSION s.platform = Gem::Platform::RUBY - s.authors = ["Zeke Sikelianos", "Tony Tam"] - s.email = ["zeke@wordnik.com", "fehguy@gmail.com"] - s.homepage = "http://swagger.io" - s.summary = %q{A ruby wrapper for the swagger APIs} - s.description = %q{This gem maps to a swagger API} - s.license = "Apache-2.0" + s.authors = ["{{gemAuthor}}"] + s.email = ["{{gemAuthorEmail}}"] + s.homepage = "{{gemHomepage}}" + s.summary = "{{gemSummary}}" + s.description = "{{gemDescription}}" + s.license = "{{gemLicense}}" + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java index d80341f0200..64e388d38ef 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/RubyClientOptionsProvider.java @@ -13,6 +13,12 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_VERSION_VALUE = "1.0.0-SNAPSHOT"; public static final String SORT_PARAMS_VALUE = "false"; public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String GEM_LICENSE_VALUE = "MIT"; + public static final String GEM_HOMEPAGE_VALUE = "homepage"; + public static final String GEM_SUMMARY_VALUE = "summary"; + public static final String GEM_DESCRIPTION_VALUE = "description"; + public static final String GEM_AUTHOR_VALUE = "foo"; + public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; @Override public String getLanguage() { @@ -25,6 +31,12 @@ public class RubyClientOptionsProvider implements OptionsProvider { return builder.put(RubyClientCodegen.GEM_NAME, GEM_NAME_VALUE) .put(RubyClientCodegen.MODULE_NAME, MODULE_NAME_VALUE) .put(RubyClientCodegen.GEM_VERSION, GEM_VERSION_VALUE) + .put(RubyClientCodegen.GEM_LICENSE, GEM_LICENSE_VALUE) + .put(RubyClientCodegen.GEM_DESCRIPTION, GEM_DESCRIPTION_VALUE) + .put(RubyClientCodegen.GEM_HOMEPAGE, GEM_HOMEPAGE_VALUE) + .put(RubyClientCodegen.GEM_SUMMARY, GEM_SUMMARY_VALUE) + .put(RubyClientCodegen.GEM_AUTHOR, GEM_AUTHOR_VALUE) + .put(RubyClientCodegen.GEM_AUTHOR_EMAIL, GEM_AUTHOR_EMAIL_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .build(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java index b679de923c8..40494161973 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/ruby/RubyClientOptionsTest.java @@ -31,6 +31,19 @@ public class RubyClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setGemVersion(RubyClientOptionsProvider.GEM_VERSION_VALUE); times = 1; + clientCodegen.setGemLicense(RubyClientOptionsProvider.GEM_LICENSE_VALUE); + times = 1; + clientCodegen.setGemHomepage(RubyClientOptionsProvider.GEM_HOMEPAGE_VALUE); + times = 1; + clientCodegen.setGemDescription(RubyClientOptionsProvider.GEM_DESCRIPTION_VALUE); + times = 1; + clientCodegen.setGemSummary(RubyClientOptionsProvider.GEM_SUMMARY_VALUE); + times = 1; + clientCodegen.setGemAuthor(RubyClientOptionsProvider.GEM_AUTHOR_VALUE); + times = 1; + clientCodegen.setGemAuthorEmail(RubyClientOptionsProvider.GEM_AUTHOR_EMAIL_VALUE); + times = 1; + }}; } } From 0bdff1c50b9836ab9d9695eff4f7ed93be7da326 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jan 2016 11:33:16 +0800 Subject: [PATCH 05/47] update reserved word to include local variable names for android, scala --- .../languages/AndroidClientCodegen.java | 20 ++++++++++++------- .../languages/AsyncScalaClientCodegen.java | 15 +++++++++----- .../codegen/languages/ScalaClientCodegen.java | 15 +++++++++----- 3 files changed, 33 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 8137dbb9793..88dd39b3d3c 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -42,13 +42,19 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi 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") + // local variable names used in API methods (endpoints) + "postBody", "path", "queryParams", "headerParams", "formParams", + "contentTypes", "contentType", "response", "builder", "httpEntity", + "authNames", "basePath", "apiInvoker", + + // android reserved words + "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") ); languageSpecificPrimitives = new HashSet( diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java index 310b4788dd0..bac6efe2aff 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AsyncScalaClientCodegen.java @@ -47,11 +47,16 @@ public class AsyncScalaClientCodegen extends DefaultCodegen implements CodegenCo reservedWords = new HashSet( Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + // local variable names used in API methods (endpoints) + "config", "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "resFuture", "client", "reader", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java index 9469cbb8e81..088d7fdaad8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalaClientCodegen.java @@ -49,11 +49,16 @@ public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig reservedWords = new HashSet( Arrays.asList( - "abstract", "case", "catch", "class", "def", "do", "else", "extends", - "false", "final", "finally", "for", "forSome", "if", "implicit", - "import", "lazy", "match", "new", "null", "object", "override", "package", - "private", "protected", "return", "sealed", "super", "this", "throw", - "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + // local variable names used in API methods (endpoints) + "path", "contentTypes", "contentType", "queryParams", "headerParams", + "formParams", "postBody", "mp", "basePath", "apiInvoker", + + // scala reserved words + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") ); additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); From f7ceace08626f8022e8321939122ef42891f00e5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jan 2016 21:21:06 +0800 Subject: [PATCH 06/47] Added URL to public docker image URL added: https://hub.docker.com/r/swaggerapi/swagger-generator/ --- README.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/README.md b/README.md index 3296077ab2e..aaef6aad31c 100644 --- a/README.md +++ b/README.md @@ -23,6 +23,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Docker](#docker) - [Build and run](#build-and-run-using-docker) - [Build a Node.js server stub](#build-a-nodejs-server-stub) + - [Public Docker image](#public-docker-image) - [Homebrew](#homebrew) - Generators - [To generate a sample client library](#to-generate-a-sample-client-library) @@ -117,6 +118,10 @@ cd swagger-codegen -o samples/server/petstore/nodejs ``` +#### Public Docker image + +https://hub.docker.com/r/swaggerapi/swagger-generator/ + ### Homebrew To install, run `brew install swagger-codegen` From 771ddccbe939b574809e4beb78b53bfe971c0cf9 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 08:42:21 -0800 Subject: [PATCH 07/47] updated jersey version --- modules/swagger-generator/pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index e893fed1ba3..f14f928b299 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -218,6 +218,6 @@ 2.5 1.3.2 9.2.9.v20150224 - 2.4.1 + 2.6 From 4fe6381fcf67a3e5ea7f97ab9ca9e4c6a94f2e90 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 11:03:24 -0800 Subject: [PATCH 08/47] updated travis --- .travis.yml | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/.travis.yml b/.travis.yml index 46286b5e5ca..ebdb7ec2306 100644 --- a/.travis.yml +++ b/.travis.yml @@ -11,12 +11,10 @@ before_install: - gem install bundler install: - - docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD script: - mvn verify -Psamples - - docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator - - if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME + - if [ ! -z "$TRAVIS_PULL_REQUEST" ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME && fi env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From 352b4ea92304e3524d56b1af44946e89aa6134c2 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 11:19:29 -0800 Subject: [PATCH 09/47] travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index ebdb7ec2306..4adb22f693e 100644 --- a/.travis.yml +++ b/.travis.yml @@ -14,7 +14,7 @@ install: script: - mvn verify -Psamples - - if [ ! -z "$TRAVIS_PULL_REQUEST" ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME && fi + - if [ ! -z "$TRAVIS_PULL_REQUEST" ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From b256ccb045983a8bbd47cc9af330bcfa4de02454 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Arne=20J=C3=B8rgensen?= Date: Thu, 7 Jan 2016 22:01:22 +0100 Subject: [PATCH 10/47] Document Java 8 as requirement. --- .travis.yml | 1 + README.md | 6 +++--- .../swagger-codegen/src/main/resources/perl/README.mustache | 2 +- .../swagger-codegen/src/main/resources/perl/Role.mustache | 2 +- 4 files changed, 6 insertions(+), 5 deletions(-) diff --git a/.travis.yml b/.travis.yml index 4adb22f693e..48d29eb3396 100644 --- a/.travis.yml +++ b/.travis.yml @@ -2,6 +2,7 @@ sudo: required language: java jdk: - oraclejdk7 + - oraclejdk8 services: - docker diff --git a/README.md b/README.md index aaef6aad31c..b5c6a769460 100644 --- a/README.md +++ b/README.md @@ -78,16 +78,16 @@ brew install swagger-codegen To build from source, you need the following installed and available in your $PATH: -* [Java 7](http://java.oracle.com) +* [Java 7 or 8](http://java.oracle.com) * [Apache maven 3.0.3 or greater](http://maven.apache.org/) #### OS X Users -Don't forget to install Java 7. You probably have 1.6 or 1.8. +Don't forget to install Java 7 or 8. You probably have 1.6. Export JAVA_HOME in order to use the supported Java version: ``` -export JAVA_HOME=`/usr/libexec/java_home -v 1.7` +export JAVA_HOME=`/usr/libexec/java_home -v 1.8` export PATH=${JAVA_HOME}/bin:$PATH ``` diff --git a/modules/swagger-codegen/src/main/resources/perl/README.mustache b/modules/swagger-codegen/src/main/resources/perl/README.mustache index d6a7b379716..62d57f6b3cf 100644 --- a/modules/swagger-codegen/src/main/resources/perl/README.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/README.mustache @@ -162,7 +162,7 @@ you could also call them on class names. See the homepage `https://github.com/swagger-api/swagger-codegen` for full details. But briefly, clone the git repository, build the codegen codebase, set up your build -config file, then run the API build script. You will need git, Java 7 and Apache +config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: diff --git a/modules/swagger-codegen/src/main/resources/perl/Role.mustache b/modules/swagger-codegen/src/main/resources/perl/Role.mustache index 499037dfea8..fb343ccb890 100644 --- a/modules/swagger-codegen/src/main/resources/perl/Role.mustache +++ b/modules/swagger-codegen/src/main/resources/perl/Role.mustache @@ -264,7 +264,7 @@ you could also call them on class names. See the homepage C for full details. But briefly, clone the git repository, build the codegen codebase, set up your build -config file, then run the API build script. You will need git, Java 7 and Apache +config file, then run the API build script. You will need git, Java 7 or 8 and Apache maven 3.0.3 or better already installed. The config file should specify the project name for the generated library: From 309906ce3affd5dcb7928756eb9116a17a40148d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 14:35:47 -0800 Subject: [PATCH 11/47] updated travis file --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 48d29eb3396..47641a02636 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,7 +15,7 @@ install: script: - mvn verify -Psamples - - if [ ! -z "$TRAVIS_PULL_REQUEST" ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi + - if [ $DOCKERHUB_USERNAME ]; then echo docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && echo docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then echo docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && echo docker push $DOCKER_IMAGE_NAME; fi env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From c0da950fce1ac4dfbf7d2c4919f77494d296d2a1 Mon Sep 17 00:00:00 2001 From: Elijah Miller Date: Thu, 7 Jan 2016 11:11:38 -0500 Subject: [PATCH 12/47] Minimal update for Ruby testing on El Capitan. --- .../swagger-codegen/src/main/resources/ruby/gemspec.mustache | 2 +- samples/client/petstore/ruby/Gemfile.lock | 4 ++-- samples/client/petstore/ruby/petstore.gemspec | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache index 5c9c1c1a497..224bfca30a2 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/gemspec.mustache @@ -22,7 +22,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' - s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.11' s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.test_files = `find spec/*`.split("\n") diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 05a6aa23790..e7812e45845 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -12,7 +12,7 @@ GEM addressable (2.3.8) autotest (4.4.6) ZenTest (>= 4.4.1) - autotest-fsevent (0.2.10) + autotest-fsevent (0.2.11) sys-uname autotest-growl (0.2.16) autotest-rails-pure (4.1.2) @@ -51,7 +51,7 @@ PLATFORMS DEPENDENCIES autotest (~> 4.4, >= 4.4.6) - autotest-fsevent (~> 0.2, >= 0.2.10) + autotest-fsevent (~> 0.2, >= 0.2.11) autotest-growl (~> 0.2, >= 0.2.16) autotest-rails-pure (~> 4.1, >= 4.1.2) petstore! diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index 6e41479fe46..df8a6df24d0 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -22,7 +22,7 @@ Gem::Specification.new do |s| s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' - s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.11' s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.test_files = `find spec/*`.split("\n") From 64427a16d120591b6f1b0e101b9dd09aa997ea28 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 7 Jan 2016 14:59:50 +0800 Subject: [PATCH 13/47] add more test case for php (array of array, map of map) --- .../src/main/resources/php/api.mustache | 7 ++- .../php/SwaggerClient-php/lib/Api/PetApi.php | 56 +++++++++-------- .../SwaggerClient-php/lib/Api/StoreApi.php | 28 +++++---- .../php/SwaggerClient-php/lib/Api/UserApi.php | 56 +++++++++-------- .../SwaggerClient-php/tests/OrderApiTest.php | 60 +++++++++++++++++++ 5 files changed, 144 insertions(+), 63 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 29b08f80061..c0c497ff418 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -126,8 +126,6 @@ use \{{invokerPackage}}\ObjectSerializer; // parse inputs $resourcePath = "{{path}}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "{{httpMethod}}"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -169,6 +167,9 @@ use \{{invokerPackage}}\ObjectSerializer; $resourcePath ); }{{/pathParams}} + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + {{#formParams}}// form params if (${{paramName}} !== null) { {{#isFile}} @@ -213,7 +214,7 @@ use \{{invokerPackage}}\ObjectSerializer; // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, '{{httpMethod}}', $queryParams, $httpBody, $headerParams{{#returnType}}, '{{returnType}}'{{/returnType}} ); 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 53871de29ef..c853583d0eb 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/PetApi.php @@ -122,8 +122,6 @@ class PetApi // parse inputs $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -137,6 +135,9 @@ class PetApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -159,7 +160,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'PUT', $queryParams, $httpBody, $headerParams ); @@ -205,8 +206,6 @@ class PetApi // parse inputs $resourcePath = "/pet"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -220,6 +219,9 @@ class PetApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -242,7 +244,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -288,8 +290,6 @@ class PetApi // parse inputs $resourcePath = "/pet/findByStatus"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -311,6 +311,9 @@ class PetApi } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -329,7 +332,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); @@ -383,8 +386,6 @@ class PetApi // parse inputs $resourcePath = "/pet/findByTags"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -406,6 +407,9 @@ class PetApi } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -424,7 +428,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet[]' ); @@ -482,8 +486,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -505,6 +507,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -525,7 +530,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Pet' ); @@ -587,8 +592,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -610,6 +613,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // form params if ($name !== null) { @@ -640,7 +646,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -692,8 +698,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -719,6 +723,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -737,7 +744,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'DELETE', $queryParams, $httpBody, $headerParams ); @@ -791,8 +798,6 @@ class PetApi // parse inputs $resourcePath = "/pet/{petId}/uploadImage"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -814,6 +819,9 @@ class PetApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // form params if ($additional_metadata !== null) { @@ -850,7 +858,7 @@ class PetApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); 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 a9d9d7a3f83..2874d8f47ac 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/StoreApi.php @@ -120,8 +120,6 @@ class StoreApi // parse inputs $resourcePath = "/store/inventory"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -135,6 +133,9 @@ class StoreApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -155,7 +156,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, 'map[string,int]' ); @@ -209,8 +210,6 @@ class StoreApi // parse inputs $resourcePath = "/store/order"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -224,6 +223,9 @@ class StoreApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -241,7 +243,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); @@ -299,8 +301,6 @@ class StoreApi // parse inputs $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -322,6 +322,9 @@ class StoreApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -335,7 +338,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\Order' ); @@ -393,8 +396,6 @@ class StoreApi // parse inputs $resourcePath = "/store/order/{orderId}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -416,6 +417,9 @@ class StoreApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -429,7 +433,7 @@ class StoreApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'DELETE', $queryParams, $httpBody, $headerParams ); 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 3d4cdca78b9..b63b679aba1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/UserApi.php @@ -122,8 +122,6 @@ class UserApi // parse inputs $resourcePath = "/user"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -137,6 +135,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -154,7 +155,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -200,8 +201,6 @@ class UserApi // parse inputs $resourcePath = "/user/createWithArray"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -215,6 +214,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -232,7 +234,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -278,8 +280,6 @@ class UserApi // parse inputs $resourcePath = "/user/createWithList"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "POST"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -293,6 +293,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -310,7 +313,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'POST', $queryParams, $httpBody, $headerParams ); @@ -358,8 +361,6 @@ class UserApi // parse inputs $resourcePath = "/user/login"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -381,6 +382,9 @@ class UserApi } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -394,7 +398,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, 'string' ); @@ -446,8 +450,6 @@ class UserApi // parse inputs $resourcePath = "/user/logout"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -461,6 +463,9 @@ class UserApi + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -474,7 +479,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams ); @@ -524,8 +529,6 @@ class UserApi // parse inputs $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "GET"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -547,6 +550,9 @@ class UserApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -560,7 +566,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'GET', $queryParams, $httpBody, $headerParams, '\Swagger\Client\Model\User' ); @@ -620,8 +626,6 @@ class UserApi // parse inputs $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "PUT"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -643,6 +647,9 @@ class UserApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + // body params $_tempBody = null; @@ -660,7 +667,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'PUT', $queryParams, $httpBody, $headerParams ); @@ -710,8 +717,6 @@ class UserApi // parse inputs $resourcePath = "/user/{username}"; - $resourcePath = str_replace("{format}", "json", $resourcePath); - $method = "DELETE"; $httpBody = ''; $queryParams = array(); $headerParams = array(); @@ -733,6 +738,9 @@ class UserApi $resourcePath ); } + // default format to json + $resourcePath = str_replace("{format}", "json", $resourcePath); + @@ -746,7 +754,7 @@ class UserApi // make the API Call try { list($response, $statusCode, $httpHeader) = $this->apiClient->callApi( - $resourcePath, $method, + $resourcePath, 'DELETE', $queryParams, $httpBody, $headerParams ); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php index 3eb0d11a9b2..f92cc83c693 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/OrderApiTest.php @@ -57,6 +57,66 @@ ORDER; $this->assertSame(false, $order->getComplete()); } + // test deseralization of array of array of order + public function testDeserializationOfArrayOfArrayOfOrder() + { + $order_json = <<deserialize(json_decode($order_json), 'Swagger\Client\Model\Order[][]'); + + $this->assertArrayHasKey(0, $order); + $this->assertArrayHasKey(0, $order[0]); + $_order = $order[0][0]; + $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); + $this->assertSame(10, $_order->getId()); + $this->assertSame(20, $_order->getPetId()); + $this->assertSame(30, $_order->getQuantity()); + $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertSame("placed", $_order->getStatus()); + $this->assertSame(false, $_order->getComplete()); + } + + // test deseralization of map of map of order + public function testDeserializationOfMapOfMapOfOrder() + { + $order_json = <<deserialize(json_decode($order_json), 'map[string,map[string,\Swagger\Client\Model\Order]]'); + + $this->assertArrayHasKey('test', $order); + $this->assertArrayHasKey('test2', $order['test']); + $_order = $order['test']['test2']; + $this->assertInstanceOf('Swagger\Client\Model\Order', $_order); + $this->assertSame(10, $_order->getId()); + $this->assertSame(20, $_order->getPetId()); + $this->assertSame(30, $_order->getQuantity()); + $this->assertTrue(new DateTime("2015-08-22T07:13:36.613Z") == $_order->getShipDate()); + $this->assertSame("placed", $_order->getStatus()); + $this->assertSame(false, $_order->getComplete()); + } + } ?> From 61e6cbef66a251981263443ef05e2028edf689d5 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 8 Jan 2016 10:37:48 +0800 Subject: [PATCH 14/47] fix httpHeader (remove s) --- .../src/main/resources/php/ObjectSerializer.mustache | 2 +- .../petstore/php/SwaggerClient-php/lib/ObjectSerializer.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index 2dfdb06603c..ea53467127d 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -231,7 +231,7 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeader) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index de3c8e0a10c..a651704e4b1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -231,7 +231,7 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeader) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); From 0a3b72cdf9c6cbbcfd848ff59c4d15b0f29038d4 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 7 Jan 2016 11:41:55 +0800 Subject: [PATCH 15/47] Add test cases of nested array/map deserialization to Ruby petstore sample --- .../petstore/ruby/spec/api_client_spec.rb | 33 +++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index aeb4eefad51..347b9876cf7 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -112,6 +112,24 @@ describe Petstore::ApiClient do end describe "#deserialize" do + it "handles Array" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '[12, 34]') + data = api_client.deserialize(response, 'Array') + data.should be_a(Array) + data.should == [12, 34] + end + + it "handles Array>" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '[[12, 34], [56]]') + data = api_client.deserialize(response, 'Array>') + data.should be_a(Array) + data.should == [[12, 34], [56]] + end + it "handles Hash" do api_client = Petstore::ApiClient.new headers = {'Content-Type' => 'application/json'} @@ -132,6 +150,21 @@ describe Petstore::ApiClient do pet.should be_a(Petstore::Pet) pet.id.should == 1 end + + it "handles Hash>" do + api_client = Petstore::ApiClient.new + headers = {'Content-Type' => 'application/json'} + response = double('response', headers: headers, body: '{"data": {"pet": {"id": 1}}}') + result = api_client.deserialize(response, 'Hash>') + result.should be_a(Hash) + result.keys.should == [:data] + data = result[:data] + data.should be_a(Hash) + data.keys.should == [:pet] + pet = data[:pet] + pet.should be_a(Petstore::Pet) + pet.id.should == 1 + end end describe "#object_to_hash" do From 7c3406804de68d919970d64c5095a78350490284 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 20:43:49 -0800 Subject: [PATCH 16/47] updated versions --- modules/swagger-codegen-cli/pom.xml | 2 +- modules/swagger-codegen-maven-plugin/pom.xml | 2 +- modules/swagger-codegen/pom.xml | 2 +- modules/swagger-generator/pom.xml | 2 +- pom.xml | 4 ++-- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen-cli/pom.xml b/modules/swagger-codegen-cli/pom.xml index 1f52f4ff663..9100143a236 100644 --- a/modules/swagger-codegen-cli/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-codegen-maven-plugin/pom.xml b/modules/swagger-codegen-maven-plugin/pom.xml index 94508f71527..850ac735534 100644 --- a/modules/swagger-codegen-maven-plugin/pom.xml +++ b/modules/swagger-codegen-maven-plugin/pom.xml @@ -6,7 +6,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. swagger-codegen-maven-plugin diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 901f18b9a1b..29d2dc4e148 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -3,7 +3,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. 4.0.0 diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index f14f928b299..6210ed77f37 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -4,7 +4,7 @@ io.swagger swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT ../.. swagger-generator diff --git a/pom.xml b/pom.xml index 4badf5b42d6..a47757a3597 100644 --- a/pom.xml +++ b/pom.xml @@ -10,7 +10,7 @@ swagger-codegen-project pom swagger-codegen-project - 2.1.5 + 2.1.6-SNAPSHOT https://github.com/swagger-api/swagger-codegen scm:git:git@github.com:swagger-api/swagger-codegen.git @@ -519,7 +519,7 @@ - 1.0.15 + 1.0.17-SNAPSHOT 2.11.1 2.3.4 1.5.6 From 1b5a7be56d308d15c55276922be83f5f68b0293a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 21:11:00 -0800 Subject: [PATCH 17/47] updated .travis --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index 47641a02636..a6f3eb6aace 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,7 +15,7 @@ install: script: - mvn verify -Psamples - - if [ $DOCKERHUB_USERNAME ]; then echo docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && echo docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then echo docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && echo docker push $DOCKER_IMAGE_NAME; fi + - if [ $DOCKERHUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From 94abbbdca7d60c5ce6af11ee03675a405b643f6c Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Thu, 7 Jan 2016 21:26:19 -0800 Subject: [PATCH 18/47] fixed variable --- .travis.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index a6f3eb6aace..46bb326da69 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,7 +15,7 @@ install: script: - mvn verify -Psamples - - if [ $DOCKERHUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi + - if [ $DOCKER_HUB_USERNAME ]; then docker login --email=$DOCKER_HUB_EMAIL --username=$DOCKER_HUB_USERNAME --password=$DOCKER_HUB_PASSWORD && docker build -t $DOCKER_IMAGE_NAME ./modules/swagger-generator && if [ ! -z "$TRAVIS_TAG" ]; then docker tag $DOCKER_IMAGE_NAME:latest $DOCKER_IMAGE_NAME:$TRAVIS_TAG; fi && docker push $DOCKER_IMAGE_NAME; fi env: - DOCKER_IMAGE_NAME=swaggerapi/swagger-generator From a8f5809370c80558b8a3ae8bb06cb403cc8de0ee Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 8 Jan 2016 14:04:10 +0800 Subject: [PATCH 19/47] replace httpHeader with httpHeaders in php object serializer --- .../src/main/resources/php/ObjectSerializer.mustache | 6 +++--- .../src/test/java/io/swagger/petstore/test/PetApiTest.java | 5 +++++ 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index ea53467127d..f53416e4c52 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -199,11 +199,11 @@ class ObjectSerializer * * @param mixed $data object or primitive to be deserialized * @param string $class class name is passed as a string - * @param string $httpHeader HTTP headers + * @param string $httpHeaders HTTP headers * * @return object an instance of $class */ - public function deserialize($data, $class, $httpHeader=null) + public function deserialize($data, $class, $httpHeaders=null) { if (null === $data) { $deserialized = null; @@ -231,7 +231,7 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeader) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); diff --git a/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java index ca868d2ea22..75039a9fa39 100644 --- a/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/android/default/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -72,6 +72,11 @@ public class PetApiTest { } @Test + @Ignore + /* ignoring the findPetByTags test below as it's very similar to + * testFindPetsByStatus and testFindPetsByTags sometimes got 500 + * due to server issue, which makes the test unstable. + */ public void testFindPetsByTags() throws Exception { Pet pet = createRandomPet(); pet.setName("monster"); From a7ff6e22abf13dd72bace238d48328bd5d970ee4 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 8 Jan 2016 14:07:05 +0800 Subject: [PATCH 20/47] update php sample before runnning CI tests --- .../petstore/php/SwaggerClient-php/lib/ObjectSerializer.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index a651704e4b1..fdd2f696189 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -199,11 +199,11 @@ class ObjectSerializer * * @param mixed $data object or primitive to be deserialized * @param string $class class name is passed as a string - * @param string $httpHeader HTTP headers + * @param string $httpHeaders HTTP headers * * @return object an instance of $class */ - public function deserialize($data, $class, $httpHeader=null) + public function deserialize($data, $class, $httpHeaders=null) { if (null === $data) { $deserialized = null; @@ -231,7 +231,7 @@ class ObjectSerializer $deserialized = $data; } elseif ($class === '\SplFileObject') { // determine file name - if (array_key_exists('Content-Disposition', $httpHeader) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeader['Content-Disposition'], $match)) { + if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); From 9fefd1e7e5610133d635f47d6826a2b109fd5517 Mon Sep 17 00:00:00 2001 From: Shyri Villar Date: Thu, 7 Jan 2016 17:53:06 +0100 Subject: [PATCH 21/47] Fixed android-volley-library responses when additionalProperties is present. Clean responses mechanism using volley default's --- .../languages/AndroidClientCodegen.java | 4 ---- .../android/libraries/volley/api.mustache | 2 +- .../libraries/volley/responses.mustache | 24 ------------------- 3 files changed, 1 insertion(+), 29 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java index 8137dbb9793..7fc9033f59d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AndroidClientCodegen.java @@ -281,10 +281,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("apiInvoker.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("responses.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "Responses.java")); - // supportingFiles.add(new SupportingFile("httpPatch.mustache", - // (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "HttpPatch.java")); supportingFiles.add(new SupportingFile("jsonUtil.mustache", (sourceFolder + File.separator + invokerPackage).replace(".", File.separator), "JsonUtil.java")); supportingFiles.add(new SupportingFile("apiException.mustache", diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index ccd12fd67c5..a327eaad659 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -50,7 +50,7 @@ public class {{classname}} { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final {{#returnBaseType}}Responses.{{returnBaseType}}{{#isListContainer}}List{{/isListContainer}}Response{{/returnBaseType}}{{^returnBaseType}}Responses.StringResponse{{/returnBaseType}} responseListener, final Response.ErrorListener errorListener) { + public void {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{^hasMore}}, {{/hasMore}}{{/allParams}}final Response.Listener<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}String{{/returnType}}> responseListener, final Response.ErrorListener errorListener) { Object postBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; {{#allParams}}{{#required}} diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache deleted file mode 100644 index 7cb955f7239..00000000000 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/responses.mustache +++ /dev/null @@ -1,24 +0,0 @@ -package {{invokerPackage}}; - -import java.util.List; -import {{modelPackage}}.*; - -public class Responses { - {{#models}} - {{#model}} - public static interface {{classname}}Response { - public void onResponse({{classname}} {{classVarName}}); - } - public static interface {{classname}}ListResponse { - public void onResponse(List<{{classname}}> {{classVarName}}List); - } - {{/model}} - {{/models}} - public static interface StringResponse { - public void onResponse(String response); - } - - public static interface StringListResponse { - public void onResponse(List stringList); - } -} \ No newline at end of file From 4261fe402cc69b952406a5edb012e40611bd7c4d Mon Sep 17 00:00:00 2001 From: Shyri Villar Date: Thu, 7 Jan 2016 17:55:04 +0100 Subject: [PATCH 22/47] android-volley-library updated android sdk, buildtools and target versions --- .../main/resources/android/libraries/volley/api.mustache | 1 - .../main/resources/android/libraries/volley/build.mustache | 6 +++--- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache index a327eaad659..1d70000c1dc 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/api.mustache @@ -1,6 +1,5 @@ package {{package}}; -import {{invokerPackage}}.Responses; import {{invokerPackage}}.ApiInvoker; import {{invokerPackage}}.ApiException; import {{invokerPackage}}.Pair; diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache index ec599632fd8..87d7f4a882c 100644 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/build.mustache @@ -28,11 +28,11 @@ apply plugin: 'com.github.dcendents.android-maven' {{/useAndroidMavenGradlePlugin}} android { - compileSdkVersion 22 - buildToolsVersion '22.0.0' + compileSdkVersion 23 + buildToolsVersion '23.0.2' defaultConfig { minSdkVersion 14 - targetSdkVersion 22 + targetSdkVersion 23 } compileOptions { sourceCompatibility JavaVersion.VERSION_1_7 From 468a13dc961e0702f4f07fff4bce848357931929 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 8 Jan 2016 17:03:57 +0800 Subject: [PATCH 23/47] add cli option to optionally generate assemblyinfo.cs (default: true) --- .../io/swagger/codegen/CodegenConstants.java | 5 +++ .../languages/CSharpClientCodegen.java | 17 +++++++++- .../csharp/CSharpClientOptionsTest.java | 3 ++ .../options/CSharpClientOptionsProvider.java | 1 + .../src/Properties/AssemblyInfo.cs | 33 +++++++++++++++++++ .../SwaggerClientTest.userprefs | 15 ++++++--- 6 files changed, 69 insertions(+), 5 deletions(-) create mode 100644 samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs 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 fc2410fa9de..80aab1af864 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 @@ -54,4 +54,9 @@ public class CodegenConstants { public static final String POD_VERSION = "podVersion"; public static final String OPTIONAL_METHOD_ARGUMENT = "optionalMethodArgument"; + public static final String OPTIONAL_METHOD_ARGUMENT_DESC = "Optional method argument, e.g. void square(int x=10) (.net 4.0+ only)."; + + public static final String OPTIONAL_ASSEMBLY_INFO = "optionalAssemblyInfo"; + public static final String OPTIONAL_ASSEMBLY_INFO_DESC = "Generate AssemblyInfo.cs (Default: true)."; + } 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 aa776731e9c..3a97237ddab 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 @@ -23,6 +23,7 @@ import org.slf4j.LoggerFactory; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + protected boolean optionalAssemblyInfoFlag = true; protected boolean optionalMethodArgumentFlag = true; protected String packageTitle = "Swagger Library"; protected String packageProductName = "SwaggerLibrary"; @@ -111,6 +112,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC).defaultValue(Boolean.TRUE.toString())); cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "C# Optional method argument, " + "e.g. void square(int x=10) (.net 4.0+ only).")); + cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, + CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString())); } @Override @@ -147,6 +150,11 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig } additionalProperties.put("optionalMethodArgument", optionalMethodArgumentFlag); + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_ASSEMBLY_INFO)) { + setOptionalAssemblyInfoFlag(Boolean.valueOf(additionalProperties + .get(CodegenConstants.OPTIONAL_ASSEMBLY_INFO).toString())); + } + supportingFiles.add(new SupportingFile("Configuration.mustache", sourceFolder + File.separator + clientPackage.replace(".", java.io.File.separator), "Configuration.cs")); supportingFiles.add(new SupportingFile("ApiClient.mustache", @@ -159,7 +167,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("RestSharp.dll", "bin", "RestSharp.dll")); supportingFiles.add(new SupportingFile("compile.mustache", "", "compile.bat")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); - supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs")); + + if (optionalAssemblyInfoFlag) { + supportingFiles.add(new SupportingFile("AssemblyInfo.mustache", "src" + File.separator + "Properties", "AssemblyInfo.cs")); + } } @@ -301,6 +312,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig return camelize(sanitizeName(operationId)); } + public void setOptionalAssemblyInfoFlag(boolean flag) { + this.optionalAssemblyInfoFlag = flag; + } + public void setOptionalMethodArgumentFlag(boolean flag) { this.optionalMethodArgumentFlag = flag; } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index ec5246f7723..7b35ed020b9 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -31,6 +31,9 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setPackageVersion(CSharpClientOptionsProvider.PACKAGE_VERSION_VALUE); times = 1; + clientCodegen.setOptionalAssemblyInfoFlag(true); + times = 1; + }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 94440db97c0..97228fdccc0 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -22,6 +22,7 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.PACKAGE_VERSION, PACKAGE_VERSION_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "true") + .put(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, "true") .build(); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..1de9edb2a81 --- /dev/null +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/Properties/AssemblyInfo.cs @@ -0,0 +1,33 @@ +using System.Reflection; +using System.Runtime.InteropServices; +using System.Windows; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Swagger Library")] +[assembly: AssemblyDescription("A library generated from a Swagger doc")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Swagger")] +[assembly: AssemblyProduct("SwaggerLibrary")] +[assembly: AssemblyCopyright("No Copyright")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")] diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index a5ad5d531bd..afe62f18b31 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -1,11 +1,18 @@  - + - - - + + + + + + + + + + From 9657d4437e25600a80b17077a6a6a425879f8257 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 8 Jan 2016 17:31:09 +0800 Subject: [PATCH 24/47] Java client: get/set connect timeout, fix "debugging" --- .../main/resources/Java/ApiClient.mustache | 58 +++++++++++------ .../java/io/swagger/client/ApiClient.java | 62 ++++++++++++------- 2 files changed, 80 insertions(+), 40 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index ef31058d561..e5f64a8c908 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -43,10 +43,12 @@ import {{invokerPackage}}.auth.OAuth; {{>generatedAnnotation}} public class ApiClient { - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "{{basePath}}"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; private ObjectMapper mapper; private Map authentications; @@ -57,6 +59,8 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + httpClient = buildHttpClient(debugging); + mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -64,7 +68,7 @@ public class ApiClient { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -224,9 +228,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.setConnectTimeout(connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -436,8 +460,6 @@ public class ApiClient { updateParamsForAuth(authNames, queryParams, headerParams); - Client client = getClient(); - StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ @@ -455,9 +477,9 @@ public class ApiClient { Builder builder; if (accept == null) - builder = client.resource(basePath + path + querystring).getRequestBuilder(); + builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); else - builder = client.resource(basePath + path + querystring).accept(accept); + builder = httpClient.resource(basePath + path + querystring).accept(accept); for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); @@ -571,19 +593,17 @@ public class ApiClient { } /** - * Get an existing client or create a new client to handle HTTP request. + * Build the Client used to make HTTP requests. */ - private Client getClient() { - if(!hostMap.containsKey(basePath)) { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) - client.addFilter(new LoggingFilter()); - hostMap.put(basePath, client); + private Client buildHttpClient(boolean debugging) { + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); + if (debugging) { + client.addFilter(new LoggingFilter()); } - return hostMap.get(basePath); + return client; } } 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 057dcd7d72d..daa584094bb 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 @@ -41,12 +41,14 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:16.440+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T17:06:02.039+08:00") public class ApiClient { - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; private ObjectMapper mapper; private Map authentications; @@ -57,6 +59,8 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + httpClient = buildHttpClient(debugging); + mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -64,7 +68,7 @@ public class ApiClient { mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); - + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -79,8 +83,8 @@ public class ApiClient { // 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()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -223,9 +227,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.setConnectTimeout(connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -435,8 +459,6 @@ public class ApiClient { updateParamsForAuth(authNames, queryParams, headerParams); - Client client = getClient(); - StringBuilder b = new StringBuilder(); b.append("?"); if (queryParams != null){ @@ -454,9 +476,9 @@ public class ApiClient { Builder builder; if (accept == null) - builder = client.resource(basePath + path + querystring).getRequestBuilder(); + builder = httpClient.resource(basePath + path + querystring).getRequestBuilder(); else - builder = client.resource(basePath + path + querystring).accept(accept); + builder = httpClient.resource(basePath + path + querystring).accept(accept); for (String key : headerParams.keySet()) { builder = builder.header(key, headerParams.get(key)); @@ -570,19 +592,17 @@ public class ApiClient { } /** - * Get an existing client or create a new client to handle HTTP request. + * Build the Client used to make HTTP requests. */ - private Client getClient() { - if(!hostMap.containsKey(basePath)) { - // Add the JSON serialization support to Jersey - JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); - DefaultClientConfig conf = new DefaultClientConfig(); - conf.getSingletons().add(jsonProvider); - Client client = Client.create(conf); - if (debugging) - client.addFilter(new LoggingFilter()); - hostMap.put(basePath, client); + private Client buildHttpClient(boolean debugging) { + // Add the JSON serialization support to Jersey + JacksonJsonProvider jsonProvider = new JacksonJsonProvider(mapper); + DefaultClientConfig conf = new DefaultClientConfig(); + conf.getSingletons().add(jsonProvider); + Client client = Client.create(conf); + if (debugging) { + client.addFilter(new LoggingFilter()); } - return hostMap.get(basePath); + return client; } } From 3d652186192732c1fea0395ba1a37712269327b0 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 8 Jan 2016 19:05:43 +0800 Subject: [PATCH 25/47] Java jersey2 client: get/set connect timeout --- .../main/resources/Java/ApiClient.mustache | 4 +- .../Java/libraries/jersey2/ApiClient.mustache | 48 +++++++++++++---- .../java/io/swagger/client/ApiClient.java | 6 +-- .../java/io/swagger/client/ApiClient.java | 52 ++++++++++++++----- 4 files changed, 81 insertions(+), 29 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index e5f64a8c908..9f55d5a14d4 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -59,8 +59,6 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { - httpClient = buildHttpClient(debugging); - mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -69,6 +67,8 @@ public class ApiClient { mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); 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 f482b8c34d4..83e92921a82 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 @@ -12,7 +12,9 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; @@ -43,12 +45,13 @@ import {{invokerPackage}}.auth.OAuth; {{>generatedAnnotation}} public class ApiClient { - private Client client; - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "{{basePath}}"; - private JSON json = new JSON(); + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; private Map authentications; @@ -58,6 +61,9 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -70,8 +76,6 @@ public class ApiClient { // Set default User-Agent. setUserAgent("Java-Swagger"); - buildClient(); - // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap();{{#authMethods}}{{#isBasic}} authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} @@ -226,10 +230,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; - buildClient(); + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -472,7 +495,7 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - WebTarget target = client.target(this.basePath).path(path); + WebTarget target = httpClient.target(this.basePath).path(path); if (queryParams != null) { for (Pair queryParam : queryParams) { @@ -545,15 +568,18 @@ public class ApiClient { } } - private void buildClient() { + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(json); - clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); + clientConfig.register(JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } - this.client = ClientBuilder.newClient(clientConfig); + return ClientBuilder.newClient(clientConfig); } private Map> buildResponseHeaders(Response response) { 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 daa584094bb..581eafa51ca 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 @@ -41,7 +41,7 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T17:06:02.039+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:50:38.131+08:00") public class ApiClient { private Map defaultHeaderMap = new HashMap(); private String basePath = "http://petstore.swagger.io/v2"; @@ -59,8 +59,6 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { - httpClient = buildHttpClient(debugging); - mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); @@ -69,6 +67,8 @@ public class ApiClient { mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); mapper.registerModule(new JodaModule()); + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); 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 73deed7fad8..7f06e36633f 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 @@ -12,7 +12,9 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.Response.Status; import org.glassfish.jersey.client.ClientConfig; +import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.filter.LoggingFilter; +import org.glassfish.jersey.jackson.JacksonFeature; import org.glassfish.jersey.media.multipart.FormDataBodyPart; import org.glassfish.jersey.media.multipart.FormDataContentDisposition; import org.glassfish.jersey.media.multipart.MultiPart; @@ -41,14 +43,15 @@ import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; import io.swagger.client.auth.OAuth; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:17.660+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-08T18:51:26.068+08:00") public class ApiClient { - private Client client; - private Map hostMap = new HashMap(); private Map defaultHeaderMap = new HashMap(); - private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; - private JSON json = new JSON(); + private boolean debugging = false; + private int connectionTimeout = 0; + + private Client httpClient; + private JSON json; private Map authentications; @@ -58,6 +61,9 @@ public class ApiClient { private DateFormat dateFormat; public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + // Use RFC3339 format for date and datetime. // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"); @@ -70,12 +76,10 @@ public class ApiClient { // Set default User-Agent. setUserAgent("Java-Swagger"); - buildClient(); - // 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()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -225,10 +229,29 @@ public class ApiClient { */ public ApiClient setDebugging(boolean debugging) { this.debugging = debugging; - buildClient(); + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); return this; } + /** + * Connect timeout (in milliseconds). + */ + public int getConnectTimeout() { + return connectionTimeout; + } + + /** + * Set the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link Integer#MAX_VALUE}. + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + this.connectionTimeout = connectionTimeout; + httpClient.property(ClientProperties.CONNECT_TIMEOUT, connectionTimeout); + return this; + } + /** * Get the date format used to parse/format date parameters. */ @@ -471,7 +494,7 @@ public class ApiClient { public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { updateParamsForAuth(authNames, queryParams, headerParams); - WebTarget target = client.target(this.basePath).path(path); + WebTarget target = httpClient.target(this.basePath).path(path); if (queryParams != null) { for (Pair queryParam : queryParams) { @@ -544,15 +567,18 @@ public class ApiClient { } } - private void buildClient() { + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { final ClientConfig clientConfig = new ClientConfig(); clientConfig.register(MultiPartFeature.class); clientConfig.register(json); - clientConfig.register(org.glassfish.jersey.jackson.JacksonFeature.class); + clientConfig.register(JacksonFeature.class); if (debugging) { clientConfig.register(LoggingFilter.class); } - this.client = ClientBuilder.newClient(clientConfig); + return ClientBuilder.newClient(clientConfig); } private Map> buildResponseHeaders(Response response) { From 170bde65e5e01174dead95bcf8fa5f3538f0b4f7 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 8 Jan 2016 19:55:31 +0800 Subject: [PATCH 26/47] Fix link to 2.1.5 --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b5c6a769460..f5ba049c8d4 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 Swagger Codegen Version | Release Date | OpenAPI Spec compatibility | Notes -------------------------- | ------------ | -------------------------- | ----- 2.1.6-SNAPSHOT | | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.1.5 (**current stable**) | 2015-01-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-codegen/tree/v2.1.4) +2.1.5 (**current stable**) | 2015-01-06 | 1.0, 1.1, 1.2, 2.0 | [tag v2.1.5](https://github.com/swagger-api/swagger-codegen/tree/v2.1.5) 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) From b6e8ad56b5c688bffc0b88a64afbf9480e46c68d Mon Sep 17 00:00:00 2001 From: frinux Date: Thu, 7 Jan 2016 10:49:37 +0100 Subject: [PATCH 27/47] Fixed bug: basePath should not be empty This last change was producing a wrong swagger spec @see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md "The value MUST start with a leading slash (/)" --- .../java/io/swagger/codegen/languages/NodeJSServerCodegen.java | 3 --- 1 file changed, 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index d4bb00bb652..1088fd6ae52 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -246,9 +246,6 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig @Override public void preprocessSwagger(Swagger swagger) { - if ("/".equals(swagger.getBasePath())) { - swagger.setBasePath(""); - } String host = swagger.getHost(); String port = "8080"; From 4f715342a131db87c80b8d005430aa0cd837d405 Mon Sep 17 00:00:00 2001 From: frinux Date: Thu, 7 Jan 2016 10:14:02 +0100 Subject: [PATCH 28/47] projectName support to fill package.json template Inspired by ClojureClientCodegen.java, it is interesting to use projectName from info.title swagger spec to fill up package.json name attribute --- .../swagger/codegen/languages/NodeJSServerCodegen.java | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index d4bb00bb652..65da63b5ada 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -259,6 +259,16 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig } } this.additionalProperties.put("serverPort", port); + + if (swagger.getInfo() != null) { + Info info = swagger.getInfo(); + if (projectName == null && info.getTitle() != null) { + // when projectName is not specified, generate it from info.title + //used in package.json + projectName = dashize(info.getTitle()); + this.additionalProperties.put("projectName", projectName); + } + } } @Override From 6064f32ba566347421eca1816aef0f3907490e54 Mon Sep 17 00:00:00 2001 From: frinux Date: Thu, 7 Jan 2016 10:19:35 +0100 Subject: [PATCH 29/47] Compilation error fixed io.swagger.models.Info dependency added --- .../java/io/swagger/codegen/languages/NodeJSServerCodegen.java | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 65da63b5ada..142e17c3c3f 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -11,6 +11,7 @@ import com.google.common.collect.Multimap; import io.swagger.codegen.*; import io.swagger.models.Swagger; +import io.swagger.models.Info; import io.swagger.util.Yaml; import java.io.File; From 15676ff72e7fa09a1ce74ac52ab45785651f0786 Mon Sep 17 00:00:00 2001 From: frinux Date: Thu, 7 Jan 2016 10:26:10 +0100 Subject: [PATCH 30/47] Update NodeJSServerCodegen.java projectName was already defined so never overriden. --- .../io/swagger/codegen/languages/NodeJSServerCodegen.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java index 142e17c3c3f..a468b0b98a8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/NodeJSServerCodegen.java @@ -263,9 +263,9 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig if (swagger.getInfo() != null) { Info info = swagger.getInfo(); - if (projectName == null && info.getTitle() != null) { - // when projectName is not specified, generate it from info.title - //used in package.json + if (info.getTitle() != null) { + // when info.title is defined, use it for projectName + // used in package.json projectName = dashize(info.getTitle()); this.additionalProperties.put("projectName", projectName); } From 5f9164049c5365ab71b179a008441b9ab77420d1 Mon Sep 17 00:00:00 2001 From: John Hancock Date: Wed, 6 Jan 2016 20:02:43 -0500 Subject: [PATCH 31/47] CSharp: add support for DateTimeOffset and sourceFolder configuration --- .../io/swagger/codegen/CodegenConstants.java | 3 ++ .../languages/CSharpClientCodegen.java | 32 +++++++++++++++++++ .../main/resources/csharp/ApiClient.mustache | 6 ++++ .../csharp/CSharpClientOptionsTest.java | 4 +++ .../options/CSharpClientOptionsProvider.java | 5 ++- .../csharp/SwaggerClientTest/TestApiClient.cs | 2 +- 6 files changed, 50 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 80aab1af864..6fa62061300 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 @@ -46,6 +46,9 @@ public class CodegenConstants { 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."; + public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; + public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; + public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; 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 3a97237ddab..b68efe4fff9 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 @@ -25,6 +25,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); protected boolean optionalAssemblyInfoFlag = true; protected boolean optionalMethodArgumentFlag = true; + protected boolean useDateTimeOffsetFlag = false; protected String packageTitle = "Swagger Library"; protected String packageProductName = "SwaggerLibrary"; protected String packageDescription = "A library generated from a Swagger doc"; @@ -76,6 +77,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "List", "Dictionary", "DateTime?", + "DateTimeOffset?", "String", "Boolean", "Double", @@ -114,6 +116,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "e.g. void square(int x=10) (.net 4.0+ only).")); cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString())); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder)); + cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC)); } @Override @@ -126,6 +130,14 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)){ + setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + else + { + additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder); + } + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; @@ -135,6 +147,13 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } + // Use DateTimeOffset + if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) + { + useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString())); + } + additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); + additionalProperties.put("clientPackage", clientPackage); // Add properties used by AssemblyInfo.mustache @@ -320,6 +339,15 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig this.optionalMethodArgumentFlag = flag; } + public void useDateTimeOffset(boolean flag) { + this.useDateTimeOffsetFlag = flag; + if (flag) + typeMapping.put("datetime", "DateTimeOffset?"); + else + typeMapping.put("datetime", "DateTime?"); + } + + public void setPackageName(String packageName) { this.packageName = packageName; } @@ -328,6 +356,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig this.packageVersion = packageVersion; } + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + @Override public Map postProcessModels(Map objs) { List models = (List) objs.get("models"); diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 142b2e6bbb9..023790b5a38 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -194,6 +194,12 @@ namespace {{packageName}}.Client // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is DateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index 7b35ed020b9..c0cd6a6e9c8 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -34,6 +34,10 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { clientCodegen.setOptionalAssemblyInfoFlag(true); times = 1; + clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.useDateTimeOffset(true); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 97228fdccc0..6e3b14c580d 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -9,7 +9,8 @@ import java.util.Map; public class CSharpClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - + public static final String SOURCE_FOLDER_VALUE = "src_csharp"; + @Override public String getLanguage() { return "csharp"; @@ -23,6 +24,8 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "true") .put(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, "true") + .put(CodegenConstants.USE_DATETIME_OFFSET, "true") + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs index f0232c330f0..0fc92c7266e 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs @@ -48,7 +48,7 @@ namespace SwaggerClientTest.TestApiClient { ApiClient api = new ApiClient (); // test datetime with a time zone - DateTime dateWithTz = DateTime.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); + DateTimeOffset dateWithTz = DateTimeOffset.Parse("2008-04-10T13:30:00.0000000-04:00", null, System.Globalization.DateTimeStyles.RoundtripKind); Assert.AreEqual("2008-04-10T13:30:00.0000000-04:00", api.ParameterToString(dateWithTz)); } From ebe090572f466f418d0561f2155b725af8e5e9bf Mon Sep 17 00:00:00 2001 From: John Hancock Date: Wed, 6 Jan 2016 20:02:43 -0500 Subject: [PATCH 32/47] CSharp: add support for DateTimeOffset and sourceFolder configuration options Adds option to use DateTimeOffset to model datetime fields instead of DateTime to allow preservation of timezone information. Modifies ApiClient.ParameterToString to support DateTimeOffset. Also adds sourceFolder option. --- .../languages/CSharpClientCodegen.java | 60 +++++++++---------- .../csharp/CSharpClientOptionsTest.java | 9 ++- .../options/CSharpClientOptionsProvider.java | 6 +- 3 files changed, 37 insertions(+), 38 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 b68efe4fff9..322729ac8c0 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 @@ -25,7 +25,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig private static final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); protected boolean optionalAssemblyInfoFlag = true; protected boolean optionalMethodArgumentFlag = true; - protected boolean useDateTimeOffsetFlag = false; + protected boolean useDateTimeOffsetFlag = false; protected String packageTitle = "Swagger Library"; protected String packageProductName = "SwaggerLibrary"; protected String packageDescription = "A library generated from a Swagger doc"; @@ -77,7 +77,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "List", "Dictionary", "DateTime?", - "DateTimeOffset?", + "DateTimeOffset?", "String", "Boolean", "Double", @@ -116,8 +116,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig "e.g. void square(int x=10) (.net 4.0+ only).")); cliOptions.add(CliOption.newBoolean(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC).defaultValue(Boolean.TRUE.toString())); - cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder)); - cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC)); + cliOptions.add(new CliOption(CodegenConstants.SOURCE_FOLDER, CodegenConstants.SOURCE_FOLDER_DESC).defaultValue(sourceFolder)); + cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_DATETIME_OFFSET, CodegenConstants.USE_DATETIME_OFFSET_DESC)); } @Override @@ -130,14 +130,14 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); } - if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)){ - setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); - } - else - { - additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder); - } - + if (additionalProperties.containsKey(CodegenConstants.SOURCE_FOLDER)){ + setSourceFolder((String) additionalProperties.get(CodegenConstants.SOURCE_FOLDER)); + } + else + { + additionalProperties.put(CodegenConstants.SOURCE_FOLDER, this.sourceFolder); + } + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); apiPackage = packageName + ".Api"; @@ -147,13 +147,13 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); } - // Use DateTimeOffset - if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) - { - useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString())); - } - additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); - + // Use DateTimeOffset + if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_OFFSET)) + { + useDateTimeOffset(Boolean.valueOf(additionalProperties.get(CodegenConstants.USE_DATETIME_OFFSET).toString())); + } + additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); + additionalProperties.put("clientPackage", clientPackage); // Add properties used by AssemblyInfo.mustache @@ -339,15 +339,15 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig this.optionalMethodArgumentFlag = flag; } - public void useDateTimeOffset(boolean flag) { - this.useDateTimeOffsetFlag = flag; - if (flag) - typeMapping.put("datetime", "DateTimeOffset?"); - else - typeMapping.put("datetime", "DateTime?"); + public void useDateTimeOffset(boolean flag) { + this.useDateTimeOffsetFlag = flag; + if (flag) + typeMapping.put("datetime", "DateTimeOffset?"); + else + typeMapping.put("datetime", "DateTime?"); } - + public void setPackageName(String packageName) { this.packageName = packageName; } @@ -356,10 +356,10 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig this.packageVersion = packageVersion; } - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } + @Override public Map postProcessModels(Map objs) { List models = (List) objs.get("models"); diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java index c0cd6a6e9c8..367977e2b05 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/csharp/CSharpClientOptionsTest.java @@ -33,11 +33,10 @@ public class CSharpClientOptionsTest extends AbstractOptionsTest { times = 1; clientCodegen.setOptionalAssemblyInfoFlag(true); times = 1; - - clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); - times = 1; - clientCodegen.useDateTimeOffset(true); - times = 1; + clientCodegen.setSourceFolder(CSharpClientOptionsProvider.SOURCE_FOLDER_VALUE); + times = 1; + clientCodegen.useDateTimeOffset(true); + times = 1; }}; } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java index 6e3b14c580d..0c2da1f3fa2 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/CSharpClientOptionsProvider.java @@ -9,7 +9,7 @@ import java.util.Map; public class CSharpClientOptionsProvider implements OptionsProvider { public static final String PACKAGE_NAME_VALUE = "swagger_client_csharp"; public static final String PACKAGE_VERSION_VALUE = "1.0.0-SNAPSHOT"; - public static final String SOURCE_FOLDER_VALUE = "src_csharp"; + public static final String SOURCE_FOLDER_VALUE = "src_csharp"; @Override public String getLanguage() { @@ -24,8 +24,8 @@ public class CSharpClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, "true") .put(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, "true") .put(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, "true") - .put(CodegenConstants.USE_DATETIME_OFFSET, "true") - .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.USE_DATETIME_OFFSET, "true") + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) .build(); } From 2a7fc2d00e58be0552522487e79734e5587bf142 Mon Sep 17 00:00:00 2001 From: John Hancock Date: Fri, 8 Jan 2016 10:51:30 -0500 Subject: [PATCH 33/47] Fixed whitespace/tab issues --- .../src/main/java/io/swagger/codegen/CodegenConstants.java | 4 ++-- .../src/main/resources/csharp/ApiClient.mustache | 4 ++-- 2 files changed, 4 insertions(+), 4 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 6fa62061300..4a4f9e037ef 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 @@ -46,8 +46,8 @@ public class CodegenConstants { 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."; - public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; - public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; + public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; + public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index 023790b5a38..fab938460fc 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -194,12 +194,12 @@ namespace {{packageName}}.Client // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); - else if (obj is DateTimeOffset) + else if (obj is DateTimeOffset) // Return a formatted date string - Can be customized with Configuration.DateTimeFormat // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 - return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); From 995869f4d5b8d2ebcfadc3b6bb457880b6bde89b Mon Sep 17 00:00:00 2001 From: Erik van Zijst Date: Fri, 8 Jan 2016 11:07:18 -0800 Subject: [PATCH 34/47] Java Class Name Clashes with java.lang.* A swagger file that contains a definition named "object" compiles into a class named Object. This is technically not a problem as it lives in a different package than java.lang.Object, but this requires the templates to refer to Java's Object using its fully qualified name. --- modules/swagger-codegen/src/main/resources/Java/pojo.mustache | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index eea33d346d4..1af6e50242c 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -27,7 +27,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali {{/vars}} @Override - public boolean equals(Object o) { + public boolean equals(java.lang.Object o) { if (this == o) { return true; } @@ -59,7 +59,7 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private String toIndentedString(Object o) { + private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } From dbe62bee373d5b265ec17e075f95c580295d381a Mon Sep 17 00:00:00 2001 From: Erik van Zijst Date: Fri, 8 Jan 2016 15:11:59 -0800 Subject: [PATCH 35/47] #1858: The Java equals/hashcode methods ignores state from superclasses This fixes equals/hashCode for derived classes. --- .../src/main/resources/Java/pojo.mustache | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache index eea33d346d4..99fa12108a1 100644 --- a/modules/swagger-codegen/src/main/resources/Java/pojo.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/pojo.mustache @@ -34,15 +34,16 @@ public class {{classname}} {{#parent}}extends {{{parent}}}{{/parent}} {{#seriali if (o == null || getClass() != o.getClass()) { return false; } - {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && - {{/hasMore}}{{^hasMore}};{{/hasMore}}{{/vars}}{{/hasVars}}{{^hasVars}} - return true;{{/hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + + return true {{#hasVars}}&& {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{#hasMore}} && + {{/hasMore}}{{/vars}}{{/hasVars}} + {{#parent}}&& super.equals(o){{/parent}}; } @Override public int hashCode() { - return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}); + return Objects.hash({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{#parent}}{{#hasVars}},{{/hasVars}} super.hashCode(){{/parent}}); } @Override From 6b7439b9d9827762b001328010438ddeff8154ef Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 10 Jan 2016 00:17:55 +0800 Subject: [PATCH 36/47] add compile-mono, fix csharp comment --- .../io/swagger/codegen/languages/CSharpClientCodegen.java | 2 ++ .../src/main/resources/csharp/ApiResponse.mustache | 4 ++-- .../src/main/resources/csharp/Configuration.mustache | 1 + .../src/main/resources/csharp/model.mustache | 2 +- .../SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh | 4 ++-- .../src/main/csharp/IO/Swagger/Client/ApiClient.cs | 6 ++++++ .../src/main/csharp/IO/Swagger/Client/ApiResponse.cs | 4 ++-- .../src/main/csharp/IO/Swagger/Client/Configuration.cs | 1 + .../src/main/csharp/IO/Swagger/Model/Category.cs | 2 +- .../SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs | 2 +- .../SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs | 2 +- .../SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs | 2 +- .../SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs | 2 +- 13 files changed, 22 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 322729ac8c0..8966e19b9ce 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 @@ -185,6 +185,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig 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")); + supportingFiles.add(new SupportingFile("compile-mono.sh.mustache", "", "compile-mono.sh")); + supportingFiles.add(new SupportingFile("packages.config.mustache", "vendor" + java.io.File.separator, "packages.config")); supportingFiles.add(new SupportingFile("README.md", "", "README.md")); if (optionalAssemblyInfoFlag) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache index 32816110a1b..c4317c35b65 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiResponse.mustache @@ -27,10 +27,10 @@ namespace {{packageName}}.Client public T Data { get; private set; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// HTTP status code. - /// Error message. + /// HTTP headers. /// Data (parsed HTTP body) public ApiResponse(int statusCode, IDictionary headers, T data) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache index 7062a73c1e1..d3ef0c6f731 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/Configuration.mustache @@ -24,6 +24,7 @@ namespace {{packageName}}.Client /// Dictionary of API key prefix /// Temp folder path /// DateTime format string + /// HTTP connection timeout (in milliseconds) public Configuration(ApiClient apiClient = null, Dictionary defaultHeader = null, string username = null, diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index ad942039677..6db39b046a2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -74,7 +74,7 @@ namespace {{packageName}}.Model /// /// Returns true if {{classname}} instances are equal /// - /// Instance of {{classname}} to be compared + /// Instance of {{classname}} to be compared /// Boolean public bool Equals({{classname}} other) { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh index bc4e0989945..352274186d2 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/compile-mono.sh @@ -7,6 +7,6 @@ vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/IO.Swagger.dll \ --recurse:src/*.cs \ +-recurse:'src/*.cs' \ -doc:bin/IO.Swagger.xml \ --platform:anycpu \ No newline at end of file +-platform:anycpu 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 7e6807f16a4..ee2e1b8b8f0 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 @@ -194,6 +194,12 @@ namespace IO.Swagger.Client // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 // For example: 2009-06-15T13:45:30.0000000 return ((DateTime)obj).ToString (Configuration.DateTimeFormat); + else if (obj is DateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return ((DateTimeOffset)obj).ToString (Configuration.DateTimeFormat); else if (obj is IList) { var flattenedString = new StringBuilder(); diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs index 15735711656..651d3609c22 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/ApiResponse.cs @@ -27,10 +27,10 @@ namespace IO.Swagger.Client public T Data { get; private set; } /// - /// Initializes a new instance of the class. + /// Initializes a new instance of the class. /// /// HTTP status code. - /// Error message. + /// HTTP headers. /// Data (parsed HTTP body) public ApiResponse(int statusCode, IDictionary headers, T data) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs index 000b8893cdf..7ea30009c9c 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Client/Configuration.cs @@ -24,6 +24,7 @@ namespace IO.Swagger.Client /// Dictionary of API key prefix /// Temp folder path /// DateTime format string + /// HTTP connection timeout (in milliseconds) public Configuration(ApiClient apiClient = null, Dictionary defaultHeader = null, string username = null, diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs index 6ad53e05257..85694bc93c8 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Category.cs @@ -78,7 +78,7 @@ namespace IO.Swagger.Model /// /// Returns true if Category instances are equal /// - /// Instance of Category to be compared + /// Instance of Category to be compared /// Boolean public bool Equals(Category other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs index eb649ccf587..5a110929b20 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Order.cs @@ -111,7 +111,7 @@ namespace IO.Swagger.Model /// /// Returns true if Order instances are equal /// - /// Instance of Order to be compared + /// Instance of Order to be compared /// Boolean public bool Equals(Order other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs index 202a171c219..ec3b3d5ca13 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Pet.cs @@ -111,7 +111,7 @@ namespace IO.Swagger.Model /// /// Returns true if Pet instances are equal /// - /// Instance of Pet to be compared + /// Instance of Pet to be compared /// Boolean public bool Equals(Pet other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs index 4aa4a9c97f0..078a53ad1ea 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/Tag.cs @@ -78,7 +78,7 @@ namespace IO.Swagger.Model /// /// Returns true if Tag instances are equal /// - /// Instance of Tag to be compared + /// Instance of Tag to be compared /// Boolean public bool Equals(Tag other) { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs index 5785a3d3509..7f0b3b858aa 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/Lib/SwaggerClient/src/main/csharp/IO/Swagger/Model/User.cs @@ -127,7 +127,7 @@ namespace IO.Swagger.Model /// /// Returns true if User instances are equal /// - /// Instance of User to be compared + /// Instance of User to be compared /// Boolean public bool Equals(User other) { From 08756413dcc045c7b9784dfcc584b9878520256f Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 10 Jan 2016 00:31:37 +0800 Subject: [PATCH 37/47] fix comment in csharpdonet2.0 --- .../main/resources/CsharpDotNet2/ApiClient.mustache | 1 + .../resources/CsharpDotNet2/ApiException.mustache | 1 - .../src/main/resources/CsharpDotNet2/api.mustache | 9 ++++++--- .../CsharpDotNet2/compile-mono.sh.mustache | 4 ++-- .../src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs | 13 ++++++++----- .../main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs | 9 ++++++--- .../main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs | 5 ++++- .../CsharpDotNet2/IO/Swagger/Client/ApiClient.cs | 1 + .../CsharpDotNet2/IO/Swagger/Client/ApiException.cs | 1 - 9 files changed, 28 insertions(+), 16 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache index a428cdc3630..ea92989daa4 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiClient.mustache @@ -159,6 +159,7 @@ namespace {{packageName}}.Client /// /// HTTP body (e.g. string, JSON). /// Object type. + /// HTTP headers. /// 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/CsharpDotNet2/ApiException.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache index 71d0243d729..dd618e0a99c 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/ApiException.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/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/CsharpDotNet2/api.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache index 2e51c913c30..c3fb85acb4f 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/api.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/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}} @@ -16,7 +19,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); {{/operation}} } @@ -71,7 +74,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}} @@ -79,7 +82,7 @@ namespace {{packageName}}.Api /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{/allParams}}/// {{#returnType}}{{{returnType}}}{{/returnType}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { {{#allParams}}{{#required}} diff --git a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache index 73add75a69a..1e4e12b4aee 100644 --- a/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache +++ b/modules/swagger-codegen/src/main/resources/CsharpDotNet2/compile-mono.sh.mustache @@ -7,6 +7,6 @@ vendor/RestSharp.Net2.1.1.11/lib/net20/RestSharp.Net2.dll,\ System.Runtime.Serialization.dll \ -target:library \ -out:bin/{{packageName}}.dll \ --recurse:src/*.cs \ +-recurse:'src/*.cs' \ -doc:bin/{{packageName}}.xml \ --platform:anycpu \ No newline at end of file +-platform:anycpu diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs index 7db0f993846..b09b31264c3 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/PetApi.cs @@ -8,6 +8,9 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IPetApi { @@ -29,14 +32,14 @@ namespace IO.Swagger.Api /// 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<Pet> List FindPetsByStatus (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<Pet> List FindPetsByTags (List tags); /// @@ -124,7 +127,7 @@ namespace IO.Swagger.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} @@ -212,7 +215,7 @@ namespace IO.Swagger.Api /// 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<Pet> public List FindPetsByStatus (List status) { @@ -252,7 +255,7 @@ namespace IO.Swagger.Api /// 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<Pet> public List FindPetsByTags (List tags) { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs index c6c90631bef..ba269cc2b0c 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/StoreApi.cs @@ -8,13 +8,16 @@ using IO.Swagger.Model; 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<String, int?> Dictionary GetInventory (); /// @@ -90,14 +93,14 @@ namespace IO.Swagger.Api /// /// 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 + /// Dictionary<String, int?> public Dictionary GetInventory () { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs index 3e3c8869d04..1374556698e 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Api/UserApi.cs @@ -8,6 +8,9 @@ using IO.Swagger.Model; namespace IO.Swagger.Api { + /// + /// Represents a collection of functions to interact with the API endpoints + /// public interface IUserApi { @@ -120,7 +123,7 @@ namespace IO.Swagger.Api /// /// Gets or sets the API client. /// - /// An instance of the ApiClient + /// An instance of the ApiClient public ApiClient ApiClient {get; set;} diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs index 56331e606a9..3041cde567e 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiClient.cs @@ -159,6 +159,7 @@ namespace IO.Swagger.Client /// /// HTTP body (e.g. string, JSON). /// Object type. + /// HTTP headers. /// Object representation of the JSON string. public object Deserialize(string content, Type type, IList headers=null) { diff --git a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs index ff0b4be791e..dfc5fd9fc03 100644 --- a/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs +++ b/samples/client/petstore/csharp-dotnet2/SwaggerClientTest/Lib/SwaggerClient/src/main/CsharpDotNet2/IO/Swagger/Client/ApiException.cs @@ -20,7 +20,6 @@ namespace IO.Swagger.Client { /// /// Initializes a new instance of the class. /// - /// The base path. public ApiException() {} /// From e1348e7871222315dbb2d89d25211215f57581fd Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 10 Jan 2016 02:29:58 +0800 Subject: [PATCH 38/47] add new files for c# --- .../main/resources/csharp/compile-mono.sh.mustache | 12 ++++++++++++ .../main/resources/csharp/packages.config.mustache | 5 +++++ 2 files changed, 17 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache diff --git a/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache new file mode 100644 index 00000000000..9472dcc8d3d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/compile-mono.sh.mustache @@ -0,0 +1,12 @@ +wget -nc https://nuget.org/nuget.exe; +mozroots --import --sync +mono nuget.exe install vendor/packages.config -o vendor; +mkdir -p bin; +mcs -sdk:45 -r:vendor/Newtonsoft.Json.8.0.2/lib/net45/Newtonsoft.Json.dll,\ +vendor/RestSharp.105.2.3/lib/net45/RestSharp.dll,\ +System.Runtime.Serialization.dll \ +-target:library \ +-out:bin/{{packageName}}.dll \ +-recurse:'src/*.cs' \ +-doc:bin/{{packageName}}.xml \ +-platform:anycpu diff --git a/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache new file mode 100644 index 00000000000..c87bbb79fa6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/csharp/packages.config.mustache @@ -0,0 +1,5 @@ + + + + + From e0f43c1c589936c657a8c47c26706044e29a6200 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 11 Jan 2016 00:39:22 +0800 Subject: [PATCH 39/47] add binary support to C# client --- .../languages/CSharpClientCodegen.java | 1 + .../main/resources/csharp/ApiClient.mustache | 63 +- .../src/main/resources/csharp/api.mustache | 56 +- .../src/test/resources/2_0/petstore.json | 93 +++ .../src/main/csharp/IO/Swagger/Api/PetApi.cs | 782 +++++++++++++++--- .../main/csharp/IO/Swagger/Api/StoreApi.cs | 177 ++-- .../src/main/csharp/IO/Swagger/Api/UserApi.cs | 369 ++++++--- .../csharp/IO/Swagger/Client/ApiClient.cs | 63 +- .../SwaggerClientTest.userprefs | 6 +- .../csharp/SwaggerClientTest/TestApiClient.cs | 20 + .../csharp/SwaggerClientTest/TestPet.cs | 52 +- .../obj/Debug/SwaggerClientTest.dll.mdb | Bin 31212 -> 0 bytes 12 files changed, 1363 insertions(+), 319 deletions(-) delete mode 100644 samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb 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 8966e19b9ce..23c266e618f 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 @@ -92,6 +92,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping = new HashMap(); typeMapping.put("string", "string"); + typeMapping.put("binary", "byte[]"); typeMapping.put("boolean", "bool?"); typeMapping.put("integer", "int?"); typeMapping.put("float", "float?"); diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index fab938460fc..8a22c2f23f9 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -77,9 +77,10 @@ namespace {{packageName}}.Client // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = new RestRequest(path, method); @@ -103,8 +104,17 @@ namespace {{packageName}}.Client foreach(var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); - if (postBody != null) // http body (model) parameter - request.AddParameter("application/json", postBody, ParameterType.RequestBody); + if (postBody != null) // http body (model or byte[]) parameter + { + if (postBody.GetType() == typeof(String)) + { + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + } + else if (postBody.GetType() == typeof(byte[])) + { + request.AddParameter(contentType, postBody, ParameterType.RequestBody); + } + } return request; } @@ -120,14 +130,18 @@ namespace {{packageName}}.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content Type of the request /// Object public Object CallApi( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + var response = RestClient.Execute(request); return (Object) response; } @@ -143,14 +157,17 @@ namespace {{packageName}}.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content type. /// The Task instance. public async System.Threading.Tasks.Task CallApiAsync( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } @@ -230,6 +247,10 @@ namespace {{packageName}}.Client { return content; } + else if (type == typeof(byte[])) // return byte array + { + return data; + } if (type == typeof(Stream)) { @@ -276,11 +297,11 @@ namespace {{packageName}}.Client } /// - /// Serialize an object into JSON string. + /// Serialize an input (model) into JSON string /// /// Object. /// JSON string. - public string Serialize(object obj) + public String Serialize(object obj) { try { @@ -292,6 +313,24 @@ namespace {{packageName}}.Client } } + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public String SelectHeaderContentType(String[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + /// /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 51f8b3f9394..28919d6be49 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -154,7 +154,8 @@ namespace {{packageName}}.Api { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{operationId}}"); + if ({{paramName}} == null) + throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); {{/required}}{{/allParams}} var path_ = "{{path}}"; @@ -164,15 +165,21 @@ namespace {{packageName}}.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -185,11 +192,16 @@ namespace {{packageName}}.Api {{/headerParams}} {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToFile("{{baseName}}", {{paramName}}));{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", Configuration.ApiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}postBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter - {{/bodyParam}} + {{#bodyParam}}if ({{paramName}}.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize({{paramName}}); // http body (model) parameter + } + else + { + postBody = {{paramName}}; // byte array + }{{/bodyParam}} - {{#authMethods}} - // authentication ({{name}}) required + {{#authMethods}}// authentication ({{name}}) required {{#isApiKey}}{{#isKeyInHeader}} var apiKeyValue = Configuration.GetApiKeyWithPrefix("{{keyParamName}}"); if (!String.IsNullOrEmpty(apiKeyValue)) @@ -214,7 +226,9 @@ namespace {{packageName}}.Api {{/authMethods}} // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -261,15 +275,21 @@ namespace {{packageName}}.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -311,7 +331,9 @@ namespace {{packageName}}.Api {{/authMethods}} // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 66762d74b2b..703b920db21 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -19,6 +19,49 @@ "http" ], "paths": { + "/pet?testing_byte_array=true": { + "post": { + "tags": [ + "pet" + ], + "summary": "Fake endpoint to test byte array in body parameter for adding a new pet to the store", + "description": "", + "operationId": "addPetUsingByteArray", + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "parameters": [ + { + "in": "body", + "name": "body", + "description": "Pet object in the form of byte array", + "required": false, + "schema": { + "type": "string", + "format": "binary" + } + } + ], + "responses": { + "405": { + "description": "Invalid input" + } + }, + "security": [ + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, "/pet": { "post": { "tags": [ @@ -206,6 +249,56 @@ ] } }, + "/pet/{petId}?testing_byte_array=true": { + "get": { + "tags": [ + "pet" + ], + "summary": "Fake endpoint to test byte array return by 'Find pet by ID'", + "description": "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", + "operationId": "getPetByIdWithByteArray", + "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": { + "type": "string", + "format": "binary" + } + }, + "400": { + "description": "Invalid ID supplied" + } + }, + "security": [ + { + "api_key": [] + }, + { + "petstore_auth": [ + "write:pets", + "read:pets" + ] + } + ] + } + }, "/pet/{petId}": { "get": { "tags": [ 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 ba58eeac9e0..892412e5b3e 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 @@ -355,6 +355,86 @@ namespace IO.Swagger.Api /// Task of ApiResponse System.Threading.Tasks.Task> UploadFileAsyncWithHttpInfo (long? petId, string additionalMetadata = null, Stream file = null); + /// + /// Fake endpoint to test byte array return by '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 + /// byte[] + byte[] GetPetByIdWithByteArray (long? petId); + + /// + /// Fake endpoint to test byte array return by '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 + /// ApiResponse of byte[] + ApiResponse GetPetByIdWithByteArrayWithHttpInfo (long? petId); + + /// + /// Fake endpoint to test byte array return by '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 + /// Task of byte[] + System.Threading.Tasks.Task GetPetByIdWithByteArrayAsync (long? petId); + + /// + /// Fake endpoint to test byte array return by '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 + /// Task of ApiResponse (byte[]) + System.Threading.Tasks.Task> GetPetByIdWithByteArrayAsyncWithHttpInfo (long? petId); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// + void AddPetUsingByteArray (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// ApiResponse of Object(void) + ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// Task of void + System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null); + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// + /// + /// + /// Pet object in the form of byte array + /// Task of ApiResponse + System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null); + } /// @@ -459,15 +539,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -476,10 +562,15 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } - // authentication (petstore_auth) required // oauth required @@ -490,7 +581,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -532,15 +625,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -563,7 +662,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -604,15 +705,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -621,10 +728,15 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } - // authentication (petstore_auth) required // oauth required @@ -635,7 +747,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -677,15 +791,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; - // to determine the Accept header - String[] http_header_accepts = new String[] { + // to determine the Content-Type header + String[] httpContentTypes = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -708,7 +828,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -750,15 +872,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -770,7 +898,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -781,7 +908,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -824,15 +953,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -855,7 +990,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -897,15 +1034,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -917,7 +1060,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -928,7 +1070,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -971,15 +1115,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1002,7 +1152,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1037,7 +1189,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetById"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->GetPetById"); var path_ = "/pet/{petId}"; @@ -1047,15 +1200,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1067,7 +1226,6 @@ namespace IO.Swagger.Api - // authentication (api_key) required var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); @@ -1078,7 +1236,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1123,15 +1283,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1154,7 +1320,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1192,7 +1360,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UpdatePetWithForm"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->UpdatePetWithForm"); var path_ = "/pet/{petId}"; @@ -1202,15 +1371,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/x-www-form-urlencoded" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1224,7 +1399,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -1235,7 +1409,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1283,15 +1459,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/x-www-form-urlencoded" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1316,7 +1498,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1352,7 +1536,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling DeletePet"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->DeletePet"); var path_ = "/pet/{petId}"; @@ -1362,15 +1547,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1383,7 +1574,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -1394,7 +1584,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1440,15 +1632,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1472,7 +1670,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1510,7 +1710,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'petId' is set - if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling UploadFile"); + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->UploadFile"); var path_ = "/pet/{petId}/uploadImage"; @@ -1520,15 +1721,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "multipart/form-data" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1542,7 +1749,6 @@ namespace IO.Swagger.Api - // authentication (petstore_auth) required // oauth required @@ -1553,7 +1759,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1601,15 +1809,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "multipart/form-data" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1634,7 +1848,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1649,6 +1865,340 @@ namespace IO.Swagger.Api null); } + /// + /// Fake endpoint to test byte array return by '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 + /// byte[] + public byte[] GetPetByIdWithByteArray (long? petId) + { + ApiResponse response = GetPetByIdWithByteArrayWithHttpInfo(petId); + return response.Data; + } + + /// + /// Fake endpoint to test byte array return by '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 + /// ApiResponse of byte[] + public ApiResponse< byte[] > GetPetByIdWithByteArrayWithHttpInfo (long? petId) + { + + // verify the required parameter 'petId' is set + if (petId == null) + throw new ApiException(400, "Missing required parameter 'petId' when calling PetApi->GetPetByIdWithByteArray"); + + + var path_ = "/pet/{petId}?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // 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", Configuration.ApiClient.ParameterToString(petId)); // path parameter + + + + + + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (byte[]) Configuration.ApiClient.Deserialize(response, typeof(byte[]))); + + } + + /// + /// Fake endpoint to test byte array return by '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 + /// Task of byte[] + public async System.Threading.Tasks.Task GetPetByIdWithByteArrayAsync (long? petId) + { + ApiResponse response = await GetPetByIdWithByteArrayAsyncWithHttpInfo(petId); + return response.Data; + + } + + /// + /// Fake endpoint to test byte array return by '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 + /// Task of ApiResponse (byte[]) + public async System.Threading.Tasks.Task> GetPetByIdWithByteArrayAsyncWithHttpInfo (long? petId) + { + // verify the required parameter 'petId' is set + if (petId == null) throw new ApiException(400, "Missing required parameter 'petId' when calling GetPetByIdWithByteArray"); + + + var path_ = "/pet/{petId}?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // 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", Configuration.ApiClient.ParameterToString(petId)); // path parameter + + + + + + + + // authentication (api_key) required + + var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); + if (!String.IsNullOrEmpty(apiKeyValue)) + { + headerParams["api_key"] = apiKeyValue; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling GetPetByIdWithByteArray: " + response.ErrorMessage, response.ErrorMessage); + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + (byte[]) Configuration.ApiClient.Deserialize(response, typeof(byte[]))); + + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// + public void AddPetUsingByteArray (byte[] body = null) + { + AddPetUsingByteArrayWithHttpInfo(body); + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// ApiResponse of Object(void) + public ApiResponse AddPetUsingByteArrayWithHttpInfo (byte[] body = null) + { + + + var path_ = "/pet?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(Configuration.DefaultHeader); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/json", "application/xml" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// Task of void + public async System.Threading.Tasks.Task AddPetUsingByteArrayAsync (byte[] body = null) + { + await AddPetUsingByteArrayAsyncWithHttpInfo(body); + + } + + /// + /// Fake endpoint to test byte array in body parameter for adding a new pet to the store + /// + /// Pet object in the form of byte array + /// Task of ApiResponse + public async System.Threading.Tasks.Task> AddPetUsingByteArrayAsyncWithHttpInfo (byte[] body = null) + { + + + var path_ = "/pet?testing_byte_array=true"; + + var pathParams = new Dictionary(); + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + "application/json", "application/xml" + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); + + // to determine the Accept header + String[] httpHeaderAccepts = new String[] { + "application/json", "application/xml" + }; + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); + + // set "format" to json by default + // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json + pathParams.Add("format", "json"); + + + + + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + + + + // authentication (petstore_auth) required + + // oauth required + if (!String.IsNullOrEmpty(Configuration.AccessToken)) + { + headerParams["Authorization"] = "Bearer " + Configuration.AccessToken; + } + + + // make the HTTP request + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); + + int statusCode = (int) response.StatusCode; + + if (statusCode >= 400) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.Content, response.Content); + else if (statusCode == 0) + throw new ApiException (statusCode, "Error calling AddPetUsingByteArray: " + response.ErrorMessage, response.ErrorMessage); + + + return new ApiResponse(statusCode, + response.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), + null); + } + } } 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 a9e9d6e9b74..a92876f1a53 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 @@ -274,15 +274,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -293,7 +299,6 @@ namespace IO.Swagger.Api - // authentication (api_key) required var apiKeyValue = Configuration.GetApiKeyWithPrefix("api_key"); @@ -304,7 +309,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -345,15 +352,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -375,7 +388,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -417,15 +432,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -434,13 +455,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -483,15 +512,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -506,7 +541,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -541,7 +578,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'orderId' is set - if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling GetOrderById"); + if (orderId == null) + throw new ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->GetOrderById"); var path_ = "/store/order/{orderId}"; @@ -551,15 +589,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -574,7 +618,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -619,15 +665,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -642,7 +694,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -676,7 +730,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'orderId' is set - if (orderId == null) throw new ApiException(400, "Missing required parameter 'orderId' when calling DeleteOrder"); + if (orderId == null) + throw new ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); var path_ = "/store/order/{orderId}"; @@ -686,15 +741,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -709,7 +770,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -753,15 +816,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -776,7 +845,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; 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 5502fe15da1..0b9e633c5f3 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 @@ -443,15 +443,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -460,13 +466,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -508,15 +522,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -531,7 +551,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -572,15 +594,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -589,13 +617,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -637,15 +673,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -660,7 +702,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -701,15 +745,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -718,13 +768,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -766,15 +824,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -789,7 +853,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.POST, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -833,15 +899,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -857,7 +929,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -902,15 +976,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -926,7 +1006,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -965,15 +1047,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -987,7 +1075,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1027,15 +1117,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1049,7 +1145,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1084,7 +1182,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling GetUserByName"); + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); var path_ = "/user/{username}"; @@ -1094,15 +1193,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1117,7 +1222,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1162,15 +1269,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1185,7 +1298,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.GET, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.GET, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1221,7 +1336,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling UpdateUser"); + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); var path_ = "/user/{username}"; @@ -1231,15 +1347,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1249,13 +1371,21 @@ namespace IO.Swagger.Api - postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter - + if (body.GetType() != typeof(byte[])) + { + postBody = Configuration.ApiClient.Serialize(body); // http body (model) parameter + } + else + { + postBody = body; // byte array + } // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1301,15 +1431,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1325,7 +1461,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1359,7 +1497,8 @@ namespace IO.Swagger.Api { // verify the required parameter 'username' is set - if (username == null) throw new ApiException(400, "Missing required parameter 'username' when calling DeleteUser"); + if (username == null) + throw new ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); var path_ = "/user/{username}"; @@ -1369,15 +1508,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(Configuration.DefaultHeader); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1392,7 +1537,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) Configuration.ApiClient.CallApi(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; @@ -1436,15 +1583,21 @@ namespace IO.Swagger.Api var headerParams = new Dictionary(); var formParams = new Dictionary(); var fileParams = new Dictionary(); - String postBody = null; + Object postBody = null; + + // to determine the Content-Type header + String[] httpContentTypes = new String[] { + + }; + String httpContentType = Configuration.ApiClient.SelectHeaderContentType(httpContentTypes); // to determine the Accept header - String[] http_header_accepts = new String[] { + String[] httpHeaderAccepts = new String[] { "application/json", "application/xml" }; - String http_header_accept = Configuration.ApiClient.SelectHeaderAccept(http_header_accepts); - if (http_header_accept != null) - headerParams.Add("Accept", Configuration.ApiClient.SelectHeaderAccept(http_header_accepts)); + String httpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(httpHeaderAccepts); + if (httpHeaderAccept != null) + headerParams.Add("Accept", httpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json @@ -1459,7 +1612,9 @@ namespace IO.Swagger.Api // make the HTTP request - IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + IRestResponse response = (IRestResponse) await Configuration.ApiClient.CallApiAsync(path_, + Method.DELETE, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, httpContentType); int statusCode = (int) response.StatusCode; 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 ee2e1b8b8f0..ab115aba980 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 @@ -77,9 +77,10 @@ namespace IO.Swagger.Client // Creates and sets up a RestRequest prior to a call. private RestRequest PrepareRequest( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = new RestRequest(path, method); @@ -103,8 +104,17 @@ namespace IO.Swagger.Client foreach(var param in fileParams) request.AddFile(param.Value.Name, param.Value.Writer, param.Value.FileName, param.Value.ContentType); - if (postBody != null) // http body (model) parameter - request.AddParameter("application/json", postBody, ParameterType.RequestBody); + if (postBody != null) // http body (model or byte[]) parameter + { + if (postBody.GetType() == typeof(String)) + { + request.AddParameter("application/json", postBody, ParameterType.RequestBody); + } + else if (postBody.GetType() == typeof(byte[])) + { + request.AddParameter(contentType, postBody, ParameterType.RequestBody); + } + } return request; } @@ -120,14 +130,18 @@ namespace IO.Swagger.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content Type of the request /// Object public Object CallApi( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); + var response = RestClient.Execute(request); return (Object) response; } @@ -143,14 +157,17 @@ namespace IO.Swagger.Client /// Form parameters. /// File parameters. /// Path parameters. + /// Content type. /// The Task instance. public async System.Threading.Tasks.Task CallApiAsync( - String path, RestSharp.Method method, Dictionary queryParams, String postBody, + String path, RestSharp.Method method, Dictionary queryParams, Object postBody, Dictionary headerParams, Dictionary formParams, - Dictionary fileParams, Dictionary pathParams) + Dictionary fileParams, Dictionary pathParams, + String contentType) { var request = PrepareRequest( - path, method, queryParams, postBody, headerParams, formParams, fileParams, pathParams); + path, method, queryParams, postBody, headerParams, formParams, fileParams, + pathParams, contentType); var response = await RestClient.ExecuteTaskAsync(request); return (Object)response; } @@ -230,6 +247,10 @@ namespace IO.Swagger.Client { return content; } + else if (type == typeof(byte[])) // return byte array + { + return data; + } if (type == typeof(Stream)) { @@ -276,11 +297,11 @@ namespace IO.Swagger.Client } /// - /// Serialize an object into JSON string. + /// Serialize an input (model) into JSON string /// /// Object. /// JSON string. - public string Serialize(object obj) + public String Serialize(object obj) { try { @@ -292,6 +313,24 @@ namespace IO.Swagger.Client } } + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public String SelectHeaderContentType(String[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + if (contentTypes.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + /// /// Select the Accept header's value from the given accepts array: /// if JSON exists in the given array, use it; diff --git a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs index afe62f18b31..34b1a516f28 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs +++ b/samples/client/petstore/csharp/SwaggerClientTest/SwaggerClientTest.userprefs @@ -3,6 +3,10 @@ + + + + @@ -18,4 +22,4 @@ - \ No newline at end of file + diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs index 0fc92c7266e..6eb32a38442 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestApiClient.cs @@ -14,6 +14,26 @@ namespace SwaggerClientTest.TestApiClient Configuration.Default.DateTimeFormat = "o"; } + /// + /// Test SelectHeaderContentType + /// + [Test ()] + public void TestSelectHeaderContentType () + { + ApiClient api = new ApiClient (); + String[] contentTypes = new String[] { "application/json", "application/xml" }; + Assert.AreEqual("application/json", api.SelectHeaderContentType (contentTypes)); + + contentTypes = new String[] { "application/xml" }; + Assert.AreEqual("application/xml", api.SelectHeaderContentType (contentTypes)); + + contentTypes = new String[] {}; + Assert.IsNull(api.SelectHeaderContentType (contentTypes)); + } + + /// + /// Test ParameterToString + /// [Test ()] public void TestParameterToString () { diff --git a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs index fbbf4494951..001b052bf76 100644 --- a/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs +++ b/samples/client/petstore/csharp/SwaggerClientTest/TestPet.cs @@ -15,7 +15,10 @@ namespace SwaggerClientTest.TestPet { public long petId = 11088; - [SetUp] public void Init() + /// + /// Create a Pet object + /// + private Pet createPet() { // create pet Pet p = new Pet(); @@ -36,6 +39,24 @@ namespace SwaggerClientTest.TestPet p.Category = category; p.PhotoUrls = photoUrls; + return p; + } + + /// + /// Convert string to byte array + /// + private byte[] GetBytes(string str) + { + byte[] bytes = new byte[str.Length * sizeof(char)]; + System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length); + return bytes; + } + + [SetUp] public void Init() + { + // create pet + Pet p = createPet(); + // add pet before testing PetApi petApi = new PetApi("http://petstore.swagger.io/v2/"); petApi.AddPet (p); @@ -137,6 +158,35 @@ namespace SwaggerClientTest.TestPet } + /// + /// Test GetPetByIdWithByteArray + /// + [Test ()] + public void TestGetPetByIdWithByteArray () + { + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000); + + PetApi petApi = new PetApi (c1); + byte[] response = petApi.GetPetByIdWithByteArray (petId); + Assert.IsInstanceOf (response, "Response is byte array"); + } + + /// + /// Test AddPetUsingByteArray + /// + [Test ()] + public void TestAddPetUsingByteArray () + { + // set timeout to 10 seconds + Configuration c1 = new Configuration (timeout: 10000); + + PetApi petApi = new PetApi (c1); + Pet p = createPet (); + byte[] petByteArray = GetBytes ((string)petApi.Configuration.ApiClient.Serialize (p)); + petApi.AddPetUsingByteArray (petByteArray); + } + /// /// Test UpdatePetWithForm /// diff --git a/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb b/samples/client/petstore/csharp/SwaggerClientTest/obj/Debug/SwaggerClientTest.dll.mdb deleted file mode 100644 index d4c01b5c42a8c3b132647584a5049b0c6ed86807..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 31212 zcmdUY2UrwW`~AH;3+%G4x)g=AfFL#mWEU)e4KUW&q9y?q0TDqdQY;u1uqAe}_kvxq zHxRIQ6BA49y=#hHV~PKBr?HD@%>Vhm@9`%&d(OP?otZoDymRlJyE7ZRWy9XOR=eBG zK!ktGjy%43>2`k8tf#x{*zHl+{5FV?M7VnNB&003FP786O#e1e&^eTlpW&})2c!6p zt;hbo!#@>R%`Xu$lX`Vdj!H`Q8W7XBZ%lYxWbdf>Xs@7zo>5*Yafx2Z1Hz-Dqmn!# zVTg{3_eu_rOY9q!>=oHJCMrI~D={i1IVB+}$}2LtcX(2w*H=REAl}<4DmlfgO-zKj z)hjtE(km`JCSF>nWjm>WSJT88ul7+XAkWC;9?RmJ9PgRgX6wViQyEFiXZd}XJk595 zvO9-%Yu^YUh0p8 zM+dvPKJIO-W*_qMo(-A*In`arHI_PpDj{9Z1SQ1xiiu853je@CblSZn@y@AN z&m1PN4|{k?;Ya3vP6zQN+PJ=6LE$M;(FsX|N;n5I3l=G@_S|e~X#4xND`}lheqI-` zQ2lmEJ)@FJsC$8DrP#__3JVP*e3NI}c%CCOKEKeT=`W$?z5~jZKeyeFoBH~N-0rZcwE$ggrq*TyI?SkF1TTT zA5UM;rpd`saS?q7HBCuLiit=~DXHeizIk{dX`i8o;&uhUd9>bPg3-5v5RMQfAr^#K z5@JON#@rZkTN9!oq!b}qLP`@-Mi{rF@IwXlx78aAMnY*>wbsYQMopiTCr`^iE6+AY zxYw+Jzh76qSVC7$S58f*I*@4&(;b8&-*eQ~Cd6Qf#5UAgNAG}OHQnYwwmamC1+qA5 z$9!sf)`6UJI4_!Ka}-t&`lkbV=arsfmk9>s|>-apHo7b+4GdQR0H7Dls8BB`~4qAYx_PJ0&GCOjt22 zJd%y8l8MUZeJfF`lEkbe*4D`>;VG%f?Cu9uWw%OY3g~4@xV;>;5AgT5F&O-Vg4}+z zi46)0j5XAasAm(wSt+b29HF+ch7e;pn~i<-!F@W$q98sRx+@x6H;Ch7QrSt{_)F)? zm9<)J&8Avi?cmB<2dzULZFOHqt*&9~N?L8*wptIZu4{aG8(r7r@>;!%otpmPNPeg= zwE`c1Y=+LNNM=`@Q&C=CS&^)&xLR1|jwnr|oLiCPRonsB|CK18QvUCv{B0jZ`P)P> z%BL!lKP$beBuDjKWs>fc;Uq6lbRv_SCS#eBqIAJkdBK7O+=jp6O4lh}Sxpx>k=0IX zQ1bH+`Z4-DQv0?=$wBw=3yd&u)(VRcCU*c!ZvQ;)Z+4w1tZDp*)4YoRS03*rdSoh2 zL1Y>`1(ke}>W7`kP3J$I<)DvnAtPNzxyZ{?UC1<-=~ymy68^9(eiD|rko7JbQ1buE zN%+h1e{d3<>a}x!?<9mL<0OO+luyD>F65r;Q&&0YKe&-GZe!i#b}ffUf%3ZwzzK&oz)d!w%80219gV`zH+Kq~Vl_St@_e zK<*nJh>krfseGo93^$H23cF=ysr)P>nQfdSIIDj#4MHn%Sc`sUyF|UrKIv%K4gl|R3D)}%q*2(=|fietQH(f1-G5PcSEVz z<3slP?30V^WkrhLQYvowklQ|Y$^^N zT&MhvrQ(1uIp}++nAxDXrSg% zd?14Qq$^NT8k9H2P(-n@E-9?L6J`Ie4MjH5-IU;v#wbc29}461e=`UvaRgFq@DbJz z-CkIK*6q~}wo@xE*CnItXVvG=H?AVZyar@`g9Q!b<(vj&ZG&}KHXjqB-V^xSe)0aO zHaiss4angJM^N@NZjUi@qu^$J_?Ewg`AvSwqrDOXjoW?UCf}rOb@WDv?=>JJ{73rB zAx#e;83CCA^75nrGC3d%%kPDFGJnr+8sdckWKBR0%6{%4o{Rhaj}7#M>^7TFDLK|I zHA)^?y99Ld5Cd+K(|o{>1&})p?>3YJ{HPIm+~`Roc{!so$!t8lF~7{Rfxpp5^0WCX z#pK2$tML>#Klcb{}_ z?d0X#?Z};WcZFqS?`A7@<01|+xaaN2i*_&J{M@s*!0KZ+CuXtz$9CYo(J`Vp zr9D~OVO<9~YI8f1c^&6>l$Y0ZBsm?|V)?z)U2i%m?aop+zau%+@i5AM?m^vw>F0kr zaw~ak>{_$rv9W8TE}r7pxJMG2iXH=4lj~3i0l(Xk4DU3elN{jjoymmG6FbYx^E#9H zofinpNZVXYH_KC1-ujx{ z{`$_>^76B<$@8yY2+N4;K1?CY-j2 za1%qxq|nKs{Kl~{=8)D|5lU8uu998Xr27YMZz$Opy5Gzpt#dJyTnfD`yKYI-n%s*} z@-p-uHlx{;~frgf7lz#P&#Yr2t~Zfj-NTWOk;JJ^jJ>UP-7A+2+@ z8@bl)y694J4w#hmGx|wS!f3U6ty=lI8+p_1tz5=coVfIni|O!>FS(#QS=fD1ccF4h z&VZ6Op@slGzAzG=oGDdahlUOhVW^ddyOSf`kIH46vDr#b<+JYOdG{CQR-~a#0vr9F}cv^-yjLBiqArVYMVyNl|!~B{_vqJm`XlTPP4sAE8DHYCwj(7L$T zyXb1yb98YLWKADgdI!kTq(F6#293Y`Dl&%obdHGlk6|Re$I%`{p)iR|(YLXfcvEu2 zsBKz+jh}yzxYvr+vErR@@;3bMa6bI7D;GwPMG=c5q|=ejCWnRRp6t}h^$}!4#75b< z7S2e0gu&2LA0m{|8RNgKrZZMUg(ApL5yw$fp(xXdRD4v=ukf%}e6)0`6iVSq zpt@_Rf;L=?`Oo%gl>257t7`!^9nEgkBW?X{{195y!p~pt&%NfKiQuTJy-k!@F`c1F z4I6EBou{YXQ)ge(v8KJ7&Qn)I=d4z~j384YS49$qHBt5qPYEZ~Dl#D+bx9!#E8!ug zWTI3F&pM^_M)D-#ZH$4OrKR9hsx0EdQzCm?s`)Z)@hqE_wPkWjQdD@HLPMi88sQM! zjRLnQR8U2`9EF1Wp5`d1ayq{8rWOn6I0d!LXPXA6f>+bHY)(+w+y+r?;12K^ zhS`5M+m648P}^nzVt}WiA`L-?AU?%xYZ=&=Dz8@l9Z7!enG=O^BBfCZ z@zAJVI552jJD<}O)Xp|=s;#Y`xO<&JT=`}%aPd_oGw9OoK z+6rprqG+->Iy+h_xE%%k41Ag9ZCusLBhln&^fB4J4{k-OhCfub@?JE#AN>GMj#x&d z_UaXtM5rPznJSbxlRXt;7BTTXqXrVrvM*i$LXIib$*B>- zmB5KRwz3ss7O_5H@DjFRvUQOD4olj1{aF z=qLPaU@z^#Hmc%ZVJx(;pmVZpL5gtTTTNK2S!q}a%w-)c^{h{!)5*K30#n?-7 z2`$^7v&Gw3@^|bzbE})hls;r?pJ{!hTG+C()h$-`A*=eVHn;j%?Ce8!_1P_2ExBlF z!_{Fy=wZXzFy@@`$sNV>Q)O_KavF9q_>T+L8*!ER`0I^9t%KS?;txB~H7V;;)=%f9 z!{edo>x6$0?2rGawmjX3{MzTtKke_KxIcXNH!kSC4XZ8p_az7V9_%X|p(Xb%wed4V zuyVFlz3N+zjU(gY#>YwCuE=h_W7X;^RMT3nj3cY!R?FUaY7@(^>0x;=jvR_REPMJ< zTeff1-SS!-xgK{z_6(tTo(3+p)=6#oI*z=Fdn@}!@?R*rSk8ziGvjB)OO+7J)h*Y? zlXdayW%F3E^!|8qApT%6b9Kv$@#IqcW!XHLFYRXeB%VBte^$&~%W_Nt8JjRJf%RNw z&l1s6!jnbqlcIXX;Qc$IwB(keN%ZgN@82;L^TX^&w02r;Wt~oKxhR3`OxT632nDy{ zLKXt#Zh0qx+)cR0T;h|br5xF|@>ug4Y8zD7Ce)^(K5%&79emg->g?@x&h}2aDtdc+ ztz~8+8J;*UQQGcBtkj1ur?uRfNOmReW-e*FmDqN#^4qnGtS6iXetTNW^NHj_;!PB$ z#4;%=F(D~MsOV#MM0u!`?;q3}38=Ol-H%M}m(@?ILID6{P9#1Z-R$D#mN1pe4A$y$IrYcxX zOd^w#CMO9yu;O^Dv(?fhvMg!2Y^}!1R<_!aMDmjg%&o3gza)_pNhe{Ygf)6NTUMMG z4$aTs&o3kdABKg_lwPkC$)`2dswz`uiL^Rh<>vFdROd6M$f-0H0QK9&5CIwn=x ziV$Me{8X|ab)mV{Rkb;lY)RcJTRqt6a8?~jB}Y?_nOogdS5wKg)a$ak!Uf08~RV}Mls zFq70#T^m5I54a)wVoXv;^>zUHd%!!{mtvYanX1Uu$RLRnO*L#$NGQ=-EU#+n^&Zap z+IoE*SMjqJGR?D!u%K4W8c1djoHOwKe4DIb>4O^)IpgLSGJ|chD8S!iUb zSXch=5tLdrdJvg7Xx1PhAZnA$R6ia>o(y^_dxXqXk4q!t(n(Cj@$nmtFWh$z8=U@~NoK0eGm}rn_dZH!!1$!(TQRR1eqwvZrzbK~J@q>>`@1>V4QnFQoM~pN zUw=p5eD_xNnP#SX#t<@d$gCmKdS;pF$J#V06U7A+Q?aZR@=<8>^d5SB{i>`1G&<>p zzhOQqf9F?_6 zT3Y`wjEosJc9`T5($YG67+ErGskznJI(Hb!8@5BX3Js?9@nPiWVZWGLU9E2oBe#d$ zfmLpRtp7!yWc_*=$w;S}=~$bcKx@vlSF+BBy&##Z4-6lTzaAink*lYnbp!TLIbzA17FG1tt}C5q(_T6s%x&pawC)8EOPM8f~)2=EN?RD+hUFynyJGn znKqnG2Z=l9n*kS14lHYj({;rh)inoTIXIjiDsu2mgp=k9ELVrqYsDN@H7{ZLYdC#X z9Q2uiX>&?z8s=e(o3W)&=}N6y4w!UyY#i}$*G^TxMqyejI1c~xJh);t-Ft7|kJ`MnshQd}99 zG1jG?!Seij`hqzu2~8wa6)CkH!Q5K9h-sWg`E(9qi1M z;%pGwSWLM3`S^DPr3LUyAwe!iy;1LL2y*ekp14vfL$4F3?ckSh>wloUsunmnnvm1R9&OgSE<3& zC)f7WSV|s_rH?>}o+8qlP$`7PW0y?rFg=Ut{hQd8$4SzEa&0olQ!;lvod+^KmqjO0 zp_bm+WIvOGgqy_fX8n^geNZhUPMl4Mcw+gpiqq(u6k&vq|5kxzOjX1P^}!j#>GaYl zYigAI>15{*z6wfjoWn^I(49=68$qatIxJj#8<@~iVKH&x(NUNl!wf4f6Vv2h#qO1H z6B#hO?kYZW+^ni=D`98Y;>?NYjwjMWkV09MrQ%CSZDR06fx@aUsC`rlE--ACa>BHJ z)&7(kzNQMlF6?;o`QuFs(EGC~R)1SuY6c_sMx0mO(?m?z%1S4t170#!T9mS=UJ8;c zbsxK)Jc%xzgc?{AMIz3$TDrWwVUn+JZ^E%l+nXpY*cI+gEEI_bVks9k5UZlX2BKnx z4Mfcs7SGC0tcm?_I}ns)3^WG%1ciXog88M0pjt-!`MMa4wQv~(;@WdD_y!tX3_d}% z48Ed)kE&K_#r_KHnx{(v@#PSgN6-At6#zq*qqfC@Ug`D!XB8{8`6#?jExgGrW>kD?9IsG!EgEOrhI#&h2H#A4@YS|cR#w(Rd!cmJaN3>N z%%!RHvgy{W@TEjl=M;QFQHrUrV^VszP3V-yu01X1jO|7E#~OUuhqygwWdmGL%KF&e z_-W|3r_r?_1XQe@v=wO^n1cx@T3uUP`-PoadkL#NnnoX+t|`}q-*tT!27c#kzX(Pp zZB17s9@123^eD=t3h|SW0tt_!Y0?RnMrd%VgVzy4e=3*AVMglE`1E%A7|2^SfQdC`%~LI?3gv4{BFykl6*ZMq1^MC z^aU%f6xs~d7ASD2oFdUE)FYT(5%}YKPMZPhl!HI4fVp~n!+`G?%IrXi{5iCs zs9t+(A&ivo@L&`^7kD2uE=4>)~H)%`dmt8%%w9y;y!stP?>eGte;Ca z6gl*44aYKvU^zUO9x3LiR^}Qk*XPn3qC>@H;HhkUBb8DL>#6Ze4X@yNJ(s=_3&2X} z%tP-ykIn{+j(BI3_eQYmA}pn0kR@@KXua)Q|mCLY@IX zm7rKcO9gfv3$H&b(y$NvtppYOjRpG$cE#}d|}PV45;Jicl;9jNW$ z`MC3&Pmh9Fu((~)qa5@iOqb@<%cdUjnFRVA#uxMHOVOv|vMkKwlC^-6DGTUS5Zf%< z(S`Mbg8LF3ReM)h1qnc=u>gqtV#^mITSdbO)rS$ zShzBlP?EWX4hP9snHa9UY$N}xa25N}02Z#|KN&C;b)2?@F665!Tnjsw;?8X;-3{Wy z^;~*LiJpMzI$AH+@S-93iZ&*e* z@+L96GPs!>vg;h%h~46lh9$R4#xYqNg#-%>3H1xL&3dn4`api+o$?Q~Qsyu8vyhp* z?!~{(zZdn~w~QV)IfBQ_DS5J-J_Ye1n;<=JMMtinWYh{e8YFw9kS&05;R?D)^r^Vt z)O^U&snmk+fGd9mEf7nvU|oW~yn}ssbK8*Zz$=*Qz z;B{%%p#M{}N_YpK1XE|s zD~xAW(X*mY#f{PMVM~*u_86WgtLRg)0E^m`)s#$KO{an6D{>k43ya!xw)Q`ym@gkN z_Qw2wBw)qfnrE>xe`kIf>bZP1-N;v0xJXW~q2$*!^bClP)sGtKt>U{d-CINNn|h>J zW#(XrlS4;<*jg%XRjFbrHXp79Idq{|f(2_A^zIzGhc}5Sb`9eLtiFw{{tv;DQVdt- ze=NmHdeObuwaI>H12sOCL$8<|%eZxvj9*75fcUWeDZh-p0H%fO=ps{(6t-L#^VZQF zqED$%aR>0g6$V$Wi#kjG?c~!a^6NT!Ml6Z&Dc(V+ucsO7O>%9%Vhbh)v6)}kW~ ztw_GDbSg+#Q^j30AD=7M!?$58-6$4eiEnDuO*5DoK}WN)Je zcec{ICUyIB8|GiP(MKRL7Sp5wrXq7Y+TZPT1jxiE#bQ3p3%1jRl9y9)_k?Rlx`*TP z;Valq3&kRc1$PDd>UMg~WUZ(F?xHaZ!3VP8{YwQeK|IDjpKPa3O=|OdE+v2D(mz4` z5pvu@=|bVs^KixI(M*tuPds{VF3j`t=zQ6$;_eF`C<`v^p~J7=g})B zYdvFYeR`AeFOI(03ylx4(?@yqu}O7)+ks*44*Ca3Jj6xPg}}XoF+HDVAR)-dxuDb|moahQxfX6>d^#2vG`jM+oU*gbR{NIdps^4lx( zV4S~)E-?2=$DRvw-X6L`_Nut2@7+-HZv~z~k+XZ~Ik6<$ZN^^QfA6KkLBeiTT>2;6 z8Zp(ys4hB_I^4CB*kT{^*{HbB@DaF zGUOkEQDRTB26f2UPuGf7VYS}61{I0e=qp)JLrOv2*A>$@&@{AXeVfU;2Y@r;Mzb8bSStP5DT3S?hW*T&IXSM`aNj|;3Ggf^d<0lAOre2_&$&ct-}S)0mGqdfhz+epqqi~0VAQi zgF6DFpa+5b0HdL^m<{+IItRP}SPA_zI1g9_{S15wSPhLAoQMKg1MLlV19G5SfExj8 zp~JwPfpySB!F_@C(DT4!fep}k;8nmz=>2GT!hucDr@<$H&Cs{N*MTk23N%QMp|?Vp zMuW5x%iEwULstN{LwkbVfn4a;V1FPF`fD^=kD+%!M??1n@}UQSQ-A{KZ16;&5c(Jz zwpPGS=!@WUz%JQa1eS5coJ|3IvczYI1IfDydF3LeZifOXy7RH1Mpqo81!rKOW;RnhuWA11b%|{ z_CVdCk3% zK=80%0eB5Sq0fMi01D_w;F|ykt*wV`Kr5lELhAtwXn(LbUb&W40IlN3Q!jMXYfHl z2mJti39x~-Xn^=Z+d@}>wgK#*y}>mAd+6riMnE~}Zs1NpdFZ*|1i%4$J9s7F2z?5? zAJ9W<{gAWJ6`3iPkw9|0HW z-@rEjS7?Pl&OdZjXb0#rfE%%S&{LQVNQ1^th>@+pVCX(yq74APgI)_B2@HWg11@M&NU^lR{+z+7n8uh6Ff^Pua3jlg{9Tj2J<0_d0EXTU;e zn@;E_fkn`sU>9I9bbD|kAR9Uo+yhtwU9mIb54{xH3%WM247w$_F|Zsu3j8gw0(ulU z6<7&93p^cI1>K?x#^%tgp+lj+0oFjLg8KkD(38O9!&&0+q04kb9DrY-J-|-D3F!9V zhQLYaNN^9}6!aBvGH@FDG5Am5SLo8+aV~%}(6zypfwR!Baa31IMWTSK(6k5IH0W#4cF;QDI&>XyRp176 zTW}NLCUie=cidXLblslFW$3@4TS9*Uyn>Dbe+#^Z9u7_g z-axMhPXXRS?*;DyDB Date: Mon, 11 Jan 2016 16:16:49 +0800 Subject: [PATCH 40/47] better filename handling in objectseralizer (php) --- .../resources/php/ObjectSerializer.mustache | 19 +- .../lib/ObjectSerializer.php | 19 +- .../SwaggerClient-php/tests/PetApiTest.php | 499 +++++++++--------- 3 files changed, 285 insertions(+), 252 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache index f53416e4c52..a264c13af30 100644 --- a/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache +++ b/modules/swagger-codegen/src/main/resources/php/ObjectSerializer.mustache @@ -79,6 +79,23 @@ class ObjectSerializer return $sanitized; } + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + /** * Take value and turn it into a string suitable for inclusion in * the path, by url-encoding. @@ -232,7 +249,7 @@ class ObjectSerializer } elseif ($class === '\SplFileObject') { // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { - $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php index fdd2f696189..e7417fc42f2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/ObjectSerializer.php @@ -79,6 +79,23 @@ class ObjectSerializer return $sanitized; } + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param string $filename filename to be sanitized + * + * @return string the sanitized filename + */ + public function sanitizeFilename($filename) + { + if (preg_match("/.*[\/\\\\](.*)$/", $filename, $match)) { + return $match[1]; + } else { + return $filename; + } + } + /** * Take value and turn it into a string suitable for inclusion in * the path, by url-encoding. @@ -232,7 +249,7 @@ class ObjectSerializer } elseif ($class === '\SplFileObject') { // determine file name if (array_key_exists('Content-Disposition', $httpHeaders) && preg_match('/inline; filename=[\'"]?([^\'"\s]+)[\'"]?$/i', $httpHeaders['Content-Disposition'], $match)) { - $filename = Configuration::getDefaultConfiguration()->getTempFolderPath().$match[1]; + $filename = Configuration::getDefaultConfiguration()->getTempFolderPath() . sanitizeFilename($match[1]); } else { $filename = tempnam(Configuration::getDefaultConfiguration()->getTempFolderPath(), ''); } diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index c81b07b38fd..a7f53d5c5ba 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -5,257 +5,256 @@ require_once('autoload.php'); class PetApiTest extends \PHPUnit_Framework_TestCase { - // add a new pet (id 10005) to ensure the pet object is available for all the tests - public static function setUpBeforeClass() { - // for error reporting (need to run with php5.3 to get no warning) - //ini_set('display_errors', 1); - //error_reporting(~0); - // when running with php5.5, comment out below to skip the warning about - // using @ to handle file upload - //ini_set('display_startup_errors',1); - //ini_set('display_errors',1); - //error_reporting(-1); - - // enable debugging - //Swagger\Client\Configuration::$debug = true; - - // skip initializing the API client as it should be automatic - //$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); - // new pet - $new_pet_id = 10005; - $new_pet = new Swagger\Client\Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); - // new tag - $tag= new Swagger\Client\Model\Tag; - $tag->setId($new_pet_id); // use the same id as pet - $tag->setName("test php tag"); - // new category - $category = new Swagger\Client\Model\Category; - $category->setId($new_pet_id); // use the same id as pet - $category->setName("test php category"); - - $new_pet->setTags(array($tag)); - $new_pet->setCategory($category); - - $pet_api = new Swagger\Client\Api\PetAPI(); - // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); - } - - // test static functions defined in ApiClient - public function testApiClient() - { - // test selectHeaderAccept - $api_client = new Swagger\Client\ApiClient(); - $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); - $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); - - // test selectHeaderContentType - $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); - $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); - $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); - - // test addDefaultHeader and getDefaultHeader - $api_client->getConfig()->addDefaultHeader('test1', 'value1'); - $api_client->getConfig()->addDefaultHeader('test2', 200); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertSame('value1', $defaultHeader['test1']); - $this->assertSame(200, $defaultHeader['test2']); - - // test deleteDefaultHeader - $api_client->getConfig()->deleteDefaultHeader('test2'); - $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); - $this->assertFalse(isset($defaultHeader['test2'])); - - $pet_api2 = new Swagger\Client\Api\PetAPI(); - $config3 = new Swagger\Client\Configuration(); - $apiClient3 = new Swagger\Client\ApiClient($config3); - $apiClient3->getConfig()->setUserAgent('api client 3'); - $config4 = new Swagger\Client\Configuration(); - $apiClient4 = new Swagger\Client\ApiClient($config4); - $apiClient4->getConfig()->setUserAgent('api client 4'); - $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); - - // 2 different api clients are not the same - $this->assertNotEquals($apiClient3, $apiClient4); - // customied pet api not using the old pet api's api client - $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); - - // test access token - $api_client->getConfig()->setAccessToken("testing_only"); - $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); - } - - // test getPetById with a Pet object (id 10005) - public function testGetPetById() - { - // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (model) - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getCategory()->getId(), $pet_id); - $this->assertSame($response->getCategory()->getName(), 'test php category'); - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); - } - - // test getPetById with a Pet object (id 10005) - public function testGetPetByIdWithHttpInfo() - { - // initialize the API client without host - $pet_id = 10005; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI(); - $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); - // return Pet (model) - list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - $this->assertSame($response->getCategory()->getId(), $pet_id); - $this->assertSame($response->getCategory()->getName(), 'test php category'); - $this->assertSame($response->getTags()[0]->getId(), $pet_id); - $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); - $this->assertSame($status_code, 200); - $this->assertSame($response_headers['Content-Type'], 'application/json'); - } - - // test getPetByStatus and verify by the "id" of the response - public function testFindPetByStatus() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // return Pet (model) - $response = $pet_api->findPetsByStatus("available"); - $this->assertGreaterThan(0, count($response)); // at least one object returned - $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet - // loop through result to ensure status is "available" - foreach ($response as $_pet) { - $this->assertSame($_pet['status'], "available"); + // add a new pet (id 10005) to ensure the pet object is available for all the tests + public static function setUpBeforeClass() { + // for error reporting (need to run with php5.3 to get no warning) + //ini_set('display_errors', 1); + //error_reporting(~0); + // when running with php5.5, comment out below to skip the warning about + // using @ to handle file upload + //ini_set('display_startup_errors',1); + //ini_set('display_errors',1); + //error_reporting(-1); + + // enable debugging + //Swagger\Client\Configuration::$debug = true; + + // skip initializing the API client as it should be automatic + //$api_client = new Swagger\Client\ApiClient('http://petstore.swagger.io/v2'); + // new pet + $new_pet_id = 10005; + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); + // new tag + $tag= new Swagger\Client\Model\Tag; + $tag->setId($new_pet_id); // use the same id as pet + $tag->setName("test php tag"); + // new category + $category = new Swagger\Client\Model\Category; + $category->setId($new_pet_id); // use the same id as pet + $category->setName("test php category"); + + $new_pet->setTags(array($tag)); + $new_pet->setCategory($category); + + $pet_api = new Swagger\Client\Api\PetAPI(); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); } - // test invalid status - $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); - $this->assertSame(count($response), 0); // confirm no object returned - } - - // test updatePet (model/json)and verify by the "id" of the response - public function testUpdatePet() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // create updated pet object - $updated_pet = new Swagger\Client\Model\Pet; - $updated_pet->setId($pet_id); - $updated_pet->setName('updatePet'); // new name - $updated_pet->setStatus('pending'); // new status - // update Pet (model/json) - $update_response = $pet_api->updatePet($updated_pet); - // return nothing (void) - $this->assertSame($update_response, NULL); - // verify updated Pet - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getStatus(), 'pending'); - $this->assertSame($response->getName(), 'updatePet'); - } - - // test updatePetWithFormWithHttpInfo and verify by the "name" of the response - public function testUpdatePetWithFormWithHttpInfo() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // update Pet (form) - list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); - // return nothing (void) - $this->assertNull($update_response); - $this->assertSame($status_code, 200); - $this->assertSame($http_headers['Content-Type'], 'application/json'); - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'update pet with form with http info'); - } - - // test updatePetWithForm and verify by the "name" and "status" of the response - public function testUpdatePetWithForm() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_id = 10001; // ID of pet that needs to be fetched - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // update Pet (form) - $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); - // return nothing (void) - $this->assertSame($update_response, NULL); - $response = $pet_api->getPetById($pet_id); - $this->assertSame($response->getId(), $pet_id); - $this->assertSame($response->getName(), 'update pet with form'); - $this->assertSame($response->getStatus(), 'sold'); - } - - // test addPet and verify by the "id" and "name" of the response - public function testAddPet() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $new_pet_id = 10001; - $new_pet = new Swagger\Client\Model\Pet; - $new_pet->setId($new_pet_id); - $new_pet->setName("PHP Unit Test"); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // add a new pet (model) - $add_response = $pet_api->addPet($new_pet); - // return nothing (void) - $this->assertSame($add_response, NULL); - // verify added Pet - $response = $pet_api->getPetById($new_pet_id); - $this->assertSame($response->getId(), $new_pet_id); - $this->assertSame($response->getName(), 'PHP Unit Test'); - } - - // test upload file - public function testUploadFile() - { - // initialize the API client - $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\ApiClient($config); - $pet_api = new Swagger\Client\Api\PetAPI($api_client); - // upload file - $pet_id = 10001; - $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); - // return nothing (void) - $this->assertSame($add_response, NULL); - } - - // test get inventory - public function testGetInventory() - { - // initialize the API client - $config = new Swagger\Client\Configuration(); - $config->setHost('http://petstore.swagger.io/v2'); - $api_client = new Swagger\Client\APIClient($config); - $store_api = new Swagger\Client\Api\StoreAPI($api_client); - // get inventory - $get_response = $store_api->getInventory(); - - $this->assertInternalType("int", $get_response['sold']); - $this->assertInternalType("int", $get_response['pending']); - - } - + + // test static functions defined in ApiClient + public function testApiClient() + { + // test selectHeaderAccept + $api_client = new Swagger\Client\ApiClient(); + $this->assertSame('application/json', $api_client->selectHeaderAccept(array('application/xml','application/json'))); + $this->assertSame(NULL, $api_client->selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderAccept(array('application/yaml','application/xml'))); + + // test selectHeaderContentType + $this->assertSame('application/json', $api_client->selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', $api_client->selectHeaderContentType(array())); + $this->assertSame('application/yaml,application/xml', $api_client->selectHeaderContentType(array('application/yaml','application/xml'))); + + // test addDefaultHeader and getDefaultHeader + $api_client->getConfig()->addDefaultHeader('test1', 'value1'); + $api_client->getConfig()->addDefaultHeader('test2', 200); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); + $this->assertSame('value1', $defaultHeader['test1']); + $this->assertSame(200, $defaultHeader['test2']); + + // test deleteDefaultHeader + $api_client->getConfig()->deleteDefaultHeader('test2'); + $defaultHeader = $api_client->getConfig()->getDefaultHeaders(); + $this->assertFalse(isset($defaultHeader['test2'])); + + $pet_api2 = new Swagger\Client\Api\PetAPI(); + $config3 = new Swagger\Client\Configuration(); + $apiClient3 = new Swagger\Client\ApiClient($config3); + $apiClient3->getConfig()->setUserAgent('api client 3'); + $config4 = new Swagger\Client\Configuration(); + $apiClient4 = new Swagger\Client\ApiClient($config4); + $apiClient4->getConfig()->setUserAgent('api client 4'); + $pet_api3 = new Swagger\Client\Api\PetAPI($apiClient3); + + // 2 different api clients are not the same + $this->assertNotEquals($apiClient3, $apiClient4); + // customied pet api not using the old pet api's api client + $this->assertNotEquals($pet_api2->getApiClient(), $pet_api3->getApiClient()); + + // test access token + $api_client->getConfig()->setAccessToken("testing_only"); + $this->assertSame('testing_only', $api_client->getConfig()->getAccessToken()); + } + + // test getPetById with a Pet object (id 10005) + public function testGetPetById() + { + // initialize the API client without host + $pet_id = 10005; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + // return Pet (model) + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + } + + // test getPetById with a Pet object (id 10005) + public function testGetPetByIdWithHttpInfo() + { + // initialize the API client without host + $pet_id = 10005; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI(); + $pet_api->getApiClient()->getConfig()->setApiKey('api_key', '111222333444555'); + // return Pet (model) + list($response, $status_code, $response_headers) = $pet_api->getPetByIdWithHttpInfo($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + $this->assertSame($response->getCategory()->getId(), $pet_id); + $this->assertSame($response->getCategory()->getName(), 'test php category'); + $this->assertSame($response->getTags()[0]->getId(), $pet_id); + $this->assertSame($response->getTags()[0]->getName(), 'test php tag'); + $this->assertSame($status_code, 200); + $this->assertSame($response_headers['Content-Type'], 'application/json'); + } + + // test getPetByStatus and verify by the "id" of the response + public function testFindPetByStatus() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // return Pet (model) + $response = $pet_api->findPetsByStatus("available"); + $this->assertGreaterThan(0, count($response)); // at least one object returned + $this->assertSame(get_class($response[0]), "Swagger\\Client\\Model\\Pet"); // verify the object is Pet + // loop through result to ensure status is "available" + foreach ($response as $_pet) { + $this->assertSame($_pet['status'], "available"); + } + // test invalid status + $response = $pet_api->findPetsByStatus("unknown_and_incorrect_status"); + $this->assertSame(count($response), 0); // confirm no object returned + } + + // test updatePet (model/json)and verify by the "id" of the response + public function testUpdatePet() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // create updated pet object + $updated_pet = new Swagger\Client\Model\Pet; + $updated_pet->setId($pet_id); + $updated_pet->setName('updatePet'); // new name + $updated_pet->setStatus('pending'); // new status + // update Pet (model/json) + $update_response = $pet_api->updatePet($updated_pet); + // return nothing (void) + $this->assertSame($update_response, NULL); + // verify updated Pet + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getStatus(), 'pending'); + $this->assertSame($response->getName(), 'updatePet'); + } + + // test updatePetWithFormWithHttpInfo and verify by the "name" of the response + public function testUpdatePetWithFormWithHttpInfo() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // update Pet (form) + list($update_response, $status_code, $http_headers) = $pet_api->updatePetWithFormWithHttpInfo($pet_id, 'update pet with form with http info'); + // return nothing (void) + $this->assertNull($update_response); + $this->assertSame($status_code, 200); + $this->assertSame($http_headers['Content-Type'], 'application/json'); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form with http info'); + } + + // test updatePetWithForm and verify by the "name" and "status" of the response + public function testUpdatePetWithForm() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_id = 10001; // ID of pet that needs to be fetched + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // update Pet (form) + $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); + // return nothing (void) + $this->assertSame($update_response, NULL); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->getId(), $pet_id); + $this->assertSame($response->getName(), 'update pet with form'); + $this->assertSame($response->getStatus(), 'sold'); + } + + // test addPet and verify by the "id" and "name" of the response + public function testAddPet() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $new_pet_id = 10001; + $new_pet = new Swagger\Client\Model\Pet; + $new_pet->setId($new_pet_id); + $new_pet->setName("PHP Unit Test"); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + // return nothing (void) + $this->assertSame($add_response, NULL); + // verify added Pet + $response = $pet_api->getPetById($new_pet_id); + $this->assertSame($response->getId(), $new_pet_id); + $this->assertSame($response->getName(), 'PHP Unit Test'); + } + + // test upload file + public function testUploadFile() + { + // initialize the API client + $config = (new Swagger\Client\Configuration())->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\ApiClient($config); + $pet_api = new Swagger\Client\Api\PetAPI($api_client); + // upload file + $pet_id = 10001; + $add_response = $pet_api->uploadFile($pet_id, "test meta", "./composer.json"); + // return nothing (void) + $this->assertSame($add_response, NULL); + } + + // test get inventory + public function testGetInventory() + { + // initialize the API client + $config = new Swagger\Client\Configuration(); + $config->setHost('http://petstore.swagger.io/v2'); + $api_client = new Swagger\Client\APIClient($config); + $store_api = new Swagger\Client\Api\StoreAPI($api_client); + // get inventory + $get_response = $store_api->getInventory(); + + $this->assertInternalType("int", $get_response['sold']); + $this->assertInternalType("int", $get_response['pending']); + } + } ?> From b87d6a0f36ca8233f099801246560d7998c4b911 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 11 Jan 2016 18:10:02 +0800 Subject: [PATCH 41/47] Java okhttp-gson: implement the "debugging" option for ApiClient and upgrade OkHttp --- .../libraries/okhttp-gson/ApiClient.mustache | 14 ++++++++++++++ .../Java/libraries/okhttp-gson/pom.mustache | 7 ++++++- samples/client/petstore/java/okhttp-gson/pom.xml | 7 ++++++- .../main/java/io/swagger/client/ApiClient.java | 16 +++++++++++++++- .../java/io/swagger/client/ApiClientTest.java | 9 +++++---- 5 files changed, 46 insertions(+), 7 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 8c0880bf217..c80f45b91a5 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 @@ -11,6 +11,8 @@ import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.lang.reflect.Type; @@ -116,6 +118,8 @@ public class ApiClient { private OkHttpClient httpClient; private JSON json; + private HttpLoggingInterceptor loggingInterceptor; + public ApiClient() { httpClient = new OkHttpClient(); @@ -452,6 +456,16 @@ public class ApiClient { * @param debugging To enable (true) or disable (false) debugging */ public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } this.debugging = debugging; return this; } 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 index 0d7e9015101..982334a3914 100644 --- 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 @@ -117,6 +117,11 @@ okhttp ${okhttp-version} + + com.squareup.okhttp + logging-interceptor + ${okhttp-version} + com.google.code.gson gson @@ -133,7 +138,7 @@ 1.5.0 - 2.4.0 + 2.7.2 2.3.1 1.0.0 4.8.1 diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index 9fa057be939..4eaf536b2c8 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -117,6 +117,11 @@ okhttp ${okhttp-version} + + com.squareup.okhttp + logging-interceptor + ${okhttp-version} + com.google.code.gson gson @@ -133,7 +138,7 @@ 1.5.0 - 2.4.0 + 2.7.2 2.3.1 1.0.0 4.8.1 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 7fb4cc49bf3..782f3b239c5 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 @@ -11,6 +11,8 @@ import com.squareup.okhttp.MultipartBuilder; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Headers; import com.squareup.okhttp.internal.http.HttpMethod; +import com.squareup.okhttp.logging.HttpLoggingInterceptor; +import com.squareup.okhttp.logging.HttpLoggingInterceptor.Level; import java.lang.reflect.Type; @@ -116,6 +118,8 @@ public class ApiClient { private OkHttpClient httpClient; private JSON json; + private HttpLoggingInterceptor loggingInterceptor; + public ApiClient() { httpClient = new OkHttpClient(); @@ -141,8 +145,8 @@ public class ApiClient { // 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()); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -451,6 +455,16 @@ public class ApiClient { * @param debugging To enable (true) or disable (false) debugging */ public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient.interceptors().add(loggingInterceptor); + } else { + httpClient.interceptors().remove(loggingInterceptor); + loggingInterceptor = null; + } + } this.debugging = debugging; return this; } 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 index ba143470c9a..43c5ee2b86a 100644 --- 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 @@ -186,14 +186,15 @@ public class ApiClientTest { @Test public void testGetAndSetConnectTimeout() { - assertEquals(0, apiClient.getConnectTimeout()); - assertEquals(0, apiClient.getHttpClient().getConnectTimeout()); - - apiClient.setConnectTimeout(10000); + // connect timeout defaults to 10 seconds assertEquals(10000, apiClient.getConnectTimeout()); assertEquals(10000, apiClient.getHttpClient().getConnectTimeout()); apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().getConnectTimeout()); + + apiClient.setConnectTimeout(10000); } @Test From cba7e063e1cd6dd5f3349e4da17a550688b32787 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 11 Jan 2016 21:01:02 +0800 Subject: [PATCH 42/47] add test case for objectserializer --- .../tests/ObjectSerializerTest.php | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php new file mode 100644 index 00000000000..14bbc0de913 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/tests/ObjectSerializerTest.php @@ -0,0 +1,29 @@ +assertSame("sun.gif", $s->sanitizeFilename("sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("../sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("/var/tmp/sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("./sun.gif")); + + $this->assertSame("sun", $s->sanitizeFilename("sun")); + $this->assertSame("sun.gif", $s->sanitizeFilename("..\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("\var\tmp\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename("c:\var\tmp\sun.gif")); + $this->assertSame("sun.gif", $s->sanitizeFilename(".\sun.gif")); + } + +} + +?> + From 58c0e630123411a9208de3e2e1f8927295275f71 Mon Sep 17 00:00:00 2001 From: cbornet Date: Sat, 9 Jan 2016 15:21:02 +0000 Subject: [PATCH 43/47] add auth support to feign library Fix #1840 --- .../codegen/languages/JavaClientCodegen.java | 9 +- .../Java/libraries/feign/ApiClient.mustache | 132 ++++++++++++++++- .../libraries/feign/auth/ApiKeyAuth.mustache | 41 ++++++ .../feign/auth/HttpBasicAuth.mustache | 41 ++++++ .../Java/libraries/feign/auth/OAuth.mustache | 17 +++ .../java/io/swagger/client/ApiClient.java | 133 ++++++++++++++++-- .../io/swagger/client/FormAwareEncoder.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/api/StoreApi.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 2 +- .../io/swagger/client/auth/ApiKeyAuth.java | 41 ++++++ .../io/swagger/client/auth/HttpBasicAuth.java | 41 ++++++ .../java/io/swagger/client/auth/OAuth.java | 17 +++ .../io/swagger/client/auth/OAuthFlow.java | 5 + .../io/swagger/client/model/Category.java | 8 +- .../java/io/swagger/client/model/Order.java | 8 +- .../java/io/swagger/client/model/Pet.java | 8 +- .../java/io/swagger/client/model/Tag.java | 8 +- .../java/io/swagger/client/model/User.java | 8 +- 20 files changed, 487 insertions(+), 40 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java 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 0658e3ad6f3..8a09eb34ea9 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 @@ -223,12 +223,11 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { final String authFolder = (sourceFolder + '/' + invokerPackage + ".auth").replace(".", "/"); if ("feign".equals(getLibrary())) { supportingFiles.add(new SupportingFile("FormAwareEncoder.mustache", invokerFolder, "FormAwareEncoder.java")); - } else { - 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")); } + 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 (!("feign".equals(getLibrary()) || "retrofit".equals(getLibrary()) || "retrofit2".equals(getLibrary()))) { supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 3f2bfcebd5b..19d5fa8b72a 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -1,12 +1,18 @@ package {{invokerPackage}}; +import java.util.LinkedHashMap; +import java.util.Map; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; + import feign.Feign; +import feign.RequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; +import {{invokerPackage}}.auth.*; {{>generatedAnnotation}} public class ApiClient { @@ -14,20 +20,89 @@ public class ApiClient { private ObjectMapper objectMapper; private String basePath = "{{basePath}}"; + private Map apiAuthorizations; + private Feign.Builder feignBuilder; public ApiClient() { objectMapper = createObjectMapper(); + apiAuthorizations = new LinkedHashMap(); + feignBuilder = Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) + .logger(new Slf4jLogger()); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { {{#hasAuthMethods}} + RequestInterceptor auth; + {{#authMethods}}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}}{{scope}}{{#hasMore}}, {{/hasMore}}{{/scopes}}");{{/isOAuth}} + } else {{/authMethods}}{ + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth);{{/hasAuthMethods}}{{^hasAuthMethods}} + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names");{{/hasAuthMethods}} + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(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 ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); } public String getBasePath() { return basePath; } + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + public ApiClient setBasePath(String basePath) { this.basePath = basePath; return this; } + public Feign.Builder getFeignBuilder() { + return feignBuilder; + } + + public ApiClient setFeignBuilder(Feign.Builder feignBuilder) { + this.feignBuilder = feignBuilder; + return this; + } + private ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); @@ -45,13 +120,7 @@ public class ApiClient { * XYZResponse response = api.someMethod(...); */ public T buildClient(Class clientClass) { - return Feign.builder() - .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) - .decoder(new JacksonDecoder(objectMapper)) -// enable for basic auth: -// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) - .logger(new Slf4jLogger()) - .target(clientClass, basePath); + return feignBuilder.target(clientClass, basePath); } /** @@ -83,4 +152,53 @@ public class ApiClient { if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; return contentTypes[0]; } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + public void setApiKey(String apiKey) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return ; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure the username/password for basic auth or password OAuth + * @param username + * @param password + */ + public void setCredentials(String username, String password) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + } + throw new RuntimeException("No Basic authentication configured!"); + } + + public RequestInterceptor getAuthorization(String authName) { + return apiAuthorizations.get(authName); + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, RequestInterceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + feignBuilder.requestInterceptor(authorization); + } + } diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..371b24dbe55 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/ApiKeyAuth.mustache @@ -0,0 +1,41 @@ +package {{invokerPackage}}.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class ApiKeyAuth implements RequestInterceptor { + private final String location; + private final String paramName; + + private String apiKey; + + 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; + } + + @Override + public void apply(RequestTemplate template) { + if (location == "query") { + template.query(paramName, apiKey); + } else if (location == "header") { + template.header(paramName, apiKey); + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..2b1acb8ff74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/HttpBasicAuth.mustache @@ -0,0 +1,41 @@ +package {{invokerPackage}}.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.auth.BasicAuthRequestInterceptor; + +/** + * An interceptor that adds the request header needed to use HTTP basic authentication. + */ +public class HttpBasicAuth implements RequestInterceptor { + + 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 void apply(RequestTemplate template) { + RequestInterceptor requestInterceptor = new BasicAuthRequestInterceptor(username, password); + requestInterceptor.apply(template); + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache new file mode 100644 index 00000000000..d34818944c7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -0,0 +1,17 @@ +package {{invokerPackage}}.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class OAuth implements RequestInterceptor { + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + // TODO Not implemented yet + } + + @Override + public void apply(RequestTemplate template) { + // TODO Not implemented yet + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index a2959f6ef9f..b755509c532 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -1,33 +1,107 @@ package io.swagger.client; +import java.util.LinkedHashMap; +import java.util.Map; + import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; + import feign.Feign; +import feign.RequestInterceptor; import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; +import io.swagger.client.auth.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class ApiClient { public interface Api {} private ObjectMapper objectMapper; private String basePath = "http://petstore.swagger.io/v2"; + private Map apiAuthorizations; + private Feign.Builder feignBuilder; public ApiClient() { objectMapper = createObjectMapper(); + apiAuthorizations = new LinkedHashMap(); + feignBuilder = Feign.builder() + .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) + .decoder(new JacksonDecoder(objectMapper)) + .logger(new Slf4jLogger()); + } + + public ApiClient(String[] authNames) { + this(); + for(String authName : authNames) { + RequestInterceptor auth; + if (authName == "petstore_auth") { + auth = new OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets"); + } else if (authName == "api_key") { + auth = new ApiKeyAuth("header", "api_key"); + } else { + throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); + } + addAuthorization(authName, auth); + } + } + + /** + * Basic constructor for single auth name + * @param authName + */ + public ApiClient(String authName) { + this(new String[]{authName}); + } + + /** + * Helper constructor for single api key + * @param authName + * @param apiKey + */ + public ApiClient(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 ApiClient(String authName, String username, String password) { + this(authName); + this.setCredentials(username, password); } public String getBasePath() { return basePath; } + public Map getApiAuthorizations() { + return apiAuthorizations; + } + + public void setApiAuthorizations(Map apiAuthorizations) { + this.apiAuthorizations = apiAuthorizations; + } + public ApiClient setBasePath(String basePath) { this.basePath = basePath; return this; } + public Feign.Builder getFeignBuilder() { + return feignBuilder; + } + + public ApiClient setFeignBuilder(Feign.Builder feignBuilder) { + this.feignBuilder = feignBuilder; + return this; + } + private ObjectMapper createObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); @@ -45,13 +119,7 @@ public class ApiClient { * XYZResponse response = api.someMethod(...); */ public T buildClient(Class clientClass) { - return Feign.builder() - .encoder(new FormAwareEncoder(new JacksonEncoder(objectMapper))) - .decoder(new JacksonDecoder(objectMapper)) -// enable for basic auth: -// .requestInterceptor(new feign.auth.BasicAuthRequestInterceptor(username, password)) - .logger(new Slf4jLogger()) - .target(clientClass, basePath); + return feignBuilder.target(clientClass, basePath); } /** @@ -83,4 +151,53 @@ public class ApiClient { if (StringUtil.containsIgnoreCase(contentTypes, "application/json")) return "application/json"; return contentTypes[0]; } + + /** + * Helper method to configure the first api key found + * @param apiKey + */ + public void setApiKey(String apiKey) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof ApiKeyAuth) { + ApiKeyAuth keyAuth = (ApiKeyAuth) apiAuthorization; + keyAuth.setApiKey(apiKey); + return ; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to configure the username/password for basic auth or password OAuth + * @param username + * @param password + */ + public void setCredentials(String username, String password) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof HttpBasicAuth) { + HttpBasicAuth basicAuth = (HttpBasicAuth) apiAuthorization; + basicAuth.setCredentials(username, password); + return; + } + } + throw new RuntimeException("No Basic authentication configured!"); + } + + public RequestInterceptor getAuthorization(String authName) { + return apiAuthorizations.get(authName); + } + + /** + * Adds an authorization to be used by the client + * @param authName + * @param authorization + */ + public void addAuthorization(String authName, RequestInterceptor authorization) { + if (apiAuthorizations.containsKey(authName)) { + throw new RuntimeException("auth name \"" + authName + "\" already in api authorizations"); + } + apiAuthorizations.put(authName, authorization); + feignBuilder.requestInterceptor(authorization); + } + } diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index eab17f660ef..8e4924f3c53 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 9a27c73e12f..42c79bd4bef 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/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 = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index f53ac745037..57d901c1a42 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -8,7 +8,7 @@ import java.io.File; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public interface PetApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index 66644ad9469..77700db443e 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -8,7 +8,7 @@ import io.swagger.client.model.Order; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public interface StoreApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index 5400f5cace4..c2824ee3bf0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -8,7 +8,7 @@ import java.util.*; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public interface UserApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..067672104a9 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class ApiKeyAuth implements RequestInterceptor { + private final String location; + private final String paramName; + + private String apiKey; + + 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; + } + + @Override + public void apply(RequestTemplate template) { + if (location == "query") { + template.query(paramName, apiKey); + } else if (location == "header") { + template.header(paramName, apiKey); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..26a97039879 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,41 @@ +package io.swagger.client.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import feign.auth.BasicAuthRequestInterceptor; + +/** + * An interceptor that adds the request header needed to use HTTP basic authentication. + */ +public class HttpBasicAuth implements RequestInterceptor { + + 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 void apply(RequestTemplate template) { + RequestInterceptor requestInterceptor = new BasicAuthRequestInterceptor(username, password); + requestInterceptor.apply(template); + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..0c90e2f0410 --- /dev/null +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,17 @@ +package io.swagger.client.auth; + +import feign.RequestInterceptor; +import feign.RequestTemplate; + +public class OAuth implements RequestInterceptor { + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + // TODO Not implemented yet + } + + @Override + public void apply(RequestTemplate template) { + // TODO Not implemented yet + } + +} \ No newline at end of file diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..597ec99b48b --- /dev/null +++ b/samples/client/petstore/java/feign/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/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index 52bff46824c..7206f4ae8fb 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class Category { private Long id = null; @@ -53,8 +53,10 @@ public class Category { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + + return true && Objects.equals(id, category.id) && + Objects.equals(name, category.name) + ; } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 8c5d349d105..001ecb72359 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class Order { private Long id = null; @@ -131,12 +131,14 @@ public class Order { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && + + return true && Objects.equals(id, order.id) && Objects.equals(petId, order.petId) && Objects.equals(quantity, order.quantity) && Objects.equals(shipDate, order.shipDate) && Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + Objects.equals(complete, order.complete) + ; } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index df7d37173fb..e3aab4a41cf 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -13,7 +13,7 @@ import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class Pet { private Long id = null; @@ -133,12 +133,14 @@ public class Pet { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && + + return true && Objects.equals(id, pet.id) && Objects.equals(category, pet.category) && Objects.equals(name, pet.name) && Objects.equals(photoUrls, pet.photoUrls) && Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + Objects.equals(status, pet.status) + ; } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index 5f6b24d052c..197c5e600cc 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class Tag { private Long id = null; @@ -53,8 +53,10 @@ public class Tag { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + + return true && Objects.equals(id, tag.id) && + Objects.equals(name, tag.name) + ; } @Override diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index 7ebd78e6ea8..ae5f7e0f6a6 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-05T14:39:18.888+08:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") public class User { private Long id = null; @@ -138,14 +138,16 @@ public class User { return false; } User user = (User) o; - return Objects.equals(id, user.id) && + + return true && Objects.equals(id, user.id) && Objects.equals(username, user.username) && Objects.equals(firstName, user.firstName) && Objects.equals(lastName, user.lastName) && Objects.equals(email, user.email) && Objects.equals(password, user.password) && Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + Objects.equals(userStatus, user.userStatus) + ; } @Override From 5e4db995c9703c25900161cf0d729099dd5cad8f Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 11 Jan 2016 22:15:24 +0000 Subject: [PATCH 44/47] add oauth support to feign client --- .../Java/libraries/feign/ApiClient.mustache | 117 +++++++++- .../Java/libraries/feign/auth/OAuth.mustache | 202 +++++++++++++++++- .../Java/libraries/feign/pom.mustache | 7 + samples/client/petstore/java/feign/pom.xml | 7 + .../java/io/swagger/client/ApiClient.java | 119 ++++++++++- .../io/swagger/client/FormAwareEncoder.java | 2 +- .../java/io/swagger/client/StringUtil.java | 2 +- .../java/io/swagger/client/api/PetApi.java | 2 +- .../java/io/swagger/client/api/StoreApi.java | 2 +- .../java/io/swagger/client/api/UserApi.java | 2 +- .../java/io/swagger/client/auth/OAuth.java | 202 +++++++++++++++++- .../io/swagger/client/model/Category.java | 2 +- .../java/io/swagger/client/model/Order.java | 2 +- .../java/io/swagger/client/model/Pet.java | 2 +- .../java/io/swagger/client/model/Tag.java | 2 +- .../java/io/swagger/client/model/User.java | 2 +- 16 files changed, 635 insertions(+), 39 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache index 19d5fa8b72a..2d9fa23cf04 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -3,6 +3,9 @@ package {{invokerPackage}}; 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 com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -13,6 +16,7 @@ import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; import {{invokerPackage}}.auth.*; +import {{invokerPackage}}.auth.OAuth.AccessTokenListener; {{>generatedAnnotation}} public class ApiClient { @@ -77,10 +81,32 @@ public class ApiClient { this.setCredentials(username, password); } + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + public String getBasePath() { return basePath; } + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + public Map getApiAuthorizations() { return apiAuthorizations; } @@ -89,11 +115,6 @@ public class ApiClient { this.apiAuthorizations = apiAuthorizations; } - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - public Feign.Builder getFeignBuilder() { return feignBuilder; } @@ -180,8 +201,92 @@ public class ApiClient { basicAuth.setCredentials(username, password); return; } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + throw new RuntimeException("No Basic authentication or OAuth configured!"); + } + + /** + * 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(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) 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(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) 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 + * @param expiresIn : validity period in seconds + */ + public void setAccessToken(String accessToken, Long expiresIn) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken, expiresIn); + 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(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } } - throw new RuntimeException("No Basic authentication configured!"); } public RequestInterceptor getAuthorization(String authName) { diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache index d34818944c7..74ff86ebd1b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/auth/OAuth.mustache @@ -1,17 +1,203 @@ package {{invokerPackage}}.auth; +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.OAuthClient; +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.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +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 org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import feign.Client; +import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; +import feign.Response; +import feign.Util; +import {{invokerPackage}}.StringUtil; + public class OAuth implements RequestInterceptor { - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - // TODO Not implemented yet - } - - @Override - public void apply(RequestTemplate template) { - // TODO Not implemented yet + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); } -} \ No newline at end of file + private volatile String accessToken; + private Long expirationTimeMillis; + private OAuthClient oauthClient; + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + + public OAuth(Client client, TokenRequestBuilder requestBuilder) { + setOauthClient(client); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); + } + + 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 void apply(RequestTemplate template) { + // If the request already have an authorization (eg. Basic auth), do nothing + if (template.headers().containsKey("Authorization")) { + return; + } + // If first time, get the token + if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { + try { + updateAccessToken(); + } catch (OAuthSystemException e) { + e.printStackTrace(); + return; + } catch (OAuthProblemException e) { + e.printStackTrace(); + return; + } + } + if (getAccessToken() != null) { + template.header("Authorization", "Bearer " + getAccessToken()); + } + } + + public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { + if (getAccessToken() == null) { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken, Long expiresIn) { + this.accessToken = accessToken; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + } + + 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; + } + + public OAuthClient getOauthClient() { + return oauthClient; + } + + public void setOauthClient(OAuthClient oauthClient) { + this.oauthClient = oauthClient; + } + + public void setOauthClient(Client client) { + this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); + } + + public class OAuthFeignClient implements HttpClient { + + private Client client; + + public OAuthFeignClient() { + this.client = new Client.Default(null, null); + } + + public OAuthFeignClient(Client client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + RequestTemplate req = new RequestTemplate() + .append(request.getLocationUri()) + .method(requestMethod) + .body(request.getBody()); + + for (Entry entry : headers.entrySet()) { + req.header(entry.getKey(), entry.getValue()); + } + Response feignResponse; + String body = ""; + try { + feignResponse = client.execute(req.request(), new Options()); + body = Util.toString(feignResponse.body().asReader()); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + + String contentType = null; + Collection contentTypeHeader = feignResponse.headers().get("Content-Type"); + if(contentTypeHeader != null) { + contentType = StringUtil.join(contentTypeHeader.toArray(new String[0]), ";"); + } + + return OAuthClientResponseFactory.createCustomResponse( + body, + contentType, + feignResponse.status(), + responseClass + ); + } + + public void shutdown() { + // Nothing to do here + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache index e8069b82931..d0121e752dc 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/pom.mustache @@ -164,6 +164,12 @@ 2.2 + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + junit @@ -179,5 +185,6 @@ 2.5 4.12 1.0.0 + 1.0.0 diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index 5f7e9551862..d7ad6ee49b9 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -164,6 +164,12 @@ 2.2 + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + ${oltu-version} + + junit @@ -179,5 +185,6 @@ 2.5 4.12 1.0.0 + 1.0.0 diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java index b755509c532..2e032a9d1d1 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/ApiClient.java @@ -3,6 +3,9 @@ package io.swagger.client; 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 com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; @@ -13,8 +16,9 @@ import feign.jackson.JacksonDecoder; import feign.jackson.JacksonEncoder; import feign.slf4j.Slf4jLogger; import io.swagger.client.auth.*; +import io.swagger.client.auth.OAuth.AccessTokenListener; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class ApiClient { public interface Api {} @@ -76,10 +80,32 @@ public class ApiClient { this.setCredentials(username, password); } + /** + * Helper constructor for single password oauth2 + * @param authName + * @param clientId + * @param secret + * @param username + * @param password + */ + public ApiClient(String authName, String clientId, String secret, String username, String password) { + this(authName); + this.getTokenEndPoint() + .setClientId(clientId) + .setClientSecret(secret) + .setUsername(username) + .setPassword(password); + } + public String getBasePath() { return basePath; } + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + public Map getApiAuthorizations() { return apiAuthorizations; } @@ -88,11 +114,6 @@ public class ApiClient { this.apiAuthorizations = apiAuthorizations; } - public ApiClient setBasePath(String basePath) { - this.basePath = basePath; - return this; - } - public Feign.Builder getFeignBuilder() { return feignBuilder; } @@ -179,8 +200,92 @@ public class ApiClient { basicAuth.setCredentials(username, password); return; } + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder().setUsername(username).setPassword(password); + return; + } + } + throw new RuntimeException("No Basic authentication or OAuth configured!"); + } + + /** + * 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(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) 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(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) 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 + * @param expiresIn : validity period in seconds + */ + public void setAccessToken(String accessToken, Long expiresIn) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.setAccessToken(accessToken, expiresIn); + 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(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.getTokenRequestBuilder() + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI); + oauth.getAuthenticationRequestBuilder() + .setClientId(clientId) + .setRedirectURI(redirectURI); + return; + } + } + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener + */ + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + for(RequestInterceptor apiAuthorization : apiAuthorizations.values()) { + if (apiAuthorization instanceof OAuth) { + OAuth oauth = (OAuth) apiAuthorization; + oauth.registerAccessTokenListener(accessTokenListener); + return; + } } - throw new RuntimeException("No Basic authentication configured!"); } public RequestInterceptor getAuthorization(String authName) { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java index 8e4924f3c53..40f6af65150 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/FormAwareEncoder.java @@ -14,7 +14,7 @@ import feign.codec.EncodeException; import feign.codec.Encoder; import feign.RequestTemplate; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class FormAwareEncoder implements Encoder { public static final String UTF_8 = "utf-8"; private static final String LINE_FEED = "\r\n"; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java index 42c79bd4bef..a7299767d3f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/StringUtil.java +++ b/samples/client/petstore/java/feign/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 = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class StringUtil { /** * Check if the given array contains the given value (with case-insensitive comparison). diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java index 57d901c1a42..02a44b271f0 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/PetApi.java @@ -8,7 +8,7 @@ import java.io.File; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public interface PetApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java index 77700db443e..7a460f718a4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/StoreApi.java @@ -8,7 +8,7 @@ import io.swagger.client.model.Order; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public interface StoreApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java index c2824ee3bf0..cf7ccd97497 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/api/UserApi.java @@ -8,7 +8,7 @@ import java.util.*; import java.util.*; import feign.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public interface UserApi extends ApiClient.Api { diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java index 0c90e2f0410..5aafbf81a2f 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/auth/OAuth.java @@ -1,17 +1,203 @@ package io.swagger.client.auth; +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.OAuthClient; +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.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +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 org.apache.oltu.oauth2.common.token.BasicOAuthToken; + +import feign.Client; +import feign.Request.Options; import feign.RequestInterceptor; import feign.RequestTemplate; +import feign.Response; +import feign.Util; +import io.swagger.client.StringUtil; + public class OAuth implements RequestInterceptor { - public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { - // TODO Not implemented yet - } - - @Override - public void apply(RequestTemplate template) { - // TODO Not implemented yet + public interface AccessTokenListener { + public void notify(BasicOAuthToken token); } -} \ No newline at end of file + private volatile String accessToken; + private Long expirationTimeMillis; + private OAuthClient oauthClient; + private TokenRequestBuilder tokenRequestBuilder; + private AuthenticationRequestBuilder authenticationRequestBuilder; + private AccessTokenListener accessTokenListener; + + public OAuth(Client client, TokenRequestBuilder requestBuilder) { + setOauthClient(client); + this.tokenRequestBuilder = requestBuilder; + } + + public OAuth(Client client, OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(client, OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes)); + setFlow(flow); + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl); + } + + public OAuth(OAuthFlow flow, String authorizationUrl, String tokenUrl, String scopes) { + this(new Client.Default(null, null), flow, authorizationUrl, tokenUrl, scopes); + } + + 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 void apply(RequestTemplate template) { + // If the request already have an authorization (eg. Basic auth), do nothing + if (template.headers().containsKey("Authorization")) { + return; + } + // If first time, get the token + if (expirationTimeMillis == null || System.currentTimeMillis() >= expirationTimeMillis) { + try { + updateAccessToken(); + } catch (OAuthSystemException e) { + e.printStackTrace(); + return; + } catch (OAuthProblemException e) { + e.printStackTrace(); + return; + } + } + if (getAccessToken() != null) { + template.header("Authorization", "Bearer " + getAccessToken()); + } + } + + public synchronized void updateAccessToken() throws OAuthSystemException, OAuthProblemException { + if (getAccessToken() == null) { + OAuthJSONAccessTokenResponse accessTokenResponse = oauthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken(), accessTokenResponse.getExpiresIn()); + if (accessTokenListener != null) { + accessTokenListener.notify((BasicOAuthToken) accessTokenResponse.getOAuthToken()); + } + } + } + } + + public void registerAccessTokenListener(AccessTokenListener accessTokenListener) { + this.accessTokenListener = accessTokenListener; + } + + public synchronized String getAccessToken() { + return accessToken; + } + + public synchronized void setAccessToken(String accessToken, Long expiresIn) { + this.accessToken = accessToken; + this.expirationTimeMillis = System.currentTimeMillis() + expiresIn * 1000; + } + + 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; + } + + public OAuthClient getOauthClient() { + return oauthClient; + } + + public void setOauthClient(OAuthClient oauthClient) { + this.oauthClient = oauthClient; + } + + public void setOauthClient(Client client) { + this.oauthClient = new OAuthClient( new OAuthFeignClient(client)); + } + + public class OAuthFeignClient implements HttpClient { + + private Client client; + + public OAuthFeignClient() { + this.client = new Client.Default(null, null); + } + + public OAuthFeignClient(Client client) { + this.client = client; + } + + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + RequestTemplate req = new RequestTemplate() + .append(request.getLocationUri()) + .method(requestMethod) + .body(request.getBody()); + + for (Entry entry : headers.entrySet()) { + req.header(entry.getKey(), entry.getValue()); + } + Response feignResponse; + String body = ""; + try { + feignResponse = client.execute(req.request(), new Options()); + body = Util.toString(feignResponse.body().asReader()); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + + String contentType = null; + Collection contentTypeHeader = feignResponse.headers().get("Content-Type"); + if(contentTypeHeader != null) { + contentType = StringUtil.join(contentTypeHeader.toArray(new String[0]), ";"); + } + + return OAuthClientResponseFactory.createCustomResponse( + body, + contentType, + feignResponse.status(), + responseClass + ); + } + + public void shutdown() { + // Nothing to do here + } + + } +} diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java index 7206f4ae8fb..92e69c4d407 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Category.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Category { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java index 001ecb72359..3dc9168d926 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Order.java @@ -11,7 +11,7 @@ import java.util.Date; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Order { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java index e3aab4a41cf..908d654679a 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Pet.java @@ -13,7 +13,7 @@ import java.util.*; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Pet { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java index 197c5e600cc..337c84211a4 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/Tag.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class Tag { private Long id = null; diff --git a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java index ae5f7e0f6a6..b05d8a58a81 100644 --- a/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java +++ b/samples/client/petstore/java/feign/src/main/java/io/swagger/client/model/User.java @@ -10,7 +10,7 @@ import io.swagger.annotations.ApiModelProperty; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-09T15:18:34.525Z") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2016-01-11T21:48:33.457Z") public class User { private Long id = null; From 07947d8caddaac38bc7c6baf4bc892d5b8cb8866 Mon Sep 17 00:00:00 2001 From: cbornet Date: Mon, 11 Jan 2016 22:25:56 +0000 Subject: [PATCH 45/47] fix wrong query param key name --- .../src/main/resources/Java/libraries/feign/api.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache index 729320bd2e5..4dc48da3111 100644 --- a/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/libraries/feign/api.mustache @@ -19,7 +19,7 @@ public interface {{classname}} extends ApiClient.Api { {{#allParams}} * @param {{paramName}} {{description}} {{/allParams}} * @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} */ - @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{paramName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") + @RequestLine("{{httpMethod}} {{{path}}}{{#hasQueryParams}}?{{/hasQueryParams}}{{#queryParams}}{{baseName}}={{=<% %>=}}{<%paramName%>}<%={{ }}=%>{{#hasMore}}&{{/hasMore}}{{/queryParams}}") @Headers({ "Content-type: {{vendorExtensions.x-contentType}}", "Accepts: {{vendorExtensions.x-accepts}}",{{#headerParams}} From 637cae153c72b0f09dd4b279ab8b3e1b80001be3 Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 12 Jan 2016 18:12:54 +0800 Subject: [PATCH 46/47] Ruby: fix testing issue of deleting nonexistent pet --- samples/client/petstore/ruby/spec/spec_helper.rb | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 26da98f9c42..5eff37b134a 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -40,8 +40,13 @@ API_CLIENT = Petstore::ApiClient.new(Petstore::Configuration.new) # always delete and then re-create the pet object with 10002 def prepare_pet(pet_api) - # remove the pet - pet_api.delete_pet(10002) + begin + # remove the pet + pet_api.delete_pet(10002) + rescue Petstore::ApiError => e + # ignore ApiError 404 (Not Found) + raise e if e.code != 404 + end # recreate the pet category = Petstore::Category.new('id' => 20002, 'name' => 'category test') tag = Petstore::Tag.new('id' => 30002, 'name' => 'tag test') From 62e19c20e2eea70380bf2409cf17f82a998bea8e Mon Sep 17 00:00:00 2001 From: Michael Ira Krufky Date: Wed, 13 Jan 2016 08:15:20 -0500 Subject: [PATCH 47/47] README.md: Validating your OpenAPI Spec should point to #validating-your-openapi-spec --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index f5ba049c8d4..e267217ebd0 100644 --- a/README.md +++ b/README.md @@ -33,7 +33,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [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 OpenAPI Spec](#validating-your-swagger-spec) + - [Validating your OpenAPI Spec](#validating-your-openapi-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)