From 6e8497fdb74011496204855cf43601d8ab65bf38 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 1 May 2016 16:09:02 +0100 Subject: [PATCH 01/27] Add validation to api class --- .../src/main/resources/python/api.mustache | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 0967a2ec6b3..1a50f753409 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -94,6 +95,23 @@ class {{classname}}(object): if ('{{paramName}}' not in params) or (params['{{paramName}}'] is None): raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{operationId}}`") {{/required}} +{{/allParams}} + +{{#allParams}} +{{#hasValidation}} + {{#maximum}} + if {{#required}}{{paramName}}{{/required}}{{^required}}'{{paramName}}' in params and params['{{paramName}}']{{/required}} > {{maximum}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than `{{maximum}}`") + {{/maximum}} + {{#minimum}} + if {{#required}}{{paramName}}{{/required}}{{^required}}'{{paramName}}' in params and params['{{paramName}}']{{/required}} < {{minimum}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than `{{minimum}}`") + {{/minimum}} + {{#pattern}} + #if not re.match('{{pattern}}', {{#required}}{{paramName}}{{/required}}{{^required}}'{{paramName}}' in params and params['{{paramName}}']{{/required}}): + # raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") + {{/pattern}} +{{/hasValidation}} {{/allParams}} resource_path = '{{path}}'.replace('{format}', 'json') From cea6bce196893d804633d0904afbb0861314b10a Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 1 May 2016 16:15:29 +0100 Subject: [PATCH 02/27] Follow convention in place when accessing attributes --- .../swagger-codegen/src/main/resources/python/api.mustache | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 1a50f753409..e74365399e2 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -100,15 +100,15 @@ class {{classname}}(object): {{#allParams}} {{#hasValidation}} {{#maximum}} - if {{#required}}{{paramName}}{{/required}}{{^required}}'{{paramName}}' in params and params['{{paramName}}']{{/required}} > {{maximum}}: + if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than `{{maximum}}`") {{/maximum}} {{#minimum}} - if {{#required}}{{paramName}}{{/required}}{{^required}}'{{paramName}}' in params and params['{{paramName}}']{{/required}} < {{minimum}}: + if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than `{{minimum}}`") {{/minimum}} {{#pattern}} - #if not re.match('{{pattern}}', {{#required}}{{paramName}}{{/required}}{{^required}}'{{paramName}}' in params and params['{{paramName}}']{{/required}}): + #if not re.match('{{pattern}}', '{{paramName}}' in params and params['{{paramName}}']): # raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") {{/pattern}} {{/hasValidation}} From 97e69aabc3ea62e913228b76a514fb61d10183cc Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Sun, 1 May 2016 16:38:56 +0100 Subject: [PATCH 03/27] Add support for max/min string length --- .../src/main/resources/python/api.mustache | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index e74365399e2..5a38ee255ee 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -99,6 +99,14 @@ class {{classname}}(object): {{#allParams}} {{#hasValidation}} + {{#maxLength}} + if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxLength}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than `{{maxLength}}`") + {{/maxLength}} + {{#minLength}} + if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minLength}}: + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than `{{minLength}}`") + {{/minLength}} {{#maximum}} if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than `{{maximum}}`") From 3dbdc839811f27e85d35277d33cbc40a915a7ec4 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 2 May 2016 16:25:46 +0100 Subject: [PATCH 04/27] Add validation to model --- .../src/main/resources/python/model.mustache | 27 ++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index bd33a997c3e..340c73687f5 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -79,7 +79,32 @@ class {{classname}}(object): "Invalid value for `{{name}}`, must be one of {0}" .format(allowed_values) ) - {{/isEnum}}self._{{name}} = {{name}} + {{/isEnum}} + {{^isEnum}} + + {{#hasValidation}} + {{#maxLength}} + if len({{name}}) > {{maxLength}}: + raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") + {{/maxLength}} + {{#minLength}} + if len({{name}}) < {{minLength}}: + raise ValueError("Invalid value for `{{name}}`, length must be greater than `{{minLength}}`") + {{/minLength}} + {{#maximum}} + if {{name}} > {{maximum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value less than `{{maximum}}`") + {{/maximum}} + {{#minimum}} + if {{name}} < {{minimum}}: + raise ValueError("Invalid value for `{{name}}`, must be a value greater than `{{minimum}}`") + {{/minimum}} + {{#pattern}} + #Check pattern + {{/pattern}} + {{/hasValidation}} + {{/isEnum}} + self._{{name}} = {{name}} {{/vars}} def to_dict(self): From 4a440f4ee4cdf19f7cf427625359bde363affb2e Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 2 May 2016 16:37:32 +0100 Subject: [PATCH 05/27] Fix excpetion message to include --- .../src/main/resources/python/api.mustache | 8 ++++---- .../src/main/resources/python/model.mustache | 14 +++++++++----- 2 files changed, 13 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 5a38ee255ee..7902754e5fb 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -101,19 +101,19 @@ class {{classname}}(object): {{#hasValidation}} {{#maxLength}} if '{{paramName}}' in params and len(params['{{paramName}}']) > {{maxLength}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than `{{maxLength}}`") + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be less than or equal to `{{maxLength}}`") {{/maxLength}} {{#minLength}} if '{{paramName}}' in params and len(params['{{paramName}}']) < {{minLength}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than `{{minLength}}`") + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} if '{{paramName}}' in params and params['{{paramName}}'] > {{maximum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than `{{maximum}}`") + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value less than or equal to `{{maximum}}`") {{/maximum}} {{#minimum}} if '{{paramName}}' in params and params['{{paramName}}'] < {{minimum}}: - raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than `{{minimum}}`") + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} #if not re.match('{{pattern}}', '{{paramName}}' in params and params['{{paramName}}']): diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 340c73687f5..78fe2ff2acd 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -21,7 +21,8 @@ Copyright 2016 SmartBear Software {{#models}} {{#model}} from pprint import pformat -from six import iteritems +from six import +import re class {{classname}}(object): @@ -83,24 +84,27 @@ class {{classname}}(object): {{^isEnum}} {{#hasValidation}} + if not {{name}}: + raise ValueError("Invalid value for `{{name}}`, must not be `None`") {{#maxLength}} if len({{name}}) > {{maxLength}}: raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") {{/maxLength}} {{#minLength}} if len({{name}}) < {{minLength}}: - raise ValueError("Invalid value for `{{name}}`, length must be greater than `{{minLength}}`") + raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") {{/minLength}} {{#maximum}} if {{name}} > {{maximum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value less than `{{maximum}}`") + raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{maximum}}`") {{/maximum}} {{#minimum}} if {{name}} < {{minimum}}: - raise ValueError("Invalid value for `{{name}}`, must be a value greater than `{{minimum}}`") + raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - #Check pattern + #if not re.match('/[a-z]/i', {{name}}): + # raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") {{/pattern}} {{/hasValidation}} {{/isEnum}} From 1fef0ef691e5c8d3075711d0c333670e23590a64 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 2 May 2016 16:39:25 +0100 Subject: [PATCH 06/27] Fix import statement --- .../swagger-codegen/src/main/resources/python/model.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 78fe2ff2acd..3fce2b47697 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -21,7 +21,7 @@ Copyright 2016 SmartBear Software {{#models}} {{#model}} from pprint import pformat -from six import +from six import iteritems import re From e868690c035714f21449fdcd8e7bfa3d97de6b41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=BB=84=E7=9C=9F=E4=BF=8A?= Date: Wed, 4 May 2016 19:51:53 +0800 Subject: [PATCH 07/27] add pom.xml based on build.gradle for android api client( using the volley HTTP library ); --- .../client/petstore/android/volley/pom.xml | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 samples/client/petstore/android/volley/pom.xml diff --git a/samples/client/petstore/android/volley/pom.xml b/samples/client/petstore/android/volley/pom.xml new file mode 100644 index 00000000000..2a3b8ef2f96 --- /dev/null +++ b/samples/client/petstore/android/volley/pom.xml @@ -0,0 +1,41 @@ + + + 4.0.0 + io.swagger + volley + 1.0.0 + + + io.swagger + swagger-annotations + 1.5.0 + compile + + + org.apache.httpcomponents + httpcore + 4.4.4 + compile + + + org.apache.httpcomponents + httpmime + 4.5.2 + compile + + + com.google.code.gson + gson + 2.3.1 + compile + + + com.mcxiaoke.volley + library + 1.0.19 + aar + compile + + + From 39cbee5ca26895d78592ae5d6b3f82f6e77dff52 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 5 May 2016 15:23:56 +0800 Subject: [PATCH 08/27] rename springboot sh, chmod a+x, add ModelApiResponse --- ...rver2.sh => springboot-petstore-server.sh} | 0 .../java/io/swagger/api/ApiException.java | 2 +- .../java/io/swagger/api/ApiOriginFilter.java | 2 +- .../io/swagger/api/ApiResponseMessage.java | 2 +- .../io/swagger/api/NotFoundException.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 49 +++++------ .../main/java/io/swagger/api/StoreApi.java | 14 +-- .../src/main/java/io/swagger/api/UserApi.java | 30 +++---- .../SwaggerDocumentationConfig.java | 6 +- .../main/java/io/swagger/model/Category.java | 2 +- .../io/swagger/model/ModelApiResponse.java | 85 +++++++++++++++++++ .../src/main/java/io/swagger/model/Order.java | 4 +- .../src/main/java/io/swagger/model/Pet.java | 2 +- .../src/main/java/io/swagger/model/Tag.java | 2 +- .../src/main/java/io/swagger/model/User.java | 2 +- 15 files changed, 143 insertions(+), 61 deletions(-) rename bin/{springboot-petstore-server2.sh => springboot-petstore-server.sh} (100%) mode change 100644 => 100755 create mode 100644 samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java diff --git a/bin/springboot-petstore-server2.sh b/bin/springboot-petstore-server.sh old mode 100644 new mode 100755 similarity index 100% rename from bin/springboot-petstore-server2.sh rename to bin/springboot-petstore-server.sh diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java index c7499fe4ff2..adcd36c99e8 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class ApiException extends Exception{ private int code; public ApiException (int code, String msg) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java index 0df82935399..fbd1f7cf197 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiOriginFilter.java @@ -5,7 +5,7 @@ import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class ApiOriginFilter implements javax.servlet.Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java index c7d9f8fdb58..95287af8af9 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/ApiResponseMessage.java @@ -3,7 +3,7 @@ package io.swagger.api; import javax.xml.bind.annotation.XmlTransient; @javax.xml.bind.annotation.XmlRootElement -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class ApiResponseMessage { public static final int ERROR = 1; public static final int WARNING = 2; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java index 3a513d8713e..4c97537ad07 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/NotFoundException.java @@ -1,6 +1,6 @@ package io.swagger.api; -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class NotFoundException extends ApiException { private int code; public NotFoundException (int code, String msg) { diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java index 127a788cf73..a0c84087eaf 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/PetApi.java @@ -4,6 +4,7 @@ import io.swagger.model.*; import io.swagger.model.Pet; import java.io.File; +import io.swagger.model.ModelApiResponse; import io.swagger.annotations.*; @@ -26,7 +27,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/pet", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/pet", description = "the pet API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class PetApi { @ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class, authorizations = { @@ -38,12 +39,12 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) public ResponseEntity addPet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -60,7 +61,7 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) public ResponseEntity deletePet( @@ -77,7 +78,7 @@ public class PetApi { } - @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma seperated strings", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by status", notes = "Multiple status values can be provided with comma separated strings", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -87,10 +88,10 @@ public class PetApi { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid status value", response = Pet.class) }) @RequestMapping(value = "/findByStatus", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + public ResponseEntity> findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", required = true) @RequestParam(value = "status", required = true) List status ) @@ -100,7 +101,7 @@ public class PetApi { } - @ApiOperation(value = "Finds Pets by tags", notes = "Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { + @ApiOperation(value = "Finds Pets by tags", notes = "Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.", response = Pet.class, responseContainer = "List", authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") @@ -110,10 +111,10 @@ public class PetApi { @ApiResponse(code = 200, message = "successful operation", response = Pet.class), @ApiResponse(code = 400, message = "Invalid tag value", response = Pet.class) }) @RequestMapping(value = "/findByTags", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + public ResponseEntity> findPetsByTags(@ApiParam(value = "Tags to filter by", required = true) @RequestParam(value = "tags", required = true) List tags ) @@ -123,11 +124,7 @@ public class PetApi { } - @ApiOperation(value = "Find pet by ID", notes = "Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions", response = Pet.class, authorizations = { - @Authorization(value = "petstore_auth", scopes = { - @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), - @AuthorizationScope(scope = "read:pets", description = "read your pets") - }), + @ApiOperation(value = "Find pet by ID", notes = "Returns a single pet", response = Pet.class, authorizations = { @Authorization(value = "api_key") }) @ApiResponses(value = { @@ -135,11 +132,11 @@ public class PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Pet.class), @ApiResponse(code = 404, message = "Pet not found", response = Pet.class) }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) public ResponseEntity getPetById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId +@ApiParam(value = "ID of pet to return",required=true ) @PathVariable("petId") Long petId ) throws NotFoundException { @@ -159,12 +156,12 @@ public class PetApi { @ApiResponse(code = 404, message = "Pet not found", response = Void.class), @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) public ResponseEntity updatePet( -@ApiParam(value = "Pet object that needs to be added to the store" ) @RequestBody Pet body +@ApiParam(value = "Pet object that needs to be added to the store" ,required=true ) @RequestBody Pet body ) throws NotFoundException { // do some magic! @@ -181,11 +178,11 @@ public class PetApi { @ApiResponses(value = { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) @RequestMapping(value = "/{petId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) public ResponseEntity updatePetWithForm( -@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") Long petId , @@ -204,19 +201,19 @@ public class PetApi { } - @ApiOperation(value = "uploads an image", notes = "", response = Void.class, authorizations = { + @ApiOperation(value = "uploads an image", notes = "", response = ModelApiResponse.class, authorizations = { @Authorization(value = "petstore_auth", scopes = { @AuthorizationScope(scope = "write:pets", description = "modify pets in your account"), @AuthorizationScope(scope = "read:pets", description = "read your pets") }) }) @ApiResponses(value = { - @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) + @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) @RequestMapping(value = "/{petId}/uploadImage", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - public ResponseEntity uploadFile( + public ResponseEntity uploadFile( @ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId , @@ -231,7 +228,7 @@ public class PetApi { ) throws NotFoundException { // do some magic! - return new ResponseEntity(HttpStatus.OK); + return new ResponseEntity(HttpStatus.OK); } } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java index 9044f63f97b..ccbf7ef4211 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/StoreApi.java @@ -26,7 +26,7 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/store", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/store", description = "the store API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class StoreApi { @ApiOperation(value = "Delete purchase order by ID", notes = "For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors", response = Void.class) @@ -34,7 +34,7 @@ public class StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Void.class), @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) public ResponseEntity deleteOrder( @@ -53,7 +53,7 @@ public class StoreApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Integer.class) }) @RequestMapping(value = "/inventory", - produces = { "application/json", "application/xml" }, + produces = { "application/json" }, method = RequestMethod.GET) public ResponseEntity> getInventory() @@ -69,11 +69,11 @@ public class StoreApi { @ApiResponse(code = 400, message = "Invalid ID supplied", response = Order.class), @ApiResponse(code = 404, message = "Order not found", response = Order.class) }) @RequestMapping(value = "/order/{orderId}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) public ResponseEntity getOrderById( -@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") Long orderId ) throws NotFoundException { @@ -87,12 +87,12 @@ public class StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Order.class) }) @RequestMapping(value = "/order", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) public ResponseEntity placeOrder( -@ApiParam(value = "order placed for purchasing the pet" ) @RequestBody Order body +@ApiParam(value = "order placed for purchasing the pet" ,required=true ) @RequestBody Order body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java index c0409a9237b..03b65828d34 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/api/UserApi.java @@ -26,19 +26,19 @@ import static org.springframework.http.MediaType.*; @Controller @RequestMapping(value = "/user", produces = {APPLICATION_JSON_VALUE}) @Api(value = "/user", description = "the user API") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class UserApi { @ApiOperation(value = "Create user", notes = "This can only be done by the logged in user.", response = Void.class) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) public ResponseEntity createUser( -@ApiParam(value = "Created user object" ) @RequestBody User body +@ApiParam(value = "Created user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! @@ -50,12 +50,12 @@ public class UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/createWithArray", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) public ResponseEntity createUsersWithArrayInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -67,12 +67,12 @@ public class UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/createWithList", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.POST) public ResponseEntity createUsersWithListInput( -@ApiParam(value = "List of user object" ) @RequestBody List body +@ApiParam(value = "List of user object" ,required=true ) @RequestBody List body ) throws NotFoundException { // do some magic! @@ -85,7 +85,7 @@ public class UserApi { @ApiResponse(code = 400, message = "Invalid username supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.DELETE) public ResponseEntity deleteUser( @@ -104,7 +104,7 @@ public class UserApi { @ApiResponse(code = 400, message = "Invalid username supplied", response = User.class), @ApiResponse(code = 404, message = "User not found", response = User.class) }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) public ResponseEntity getUserByName( @@ -122,14 +122,14 @@ public class UserApi { @ApiResponse(code = 200, message = "successful operation", response = String.class), @ApiResponse(code = 400, message = "Invalid username/password supplied", response = String.class) }) @RequestMapping(value = "/login", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) - public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + public ResponseEntity loginUser(@ApiParam(value = "The user name for login", required = true) @RequestParam(value = "username", required = true) String username , - @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + @ApiParam(value = "The password for login in clear text", required = true) @RequestParam(value = "password", required = true) String password ) @@ -143,7 +143,7 @@ public class UserApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) @RequestMapping(value = "/logout", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.GET) public ResponseEntity logoutUser() @@ -158,7 +158,7 @@ public class UserApi { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) @RequestMapping(value = "/{username}", - produces = { "application/json", "application/xml" }, + produces = { "application/xml", "application/json" }, method = RequestMethod.PUT) public ResponseEntity updateUser( @@ -167,7 +167,7 @@ public class UserApi { , -@ApiParam(value = "Updated user object" ) @RequestBody User body +@ApiParam(value = "Updated user object" ,required=true ) @RequestBody User body ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java index 54c04e222b3..069ea9b8d0c 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/configuration/SwaggerDocumentationConfig.java @@ -13,18 +13,18 @@ import springfox.documentation.spring.web.plugins.Docket; @Configuration -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class SwaggerDocumentationConfig { ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Swagger Petstore") - .description("This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters") + .description("This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters.") .license("Apache 2.0") .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html") .termsOfServiceUrl("") .version("1.0.0") - .contact(new Contact("","", "apiteam@wordnik.com")) + .contact(new Contact("","", "apiteam@swagger.io")) .build(); } diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java index b672ce0839b..3e5a05eccbb 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Category.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class Category { private Long id = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java new file mode 100644 index 00000000000..598976f0cee --- /dev/null +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/ModelApiResponse.java @@ -0,0 +1,85 @@ +package io.swagger.model; + +import com.fasterxml.jackson.annotation.JsonProperty; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; + +import io.swagger.annotations.*; +import com.fasterxml.jackson.annotation.JsonProperty; + +import java.util.Objects; + + +@ApiModel(description = "") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") +public class ModelApiResponse { + + private Integer code = null; + private String type = null; + private String message = null; + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("code") + public Integer getCode() { + return code; + } + public void setCode(Integer code) { + this.code = code; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("type") + public String getType() { + return type; + } + public void setType(String type) { + this.type = type; + } + + /** + **/ + @ApiModelProperty(value = "") + @JsonProperty("message") + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(code).append("\n"); + sb.append(" type: ").append(type).append("\n"); + sb.append(" message: ").append(message).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java index 38d97525c8b..f9af13e9d51 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Order.java @@ -13,7 +13,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class Order { private Long id = null; @@ -25,7 +25,7 @@ public class Order { }; private StatusEnum status = null; - private Boolean complete = null; + private Boolean complete = false; /** **/ diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java index caa76cd78d8..d27376b35bb 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Pet.java @@ -16,7 +16,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class Pet { private Long id = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java index 8aa0ca904b7..cbb158c47d4 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/Tag.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class Tag { private Long id = null; diff --git a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java index 21432ba3355..13a62d53a71 100644 --- a/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java +++ b/samples/server/petstore/springboot/src/main/java/io/swagger/model/User.java @@ -11,7 +11,7 @@ import java.util.Objects; @ApiModel(description = "") -@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-04T16:34:30.253+02:00") +@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringBootServerCodegen", date = "2016-05-05T15:10:34.669+08:00") public class User { private Long id = null; From 3a80a4ff1e3a9d1eebad7fb18db10c6c3ce647ee Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 6 May 2016 16:36:45 +0800 Subject: [PATCH 09/27] fix double byte characters in description, upgrade to lang3 --- modules/swagger-codegen/pom.xml | 4 +- .../io/swagger/codegen/DefaultCodegen.java | 6 +- .../languages/AbstractCSharpCodegen.java | 2 +- .../AbstractTypeScriptClientCodegen.java | 2 +- .../languages/AkkaScalaClientCodegen.java | 2 +- .../languages/AndroidClientCodegen.java | 2 +- .../languages/AspNet5ServerCodegen.java | 2 +- .../languages/CSharpClientCodegen.java | 4 +- .../languages/ClojureClientCodegen.java | 2 +- .../codegen/languages/FlashClientCodegen.java | 2 +- .../codegen/languages/GoClientCodegen.java | 4 +- .../codegen/languages/JMeterCodegen.java | 2 +- .../codegen/languages/JavaClientCodegen.java | 6 +- .../languages/JavaResteasyServerCodegen.java | 2 +- .../languages/JavascriptClientCodegen.java | 2 +- ...JavascriptClosureAngularClientCodegen.java | 2 +- .../codegen/languages/LumenServerCodegen.java | 2 +- .../codegen/languages/ObjcClientCodegen.java | 2 +- .../codegen/languages/PerlClientCodegen.java | 2 +- .../languages/PythonClientCodegen.java | 2 +- .../codegen/languages/RubyClientCodegen.java | 2 +- .../codegen/languages/ScalaClientCodegen.java | 2 +- .../languages/SinatraServerCodegen.java | 2 +- .../codegen/languages/StaticDocCodegen.java | 2 +- .../languages/StaticHtmlGenerator.java | 2 +- .../codegen/languages/SwaggerGenerator.java | 2 +- .../languages/SwaggerYamlGenerator.java | 2 +- .../codegen/languages/SwiftCodegen.java | 6 +- .../codegen/languages/TizenClientCodegen.java | 2 +- .../statichtml/StaticHtmlTagsTest.java | 2 +- ...ith-fake-endpoints-models-for-testing.yaml | 12 +- pom.xml | 2 +- .../petstore/php/SwaggerClient-php/README.md | 6 +- .../php/SwaggerClient-php/docs/EnumClass.md | 9 + .../php/SwaggerClient-php/docs/EnumTest.md | 12 + .../php/SwaggerClient-php/docs/FakeApi.md | 12 + .../php/SwaggerClient-php/lib/Api/FakeApi.php | 8 + .../SwaggerClient-php/lib/Model/EnumClass.php | 182 ++++++++++ .../SwaggerClient-php/lib/Model/EnumTest.php | 318 ++++++++++++++++++ .../lib/Tests/EnumClassTest.php | 70 ++++ .../lib/Tests/EnumTestTest.php | 70 ++++ .../lib/Tests/FakeApiTest.php | 4 + samples/client/petstore/ruby/README.md | 9 +- .../client/petstore/ruby/docs/AnimalFarm.md | 7 + .../client/petstore/ruby/docs/EnumClass.md | 7 + samples/client/petstore/ruby/docs/EnumTest.md | 10 + samples/client/petstore/ruby/docs/FakeApi.md | 8 +- samples/client/petstore/ruby/lib/petstore.rb | 3 + .../ruby/lib/petstore/api/fake_api.rb | 8 +- .../ruby/lib/petstore/models/animal_farm.rb | 179 ++++++++++ .../ruby/lib/petstore/models/enum_class.rb | 184 ++++++++++ .../ruby/lib/petstore/models/enum_test.rb | 248 ++++++++++++++ 52 files changed, 1392 insertions(+), 54 deletions(-) create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumClassTest.php create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumTestTest.php create mode 100644 samples/client/petstore/ruby/docs/AnimalFarm.md create mode 100644 samples/client/petstore/ruby/docs/EnumClass.md create mode 100644 samples/client/petstore/ruby/docs/EnumTest.md create mode 100644 samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/models/enum_class.rb create mode 100644 samples/client/petstore/ruby/lib/petstore/models/enum_test.rb diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index afaecfc3512..9ea75ad3c88 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -252,8 +252,8 @@ ${slf4j-version} - commons-lang - commons-lang + org.apache.commons + commons-lang3 ${commons-lang-version} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index db000e9c63e..f350339127b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -9,8 +9,8 @@ import io.swagger.models.parameters.*; import io.swagger.models.properties.*; import io.swagger.models.properties.PropertyBuilder.PropertyId; import io.swagger.util.Json; -import org.apache.commons.lang.StringEscapeUtils; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringEscapeUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -325,7 +325,7 @@ public class DefaultCodegen { @SuppressWarnings("static-method") public String escapeText(String input) { if (input != null) { - return StringEscapeUtils.escapeJava(input).replace("\\/", "/"); + return StringEscapeUtils.unescapeJava(StringEscapeUtils.escapeJava(input).replace("\\/", "/")).replaceAll("[\\t\\n\\r]"," "); } return input; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java index e9d6457f6f0..0058468efc8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractCSharpCodegen.java @@ -2,7 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java index 55c1df5438c..9e30ae657c8 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -6,7 +6,7 @@ import io.swagger.models.properties.*; import java.util.*; import java.io.File; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public abstract class AbstractTypeScriptClientCodegen extends DefaultCodegen implements CodegenConfig { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java index 523fa6ae8c6..43faca235d0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -26,7 +26,7 @@ import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 c0bead5c695..bed84f855bf 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 @@ -14,7 +14,7 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java index cf8915974e6..90bea4a8a6b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/AspNet5ServerCodegen.java @@ -2,7 +2,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.*; import io.swagger.models.properties.*; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 1212795e1bb..5780466ddbc 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,8 +25,8 @@ import java.util.Map; import java.util.ArrayList; import java.util.Iterator; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.text.WordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java index 2c60a30754b..73ef83bc9cc 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ClojureClientCodegen.java @@ -11,7 +11,7 @@ import io.swagger.models.Contact; import io.swagger.models.Info; import io.swagger.models.License; import io.swagger.models.Swagger; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.Map; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java index b5699a93a34..a9eb1a97de7 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FlashClientCodegen.java @@ -17,7 +17,7 @@ import io.swagger.models.properties.LongProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.Arrays; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java index fe25436c901..4e34424eab7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/GoClientCodegen.java @@ -9,7 +9,7 @@ import io.swagger.models.parameters.Parameter; import java.io.File; import java.util.*; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -450,4 +450,4 @@ public class GoClientCodegen extends DefaultCodegen implements CodegenConfig { public void setPackageVersion(String packageVersion) { this.packageVersion = packageVersion; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java index 903cb7ba76e..2d08c9741e9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JMeterCodegen.java @@ -183,4 +183,4 @@ public class JMeterCodegen extends DefaultCodegen implements CodegenConfig { type = swaggerType; return toModelName(type); } -} \ No newline at end of file +} 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 e607670313c..bc839f07d18 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 @@ -9,9 +9,9 @@ import io.swagger.models.Swagger; import io.swagger.models.parameters.FormParameter; import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.*; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.StringUtils; +//import org.apache.commons.lang3.WordUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java index 5f715a43621..b919430035d 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavaResteasyServerCodegen.java @@ -4,7 +4,7 @@ import io.swagger.codegen.*; import io.swagger.models.Operation; import io.swagger.models.Path; import io.swagger.models.Swagger; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import java.io.File; import java.util.*; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java index feec76d8de2..41f55a50c2b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClientCodegen.java @@ -33,7 +33,7 @@ import io.swagger.models.properties.Property; import io.swagger.models.properties.RefProperty; import io.swagger.models.properties.StringProperty; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java index 2a2dfd86c9d..55c3fab96b0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/JavascriptClosureAngularClientCodegen.java @@ -8,7 +8,7 @@ import java.util.TreeSet; import java.util.*; import java.io.File; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class JavascriptClosureAngularClientCodegen extends DefaultCodegen implements CodegenConfig { public JavascriptClosureAngularClientCodegen() { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java index 55e72f79384..fbd98c034df 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LumenServerCodegen.java @@ -232,4 +232,4 @@ public class LumenServerCodegen extends DefaultCodegen implements CodegenConfig type = swaggerType; return toModelName(type); } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 21e319f6ec9..44ab79ddcc4 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -19,7 +19,7 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String CLASS_PREFIX = "classPrefix"; 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 e4744bf037c..e17084a3bc5 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 @@ -27,7 +27,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.regex.Matcher; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String MODULE_NAME = "moduleName"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 1bc95cfdd67..1c057834ecf 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -13,7 +13,7 @@ import java.io.File; import java.util.Arrays; import java.util.HashSet; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig { protected String packageName; 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 f9c0990c182..aeb8e524e9d 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,7 +19,7 @@ import java.util.HashSet; import java.util.Iterator; import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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 a13c7a54e70..992693810da 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 @@ -26,7 +26,7 @@ import java.util.Iterator; import java.util.List; import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class ScalaClientCodegen extends DefaultCodegen implements CodegenConfig { protected String invokerPackage = "io.swagger.client"; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java index bb7706b13fe..fb3ceab7d78 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SinatraServerCodegen.java @@ -17,7 +17,7 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Map; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java index 3ff35f170fd..c64fcfb04ef 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticDocCodegen.java @@ -85,4 +85,4 @@ public class StaticDocCodegen extends DefaultCodegen implements CodegenConfig { public String modelFileFolder() { return outputFolder + File.separator + sourceFolder + File.separator + "models"; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java index 65ec8529930..0db05d5bc0a 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/StaticHtmlGenerator.java @@ -101,4 +101,4 @@ public class StaticHtmlGenerator extends DefaultCodegen implements CodegenConfig } return objs; } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java index b34e6bba5ab..6282f72d8b7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerGenerator.java @@ -52,4 +52,4 @@ public class SwaggerGenerator extends DefaultCodegen implements CodegenConfig { LOGGER.error(e.getMessage(), e); } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java index 5442000280f..48f0197068b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwaggerYamlGenerator.java @@ -51,4 +51,4 @@ public class SwaggerYamlGenerator extends DefaultCodegen implements CodegenConfi LOGGER.error(e.getMessage(), e); } } -} \ No newline at end of file +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java index 7b6bf8fbdc3..ba846857cb9 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/SwiftCodegen.java @@ -13,9 +13,9 @@ import io.swagger.models.parameters.Parameter; import io.swagger.models.properties.ArrayProperty; import io.swagger.models.properties.MapProperty; import io.swagger.models.properties.Property; -import org.apache.commons.lang.ArrayUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.WordUtils; +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.text.WordUtils; import javax.annotation.Nullable; import java.util.*; diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java index c3f6d7ab99a..ec58781ab2b 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TizenClientCodegen.java @@ -25,7 +25,7 @@ import java.util.HashSet; import java.util.Map; import java.util.Set; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig { protected static String PREFIX = "Sami"; diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java index ad84f8ca0c7..0ba3d9e2fee 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/statichtml/StaticHtmlTagsTest.java @@ -12,7 +12,7 @@ import java.util.Set; import javax.annotation.Nullable; -import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang3.StringUtils; import org.junit.rules.TemporaryFolder; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml index 068fb8054d8..92e9cb251b1 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -564,8 +564,16 @@ paths: post: tags: - fake - summary: Fake endpoint for testing various parameters - description: Fake endpoint for testing various parameters + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 operationId: testEndpointParameters produces: - application/xml diff --git a/pom.xml b/pom.xml index 9ac1890ea91..1b5c3d7580f 100644 --- a/pom.xml +++ b/pom.xml @@ -567,7 +567,7 @@ 1.2 4.8.1 1.0.0 - 2.4 + 3.4 1.7.12 3.2.1 1.12 diff --git a/samples/client/petstore/php/SwaggerClient-php/README.md b/samples/client/petstore/php/SwaggerClient-php/README.md index a5cba5dcbb7..ab81085c3ad 100644 --- a/samples/client/petstore/php/SwaggerClient-php/README.md +++ b/samples/client/petstore/php/SwaggerClient-php/README.md @@ -5,7 +5,7 @@ This PHP package is automatically generated by the [Swagger Codegen](https://git - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-06T10:33:16.765+08:00 +- Build date: 2016-05-06T16:24:00.420+08:00 - Build package: class io.swagger.codegen.languages.PhpClientCodegen ## Requirements @@ -88,6 +88,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트 + *PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store *PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md new file mode 100644 index 00000000000..2ef9e6adaac --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/docs/EnumTest.md @@ -0,0 +1,12 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **string** | | [optional] +**enum_integer** | **int** | | [optional] +**enum_number** | **double** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md b/samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md index 93c24ef7eeb..4acf36fa696 100644 --- a/samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md +++ b/samples/client/petstore/php/SwaggerClient-php/docs/FakeApi.md @@ -5,14 +5,26 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- [**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트 + # **testEndpointParameters** > testEndpointParameters($number, $double, $string, $byte, $integer, $int32, $int64, $float, $binary, $date, $date_time, $password) Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트 + Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트 + ### Example ```php diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php index 376572544de..32acfa9e203 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Api/FakeApi.php @@ -94,6 +94,10 @@ class FakeApi * testEndpointParameters * * Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트 + * * @param float $number None (required) * @param double $double None (required) @@ -121,6 +125,10 @@ class FakeApi * testEndpointParametersWithHttpInfo * * Fake endpoint for testing various parameters +假端點 +偽のエンドポイント +가짜 엔드 포인트 + * * @param float $number None (required) * @param double $double None (required) diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php new file mode 100644 index 00000000000..66f2ba08229 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumClass.php @@ -0,0 +1,182 @@ +container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php new file mode 100644 index 00000000000..1f3213e7516 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Model/EnumTest.php @@ -0,0 +1,318 @@ + 'string', + 'enum_integer' => 'int', + 'enum_number' => 'double' + ); + + static function swaggerTypes() { + return self::$swaggerTypes; + } + + /** + * Array of attributes where the key is the local name, and the value is the original name + * @var string[] + */ + static $attributeMap = array( + 'enum_string' => 'enum_string', + 'enum_integer' => 'enum_integer', + 'enum_number' => 'enum_number' + ); + + static function attributeMap() { + return self::$attributeMap; + } + + /** + * Array of attributes to setter functions (for deserialization of responses) + * @var string[] + */ + static $setters = array( + 'enum_string' => 'setEnumString', + 'enum_integer' => 'setEnumInteger', + 'enum_number' => 'setEnumNumber' + ); + + static function setters() { + return self::$setters; + } + + /** + * Array of attributes to getter functions (for serialization of requests) + * @var string[] + */ + static $getters = array( + 'enum_string' => 'getEnumString', + 'enum_integer' => 'getEnumInteger', + 'enum_number' => 'getEnumNumber' + ); + + static function getters() { + return self::$getters; + } + + const ENUM_STRING_UPPER = 'UPPER'; + const ENUM_STRING_LOWER = 'lower'; + const ENUM_INTEGER_1 = 1; + const ENUM_INTEGER_MINUS_1 = -1; + const ENUM_NUMBER_1_DOT_1 = 1.1; + const ENUM_NUMBER_MINUS_1_DOT_2 = -1.2; + + + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getEnumStringAllowableValues() { + return [ + self::ENUM_STRING_UPPER, + self::ENUM_STRING_LOWER, + ]; + } + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getEnumIntegerAllowableValues() { + return [ + self::ENUM_INTEGER_1, + self::ENUM_INTEGER_MINUS_1, + ]; + } + + /** + * Gets allowable values of the enum + * @return string[] + */ + public function getEnumNumberAllowableValues() { + return [ + self::ENUM_NUMBER_1_DOT_1, + self::ENUM_NUMBER_MINUS_1_DOT_2, + ]; + } + + + /** + * Associative array for storing property values + * @var mixed[] + */ + protected $container = array( + /** + * $container['enum_string'] + * @var string + */ + 'enum_string' => null, + + /** + * $container['enum_integer'] + * @var int + */ + 'enum_integer' => null, + + /** + * $container['enum_number'] + * @var double + */ + 'enum_number' => null, + ); + + /** + * Constructor + * @param mixed[] $data Associated array of property value initalizing the model + */ + public function __construct(array $data = null) + { + + + if ($data != null) { + $this->container['enum_string'] = $data['enum_string']; + $this->container['enum_integer'] = $data['enum_integer']; + $this->container['enum_number'] = $data['enum_number']; + } + } + /** + * Gets enum_string + * @return string + */ + public function getEnumString() + { + return $this->container['enum_string']; + } + + /** + * Sets enum_string + * @param string $enum_string + * @return $this + */ + public function setEnumString($enum_string) + { + $allowed_values = array('UPPER', 'lower'); + if (!in_array($enum_string, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'enum_string', must be one of 'UPPER', 'lower'"); + } + $this->container['enum_string'] = $enum_string; + return $this; + } + /** + * Gets enum_integer + * @return int + */ + public function getEnumInteger() + { + return $this->container['enum_integer']; + } + + /** + * Sets enum_integer + * @param int $enum_integer + * @return $this + */ + public function setEnumInteger($enum_integer) + { + $allowed_values = array('1', '-1'); + if (!in_array($enum_integer, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'enum_integer', must be one of '1', '-1'"); + } + $this->container['enum_integer'] = $enum_integer; + return $this; + } + /** + * Gets enum_number + * @return double + */ + public function getEnumNumber() + { + return $this->container['enum_number']; + } + + /** + * Sets enum_number + * @param double $enum_number + * @return $this + */ + public function setEnumNumber($enum_number) + { + $allowed_values = array('1.1', '-1.2'); + if (!in_array($enum_number, $allowed_values)) { + throw new \InvalidArgumentException("Invalid value for 'enum_number', must be one of '1.1', '-1.2'"); + } + $this->container['enum_number'] = $enum_number; + return $this; + } + /** + * Returns true if offset exists. False otherwise. + * @param integer $offset Offset + * @return boolean + */ + public function offsetExists($offset) + { + return isset($this->container[$offset]); + } + + /** + * Gets offset. + * @param integer $offset Offset + * @return mixed + */ + public function offsetGet($offset) + { + return isset($this->container[$offset]) ? $this->container[$offset] : null; + } + + /** + * Sets value based on offset. + * @param integer $offset Offset + * @param mixed $value Value to be set + * @return void + */ + public function offsetSet($offset, $value) + { + if (is_null($offset)) { + $this->container[] = $value; + } else { + $this->container[$offset] = $value; + } + } + + /** + * Unsets offset. + * @param integer $offset Offset + * @return void + */ + public function offsetUnset($offset) + { + unset($this->container[$offset]); + } + + /** + * Gets the string presentation of the object + * @return string + */ + public function __toString() + { + if (defined('JSON_PRETTY_PRINT')) { // use JSON pretty print + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this), JSON_PRETTY_PRINT); + } + + return json_encode(\Swagger\Client\ObjectSerializer::sanitizeForSerialization($this)); + } +} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumClassTest.php b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumClassTest.php new file mode 100644 index 00000000000..4d901dfd1c9 --- /dev/null +++ b/samples/client/petstore/php/SwaggerClient-php/lib/Tests/EnumClassTest.php @@ -0,0 +1,70 @@ + e puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" @@ -91,7 +91,7 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- -*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters +*Petstore::FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 *Petstore::PetApi* | [**add_pet**](docs/PetApi.md#add_pet) | **POST** /pet | Add a new pet to the store *Petstore::PetApi* | [**delete_pet**](docs/PetApi.md#delete_pet) | **DELETE** /pet/{petId} | Deletes a pet *Petstore::PetApi* | [**find_pets_by_status**](docs/PetApi.md#find_pets_by_status) | **GET** /pet/findByStatus | Finds Pets by status @@ -117,10 +117,13 @@ Class | Method | HTTP request | Description ## Documentation for Models - [Petstore::Animal](docs/Animal.md) + - [Petstore::AnimalFarm](docs/AnimalFarm.md) - [Petstore::ApiResponse](docs/ApiResponse.md) - [Petstore::Cat](docs/Cat.md) - [Petstore::Category](docs/Category.md) - [Petstore::Dog](docs/Dog.md) + - [Petstore::EnumClass](docs/EnumClass.md) + - [Petstore::EnumTest](docs/EnumTest.md) - [Petstore::FormatTest](docs/FormatTest.md) - [Petstore::Model200Response](docs/Model200Response.md) - [Petstore::ModelReturn](docs/ModelReturn.md) diff --git a/samples/client/petstore/ruby/docs/AnimalFarm.md b/samples/client/petstore/ruby/docs/AnimalFarm.md new file mode 100644 index 00000000000..30d704dc7d1 --- /dev/null +++ b/samples/client/petstore/ruby/docs/AnimalFarm.md @@ -0,0 +1,7 @@ +# Petstore::AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/docs/EnumClass.md b/samples/client/petstore/ruby/docs/EnumClass.md new file mode 100644 index 00000000000..8d56e1f8873 --- /dev/null +++ b/samples/client/petstore/ruby/docs/EnumClass.md @@ -0,0 +1,7 @@ +# Petstore::EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + diff --git a/samples/client/petstore/ruby/docs/EnumTest.md b/samples/client/petstore/ruby/docs/EnumTest.md new file mode 100644 index 00000000000..ad3ee5c31bb --- /dev/null +++ b/samples/client/petstore/ruby/docs/EnumTest.md @@ -0,0 +1,10 @@ +# Petstore::EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enum_string** | **String** | | [optional] +**enum_integer** | **Integer** | | [optional] +**enum_number** | **Float** | | [optional] + + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 32f2902d930..c0312e00f51 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -4,15 +4,15 @@ All URIs are relative to *http://petstore.swagger.io/v2* Method | HTTP request | Description ------------- | ------------- | ------------- -[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters +[**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # **test_endpoint_parameters** > test_endpoint_parameters(number, double, string, byte, opts) -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 -Fake endpoint for testing various parameters +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 ### Example ```ruby @@ -41,7 +41,7 @@ opts = { } begin - #Fake endpoint for testing various parameters + #Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 api_instance.test_endpoint_parameters(number, double, string, byte, opts) rescue Petstore::ApiError => e puts "Exception when calling FakeApi->test_endpoint_parameters: #{e}" diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index f203db3f5ba..1ca35820523 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -22,10 +22,13 @@ require 'petstore/configuration' # Models require 'petstore/models/animal' +require 'petstore/models/animal_farm' require 'petstore/models/api_response' require 'petstore/models/cat' require 'petstore/models/category' require 'petstore/models/dog' +require 'petstore/models/enum_class' +require 'petstore/models/enum_test' require 'petstore/models/format_test' require 'petstore/models/model_200_response' require 'petstore/models/model_return' diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index a0cf2913f43..68f6fea9d2b 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -24,8 +24,8 @@ module Petstore @api_client = api_client end - # Fake endpoint for testing various parameters - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None # @param string None @@ -45,8 +45,8 @@ module Petstore return nil end - # Fake endpoint for testing various parameters - # Fake endpoint for testing various parameters + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + # Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # @param number None # @param double None # @param string None diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb new file mode 100644 index 00000000000..62ca66ce38b --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/animal_farm.rb @@ -0,0 +1,179 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class AnimalFarm + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + } + end + + # Attribute type mapping. + def self.swagger_types + { + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb new file mode 100644 index 00000000000..4dc0bb6c16b --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -0,0 +1,184 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class EnumClass + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + } + end + + # Attribute type mapping. + def self.swagger_types + { + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + allowed_values = ["_abc", "-efg", "(xyz)"] + if @EnumClass && !allowed_values.include?(EnumClass) + invalid_properties.push("invalid value for 'EnumClass', must be one of #{allowed_values}.") + end + + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb new file mode 100644 index 00000000000..3f045b3490e --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -0,0 +1,248 @@ +=begin +Swagger Petstore + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. + +OpenAPI spec version: 1.0.0 +Contact: apiteam@swagger.io +Generated by: https://github.com/swagger-api/swagger-codegen.git + +License: Apache 2.0 +http://www.apache.org/licenses/LICENSE-2.0.html + +Terms of Service: http://swagger.io/terms/ + +=end + +require 'date' + +module Petstore + class EnumTest + attr_accessor :enum_string + + attr_accessor :enum_integer + + attr_accessor :enum_number + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'enum_string' => :'enum_string', + :'enum_integer' => :'enum_integer', + :'enum_number' => :'enum_number' + } + end + + # Attribute type mapping. + def self.swagger_types + { + :'enum_string' => :'String', + :'enum_integer' => :'Integer', + :'enum_number' => :'Float' + } + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + return unless attributes.is_a?(Hash) + + # convert string to symbol for hash key + attributes = attributes.each_with_object({}){|(k,v), h| h[k.to_sym] = v} + + if attributes.has_key?(:'enum_string') + self.enum_string = attributes[:'enum_string'] + end + + if attributes.has_key?(:'enum_integer') + self.enum_integer = attributes[:'enum_integer'] + end + + if attributes.has_key?(:'enum_number') + self.enum_number = attributes[:'enum_number'] + end + + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properies with the reasons + def list_invalid_properties + invalid_properties = Array.new + return invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + allowed_values = ["UPPER", "lower"] + if @enum_string && !allowed_values.include?(@enum_string) + return false + end + allowed_values = ["1", "-1"] + if @enum_integer && !allowed_values.include?(@enum_integer) + return false + end + allowed_values = ["1.1", "-1.2"] + if @enum_number && !allowed_values.include?(@enum_number) + return false + end + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_string Object to be assigned + def enum_string=(enum_string) + allowed_values = ["UPPER", "lower"] + if enum_string && !allowed_values.include?(enum_string) + fail ArgumentError, "invalid value for 'enum_string', must be one of #{allowed_values}." + end + @enum_string = enum_string + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_integer Object to be assigned + def enum_integer=(enum_integer) + allowed_values = ["1", "-1"] + if enum_integer && !allowed_values.include?(enum_integer) + fail ArgumentError, "invalid value for 'enum_integer', must be one of #{allowed_values}." + end + @enum_integer = enum_integer + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] enum_number Object to be assigned + def enum_number=(enum_number) + allowed_values = ["1.1", "-1.2"] + if enum_number && !allowed_values.include?(enum_number) + fail ArgumentError, "invalid value for 'enum_number', must be one of #{allowed_values}." + end + @enum_number = enum_number + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + enum_string == o.enum_string && + enum_integer == o.enum_integer && + enum_number == o.enum_number + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Fixnum] Hash code + def hash + [enum_string, enum_integer, enum_number].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^Array<(.*)>/i + # check to ensure the input is an array given that the the attribute + # is documented as an array but the input is not + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + end # or else data not found in attributes(hash), not an issue as the data can be optional + end + + self + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :BOOLEAN + if value.to_s =~ /^(true|t|yes|y|1)$/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + temp_model = Petstore.const_get(type).new + temp_model.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + next if value.nil? + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map{ |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end From b3937c26564f8194ba2b62c41280d20f770206fa Mon Sep 17 00:00:00 2001 From: Leon Yu Date: Wed, 4 May 2016 17:38:53 -0400 Subject: [PATCH 10/27] Package management option ES6 target Fix enum --- .../TypeScriptFetchClientCodegen.java | 63 ++++++++++++++----- .../resources/TypeScript-Fetch/api.mustache | 10 +-- .../main/resources/TypeScript-Fetch/assign.ts | 2 +- .../resources/TypeScript-Fetch/package.json | 10 --- .../TypeScript-Fetch/package.json.mustache | 17 +++++ .../resources/TypeScript-Fetch/tsconfig.json | 11 ---- .../TypeScript-Fetch/tsconfig.json.mustache | 14 +++++ .../{typings.json => typings.json.mustache} | 4 +- .../TypeScriptFetchClientOptionsProvider.java | 5 ++ 9 files changed, 92 insertions(+), 44 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json create mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json create mode 100644 modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache rename modules/swagger-codegen/src/main/resources/TypeScript-Fetch/{typings.json => typings.json.mustache} (56%) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java index 804f48d79f7..5bc848a7c78 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/TypeScriptFetchClientCodegen.java @@ -1,11 +1,47 @@ package io.swagger.codegen.languages; +import io.swagger.codegen.CliOption; import io.swagger.codegen.SupportingFile; import java.io.File; public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodegen { + public static final String NPM_NAME = "npmName"; + public static final String NPM_VERSION = "npmVersion"; + + protected String npmName = null; + protected String npmVersion = "1.0.0"; + + public TypeScriptFetchClientCodegen() { + super(); + outputFolder = "generated-code/typescript-fetch"; + embeddedTemplateDir = templateDir = "TypeScript-Fetch"; + this.cliOptions.add(new CliOption(NPM_NAME, "The name under which you want to publish generated npm package")); + this.cliOptions.add(new CliOption(NPM_VERSION, "The version of your npm package")); + } + + @Override + public void processOpts() { + super.processOpts(); + final String defaultFolder = apiPackage().replace('.', File.separatorChar); + + supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("assign.ts", defaultFolder, "assign.ts")); + supportingFiles.add(new SupportingFile("package.json.mustache", "", "package.json")); + supportingFiles.add(new SupportingFile("typings.json.mustache", "", "typings.json")); + supportingFiles.add(new SupportingFile("tsconfig.json.mustache", "", "tsconfig.json")); + + if(additionalProperties.containsKey(NPM_NAME)) { + this.setNpmName(additionalProperties.get(NPM_NAME).toString()); + } + + if (additionalProperties.containsKey(NPM_VERSION)) { + this.setNpmVersion(additionalProperties.get(NPM_VERSION).toString()); + } + } + @Override public String getName() { return "typescript-fetch"; @@ -16,23 +52,20 @@ public class TypeScriptFetchClientCodegen extends AbstractTypeScriptClientCodege return "Generates a TypeScript client library using Fetch API (beta)."; } - @Override - public void processOpts() { - super.processOpts(); - final String defaultFolder = apiPackage().replace('.', File.separatorChar); - - supportingFiles.add(new SupportingFile("api.mustache", null, "api.ts")); - supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); - supportingFiles.add(new SupportingFile("assign.ts", defaultFolder, "assign.ts")); - supportingFiles.add(new SupportingFile("package.json", "", "package.json")); - supportingFiles.add(new SupportingFile("typings.json", "", "typings.json")); - supportingFiles.add(new SupportingFile("tsconfig.json", "", "tsconfig.json")); + public String getNpmName() { + return npmName; } - public TypeScriptFetchClientCodegen() { - super(); - outputFolder = "generated-code/typescript-fetch"; - embeddedTemplateDir = templateDir = "TypeScript-Fetch"; + public void setNpmName(String npmName) { + this.npmName = npmName; + } + + public String getNpmVersion() { + return npmVersion; + } + + public void setNpmVersion(String npmVersion) { + this.npmVersion = npmVersion; } } diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache index 02e6816ff26..67d61999aa0 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/api.mustache @@ -23,14 +23,14 @@ export interface {{classname}} {{#parent}}extends {{{parent}}} {{/parent}}{ } {{#hasEnums}} +export namespace {{classname}} { {{#vars}} {{#isEnum}} -export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} - {{.}} = '{{.}}'{{^-last}},{{/-last}}{{/values}}{{/allowableValues}} -} +export type {{datatypeWithEnum}} = {{#allowableValues}}{{#values}}'{{.}}'{{^-last}} | {{/-last}}{{/values}}{{/allowableValues}}; {{/isEnum}} {{/vars}} +} {{/hasEnums}} {{/model}} {{/models}} @@ -119,8 +119,8 @@ export enum {{datatypeWithEnum}} { {{#allowableValues}}{{#values}} if (response.status >= 200 && response.status < 300) { return response.json(); } else { - var error = new Error(response.statusText); - error['response'] = response; + let error = new Error(response.statusText); + (error as any).response = response; throw error; } }); diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts index 040f87d7d98..23355144147 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/assign.ts @@ -1,4 +1,4 @@ -export function assign (target, ...args) { +export function assign (target: any, ...args: any[]) { 'use strict'; if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json deleted file mode 100644 index 722c87cc323..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "private": true, - "dependencies": { - "isomorphic-fetch": "^2.2.1" - }, - "devDependencies": { - "typescript": "^1.8.10", - "typings": "^0.8.1" - } -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache new file mode 100644 index 00000000000..7e94923c142 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/package.json.mustache @@ -0,0 +1,17 @@ +{ + "name": "{{#npmName}}{{{npmName}}}{{/npmName}}{{^npmName}}typescript-fetch-api{{/npmName}}", + "version": "{{#npmVersion}}{{{npmVersion}}}{{/npmVersion}}{{^npmVersion}}0.0.0{{/npmVersion}}", + "private": true, + "main": "dist/api.js", + "browser": "dist/api.js", + "dependencies": { + "isomorphic-fetch": "^2.2.1" + }, + "scripts" : { + "install" : "typings install && tsc" + }, + "devDependencies": { + "typescript": "^1.8.10", + "typings": "^0.8.1" + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json deleted file mode 100644 index fc93dc1610e..00000000000 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "compilerOptions": { - "target": "es5" - }, - "exclude": [ - "node_modules", - "typings/browser", - "typings/main", - "typings/main.d.ts" - ] -} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache new file mode 100644 index 00000000000..457b7f53db8 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/tsconfig.json.mustache @@ -0,0 +1,14 @@ +{ + "compilerOptions": { + "target": "{{#supportsES6}}es6{{/supportsES6}}{{^supportsES6}}es5{{/supportsES6}}", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist" + }, + "exclude": [ + "node_modules", + "typings/browser", + "typings/main", + "typings/main.d.ts" + ] +} diff --git a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache similarity index 56% rename from modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json rename to modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache index c22f086f7f0..1d1b679de8c 100644 --- a/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json +++ b/modules/swagger-codegen/src/main/resources/TypeScript-Fetch/typings.json.mustache @@ -2,8 +2,8 @@ "version": false, "dependencies": {}, "ambientDependencies": { - "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", - "node": "registry:dt/node#4.0.0+20160423143914", +{{^supportsES6}} "es6-promise": "registry:dt/es6-promise#0.0.0+20160423074304", +{{/supportsES6}} "node": "registry:dt/node#4.0.0+20160423143914", "isomorphic-fetch": "github:leonyu/DefinitelyTyped/isomorphic-fetch/isomorphic-fetch.d.ts#isomorphic-fetch-fix-module" } } diff --git a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java index 46452af1622..cc5be4fe456 100644 --- a/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java +++ b/modules/swagger-codegen/src/test/java/io/swagger/codegen/options/TypeScriptFetchClientOptionsProvider.java @@ -2,6 +2,7 @@ package io.swagger.codegen.options; import com.google.common.collect.ImmutableMap; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.languages.TypeScriptFetchClientCodegen; import java.util.Map; @@ -10,6 +11,8 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; public static final Boolean SUPPORTS_ES6_VALUE = false; public static final String MODEL_PROPERTY_NAMING_VALUE = "camelCase"; + private static final String NMP_NAME = "npmName"; + private static final String NMP_VERSION = "1.0.0"; @Override public String getLanguage() { @@ -23,6 +26,8 @@ public class TypeScriptFetchClientOptionsProvider implements OptionsProvider { .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING_VALUE) .put(CodegenConstants.SUPPORTS_ES6, String.valueOf(SUPPORTS_ES6_VALUE)) + .put(TypeScriptFetchClientCodegen.NPM_NAME, NMP_NAME) + .put(TypeScriptFetchClientCodegen.NPM_VERSION, NMP_VERSION) .build(); } From 64548d9bf5d73d54f1fa84751357d40776ad89a1 Mon Sep 17 00:00:00 2001 From: Leon Yu Date: Fri, 6 May 2016 15:54:15 -0400 Subject: [PATCH 11/27] Update bin --- bin/typescript-fetch-petstore-target-es6.json | 3 ++ bin/typescript-fetch-petstore-target-es6.sh | 31 +++++++++++++++++++ ...petstore-target-with-package-metadata.json | 4 +++ ...h-petstore-target-with-package-metadata.sh | 31 +++++++++++++++++++ bin/typescript-fetch-petstore.sh | 2 +- 5 files changed, 70 insertions(+), 1 deletion(-) create mode 100644 bin/typescript-fetch-petstore-target-es6.json create mode 100755 bin/typescript-fetch-petstore-target-es6.sh create mode 100644 bin/typescript-fetch-petstore-target-with-package-metadata.json create mode 100755 bin/typescript-fetch-petstore-target-with-package-metadata.sh diff --git a/bin/typescript-fetch-petstore-target-es6.json b/bin/typescript-fetch-petstore-target-es6.json new file mode 100644 index 00000000000..83914bd569c --- /dev/null +++ b/bin/typescript-fetch-petstore-target-es6.json @@ -0,0 +1,3 @@ +{ + "supportsES6": true +} diff --git a/bin/typescript-fetch-petstore-target-es6.sh b/bin/typescript-fetch-petstore-target-es6.sh new file mode 100755 index 00000000000..3734e7e3449 --- /dev/null +++ b/bin/typescript-fetch-petstore-target-es6.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-es6.json -o samples/client/petstore/typescript-fetch/default-es6" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.json b/bin/typescript-fetch-petstore-target-with-package-metadata.json new file mode 100644 index 00000000000..b8193c8fa74 --- /dev/null +++ b/bin/typescript-fetch-petstore-target-with-package-metadata.json @@ -0,0 +1,4 @@ +{ + "npmName": "@swagger/typescript-fetch-petstore", + "npmVersion": "0.0.1" +} diff --git a/bin/typescript-fetch-petstore-target-with-package-metadata.sh b/bin/typescript-fetch-petstore-target-with-package-metadata.sh new file mode 100755 index 00000000000..3c4978c8a80 --- /dev/null +++ b/bin/typescript-fetch-petstore-target-with-package-metadata.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -c bin/typescript-fetch-petstore-target-with-package-metadata.json -o samples/client/petstore/typescript-fetch/with-package-metadata" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/typescript-fetch-petstore.sh b/bin/typescript-fetch-petstore.sh index a4fc62dac90..6283285c736 100755 --- a/bin/typescript-fetch-petstore.sh +++ b/bin/typescript-fetch-petstore.sh @@ -26,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l typescript-fetch -o samples/client/petstore/typescript-fetch/default" java $JAVA_OPTS -jar $executable $ags From fed22a1f72e6559536c974181cf281ac9ed1e95a Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Fri, 6 May 2016 22:52:44 +0100 Subject: [PATCH 12/27] Add regex support --- .../src/main/resources/python/api.mustache | 4 +- .../src/main/resources/python/model.mustache | 35 +++++------ samples/client/petstore/python/README.md | 6 +- samples/client/petstore/python/git_push.sh | 4 +- .../python/swagger_client/apis/fake_api.py | 26 ++++++++ .../python/swagger_client/apis/pet_api.py | 9 +++ .../python/swagger_client/apis/store_api.py | 11 ++++ .../python/swagger_client/apis/user_api.py | 9 +++ .../python/swagger_client/models/animal.py | 2 + .../swagger_client/models/api_response.py | 4 ++ .../python/swagger_client/models/cat.py | 3 + .../python/swagger_client/models/category.py | 3 + .../python/swagger_client/models/dog.py | 3 + .../swagger_client/models/format_test.py | 61 +++++++++++++++++++ .../models/model_200_response.py | 2 + .../swagger_client/models/model_return.py | 2 + .../python/swagger_client/models/name.py | 4 ++ .../python/swagger_client/models/order.py | 7 +++ .../python/swagger_client/models/pet.py | 7 +++ .../models/special_model_name.py | 2 + .../python/swagger_client/models/tag.py | 3 + .../python/swagger_client/models/user.py | 9 +++ 22 files changed, 192 insertions(+), 24 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 7902754e5fb..399c7f58451 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -116,8 +116,8 @@ class {{classname}}(object): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - #if not re.match('{{pattern}}', '{{paramName}}' in params and params['{{paramName}}']): - # raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") + if '{{paramName}}' in params and not re.match('{{pattern}}', params['{{paramName}}']): + raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") {{/pattern}} {{/hasValidation}} {{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 3fce2b47697..0cb98a57ef0 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -80,34 +80,35 @@ class {{classname}}(object): "Invalid value for `{{name}}`, must be one of {0}" .format(allowed_values) ) - {{/isEnum}} - {{^isEnum}} +{{/isEnum}} +{{^isEnum}} +{{#hasValidation}} - {{#hasValidation}} if not {{name}}: raise ValueError("Invalid value for `{{name}}`, must not be `None`") - {{#maxLength}} +{{#maxLength}} if len({{name}}) > {{maxLength}}: raise ValueError("Invalid value for `{{name}}`, length must be less than `{{maxLength}}`") - {{/maxLength}} - {{#minLength}} +{{/maxLength}} +{{#minLength}} if len({{name}}) < {{minLength}}: raise ValueError("Invalid value for `{{name}}`, length must be greater than or equal to `{{minLength}}`") - {{/minLength}} - {{#maximum}} +{{/minLength}} +{{#maximum}} if {{name}} > {{maximum}}: raise ValueError("Invalid value for `{{name}}`, must be a value less than or equal to `{{maximum}}`") - {{/maximum}} - {{#minimum}} +{{/maximum}} +{{#minimum}} if {{name}} < {{minimum}}: raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") - {{/minimum}} - {{#pattern}} - #if not re.match('/[a-z]/i', {{name}}): - # raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") - {{/pattern}} - {{/hasValidation}} - {{/isEnum}} +{{/minimum}} +{{#pattern}} + if not re.match('{{pattern}}', {{name}}): + raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") +{{/pattern}} +{{/hasValidation}} +{{/isEnum}} + self._{{name}} = {{name}} {{/vars}} diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 6640785fae9..990d5e53651 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-04-27T22:50:21.115+01:00 +- Build date: 2016-05-06T22:43:12.044+01:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. @@ -18,9 +18,9 @@ Python 2.7 and 3.4+ If the python package is hosted on Github, you can install directly from Github ```sh -pip install git+https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git +pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git ``` -(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git`) +(you may need to run `pip` with root permission: `sudo pip install git+https://github.com/GIT_USER_ID/GIT_REPO_ID.git`) Then import the package: ```python diff --git a/samples/client/petstore/python/git_push.sh b/samples/client/petstore/python/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/python/git_push.sh +++ b/samples/client/petstore/python/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/python/swagger_client/apis/fake_api.py b/samples/client/petstore/python/swagger_client/apis/fake_api.py index 2b183794ef1..ba79874f6c7 100644 --- a/samples/client/petstore/python/swagger_client/apis/fake_api.py +++ b/samples/client/petstore/python/swagger_client/apis/fake_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -103,6 +104,31 @@ class FakeApi(object): if ('byte' not in params) or (params['byte'] is None): raise ValueError("Missing the required parameter `byte` when calling `test_endpoint_parameters`") + if 'number' in params and params['number'] > 543.2: + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value less than or equal to `543.2`") + if 'number' in params and params['number'] < 32.1: + raise ValueError("Invalid value for parameter `number` when calling `test_endpoint_parameters`, must be a value greater than or equal to `32.1`") + if 'double' in params and params['double'] > 123.4: + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") + if 'double' in params and params['double'] < 67.8: + raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") + if 'string' in params and not re.match('[a-z]+', params['string']): + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `[a-z]+`") + if 'integer' in params and params['integer'] > 100.0: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") + if 'integer' in params and params['integer'] < 10.0: + raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value greater than or equal to `10.0`") + if 'int32' in params and params['int32'] > 200.0: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value less than or equal to `200.0`") + if 'int32' in params and params['int32'] < 20.0: + raise ValueError("Invalid value for parameter `int32` when calling `test_endpoint_parameters`, must be a value greater than or equal to `20.0`") + if 'float' in params and params['float'] > 987.6: + raise ValueError("Invalid value for parameter `float` when calling `test_endpoint_parameters`, must be a value less than or equal to `987.6`") + if 'password' in params and len(params['password']) > 64: + raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be less than or equal to `64`") + if 'password' in params and len(params['password']) < 10: + raise ValueError("Invalid value for parameter `password` when calling `test_endpoint_parameters`, length must be greater than or equal to `10`") + resource_path = '/fake'.replace('{format}', 'json') path_params = {} 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 cab854e3019..3b6d9ba82fe 100644 --- a/samples/client/petstore/python/swagger_client/apis/pet_api.py +++ b/samples/client/petstore/python/swagger_client/apis/pet_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -83,6 +84,7 @@ class PetApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `add_pet`") + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -161,6 +163,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -240,6 +243,7 @@ class PetApi(object): if ('status' not in params) or (params['status'] is None): raise ValueError("Missing the required parameter `status` when calling `find_pets_by_status`") + resource_path = '/pet/findByStatus'.replace('{format}', 'json') path_params = {} @@ -317,6 +321,7 @@ class PetApi(object): if ('tags' not in params) or (params['tags'] is None): raise ValueError("Missing the required parameter `tags` when calling `find_pets_by_tags`") + resource_path = '/pet/findByTags'.replace('{format}', 'json') path_params = {} @@ -394,6 +399,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -471,6 +477,7 @@ class PetApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_pet`") + resource_path = '/pet'.replace('{format}', 'json') path_params = {} @@ -550,6 +557,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + resource_path = '/pet/{petId}'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: @@ -633,6 +641,7 @@ class PetApi(object): if ('pet_id' not in params) or (params['pet_id'] is None): raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') path_params = {} if 'pet_id' in params: 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 9391a6a6096..352ab7eae63 100644 --- a/samples/client/petstore/python/swagger_client/apis/store_api.py +++ b/samples/client/petstore/python/swagger_client/apis/store_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -83,6 +84,9 @@ class StoreApi(object): if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") + if 'order_id' in params and params['order_id'] < 1.0: + raise ValueError("Invalid value for parameter `order_id` when calling `delete_order`, must be a value greater than or equal to `1.0`") + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -156,6 +160,7 @@ class StoreApi(object): del params['kwargs'] + resource_path = '/store/inventory'.replace('{format}', 'json') path_params = {} @@ -231,6 +236,11 @@ class StoreApi(object): if ('order_id' not in params) or (params['order_id'] is None): raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") + if 'order_id' in params and params['order_id'] > 5.0: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value less than or equal to `5.0`") + if 'order_id' in params and params['order_id'] < 1.0: + raise ValueError("Invalid value for parameter `order_id` when calling `get_order_by_id`, must be a value greater than or equal to `1.0`") + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') path_params = {} if 'order_id' in params: @@ -308,6 +318,7 @@ class StoreApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `place_order`") + resource_path = '/store/order'.replace('{format}', 'json') path_params = {} 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 733a950f393..d5df6f0f541 100644 --- a/samples/client/petstore/python/swagger_client/apis/user_api.py +++ b/samples/client/petstore/python/swagger_client/apis/user_api.py @@ -21,6 +21,7 @@ from __future__ import absolute_import import sys import os +import re # python 2 and python 3 compatibility library from six import iteritems @@ -83,6 +84,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_user`") + resource_path = '/user'.replace('{format}', 'json') path_params = {} @@ -160,6 +162,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_array_input`") + resource_path = '/user/createWithArray'.replace('{format}', 'json') path_params = {} @@ -237,6 +240,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_users_with_list_input`") + resource_path = '/user/createWithList'.replace('{format}', 'json') path_params = {} @@ -314,6 +318,7 @@ class UserApi(object): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `delete_user`") + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -391,6 +396,7 @@ class UserApi(object): if ('username' not in params) or (params['username'] is None): raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: @@ -472,6 +478,7 @@ class UserApi(object): if ('password' not in params) or (params['password'] is None): raise ValueError("Missing the required parameter `password` when calling `login_user`") + resource_path = '/user/login'.replace('{format}', 'json') path_params = {} @@ -547,6 +554,7 @@ class UserApi(object): del params['kwargs'] + resource_path = '/user/logout'.replace('{format}', 'json') path_params = {} @@ -626,6 +634,7 @@ class UserApi(object): if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `update_user`") + resource_path = '/user/{username}'.replace('{format}', 'json') path_params = {} if 'username' in params: diff --git a/samples/client/petstore/python/swagger_client/models/animal.py b/samples/client/petstore/python/swagger_client/models/animal.py index 762e3df5b37..0ae8f2b4bde 100644 --- a/samples/client/petstore/python/swagger_client/models/animal.py +++ b/samples/client/petstore/python/swagger_client/models/animal.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Animal(object): @@ -66,6 +67,7 @@ class Animal(object): :param class_name: The class_name of this Animal. :type: str """ + self._class_name = class_name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/api_response.py b/samples/client/petstore/python/swagger_client/models/api_response.py index c49bde7fbc6..918b4a98223 100644 --- a/samples/client/petstore/python/swagger_client/models/api_response.py +++ b/samples/client/petstore/python/swagger_client/models/api_response.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class ApiResponse(object): @@ -72,6 +73,7 @@ class ApiResponse(object): :param code: The code of this ApiResponse. :type: int """ + self._code = code @property @@ -94,6 +96,7 @@ class ApiResponse(object): :param type: The type of this ApiResponse. :type: str """ + self._type = type @property @@ -116,6 +119,7 @@ class ApiResponse(object): :param message: The message of this ApiResponse. :type: str """ + self._message = message def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/cat.py b/samples/client/petstore/python/swagger_client/models/cat.py index 4744fc4821c..fd2e5e4fce4 100644 --- a/samples/client/petstore/python/swagger_client/models/cat.py +++ b/samples/client/petstore/python/swagger_client/models/cat.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Cat(object): @@ -69,6 +70,7 @@ class Cat(object): :param class_name: The class_name of this Cat. :type: str """ + self._class_name = class_name @property @@ -91,6 +93,7 @@ class Cat(object): :param declawed: The declawed of this Cat. :type: bool """ + self._declawed = declawed def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/category.py b/samples/client/petstore/python/swagger_client/models/category.py index b8d540c51bd..e4f4a993cab 100644 --- a/samples/client/petstore/python/swagger_client/models/category.py +++ b/samples/client/petstore/python/swagger_client/models/category.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Category(object): @@ -69,6 +70,7 @@ class Category(object): :param id: The id of this Category. :type: int """ + self._id = id @property @@ -91,6 +93,7 @@ class Category(object): :param name: The name of this Category. :type: str """ + self._name = name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/dog.py b/samples/client/petstore/python/swagger_client/models/dog.py index 3885dd314ef..ac25ef01807 100644 --- a/samples/client/petstore/python/swagger_client/models/dog.py +++ b/samples/client/petstore/python/swagger_client/models/dog.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Dog(object): @@ -69,6 +70,7 @@ class Dog(object): :param class_name: The class_name of this Dog. :type: str """ + self._class_name = class_name @property @@ -91,6 +93,7 @@ class Dog(object): :param breed: The breed of this Dog. :type: str """ + self._breed = breed def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/format_test.py b/samples/client/petstore/python/swagger_client/models/format_test.py index 28f348edf04..eee1b5c9ef7 100644 --- a/samples/client/petstore/python/swagger_client/models/format_test.py +++ b/samples/client/petstore/python/swagger_client/models/format_test.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class FormatTest(object): @@ -102,6 +103,14 @@ class FormatTest(object): :param integer: The integer of this FormatTest. :type: int """ + + if not integer: + raise ValueError("Invalid value for `integer`, must not be `None`") + if integer > 100.0: + raise ValueError("Invalid value for `integer`, must be a value less than or equal to `100.0`") + if integer < 10.0: + raise ValueError("Invalid value for `integer`, must be a value greater than or equal to `10.0`") + self._integer = integer @property @@ -124,6 +133,14 @@ class FormatTest(object): :param int32: The int32 of this FormatTest. :type: int """ + + if not int32: + raise ValueError("Invalid value for `int32`, must not be `None`") + if int32 > 200.0: + raise ValueError("Invalid value for `int32`, must be a value less than or equal to `200.0`") + if int32 < 20.0: + raise ValueError("Invalid value for `int32`, must be a value greater than or equal to `20.0`") + self._int32 = int32 @property @@ -146,6 +163,7 @@ class FormatTest(object): :param int64: The int64 of this FormatTest. :type: int """ + self._int64 = int64 @property @@ -168,6 +186,14 @@ class FormatTest(object): :param number: The number of this FormatTest. :type: float """ + + if not number: + raise ValueError("Invalid value for `number`, must not be `None`") + if number > 543.2: + raise ValueError("Invalid value for `number`, must be a value less than or equal to `543.2`") + if number < 32.1: + raise ValueError("Invalid value for `number`, must be a value greater than or equal to `32.1`") + self._number = number @property @@ -190,6 +216,14 @@ class FormatTest(object): :param float: The float of this FormatTest. :type: float """ + + if not float: + raise ValueError("Invalid value for `float`, must not be `None`") + if float > 987.6: + raise ValueError("Invalid value for `float`, must be a value less than or equal to `987.6`") + if float < 54.3: + raise ValueError("Invalid value for `float`, must be a value greater than or equal to `54.3`") + self._float = float @property @@ -212,6 +246,14 @@ class FormatTest(object): :param double: The double of this FormatTest. :type: float """ + + if not double: + raise ValueError("Invalid value for `double`, must not be `None`") + if double > 123.4: + raise ValueError("Invalid value for `double`, must be a value less than or equal to `123.4`") + if double < 67.8: + raise ValueError("Invalid value for `double`, must be a value greater than or equal to `67.8`") + self._double = double @property @@ -234,6 +276,12 @@ class FormatTest(object): :param string: The string of this FormatTest. :type: str """ + + if not string: + raise ValueError("Invalid value for `string`, must not be `None`") + if not re.match('/[a-z]/i', string): + raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") + self._string = string @property @@ -256,6 +304,7 @@ class FormatTest(object): :param byte: The byte of this FormatTest. :type: str """ + self._byte = byte @property @@ -278,6 +327,7 @@ class FormatTest(object): :param binary: The binary of this FormatTest. :type: str """ + self._binary = binary @property @@ -300,6 +350,7 @@ class FormatTest(object): :param date: The date of this FormatTest. :type: date """ + self._date = date @property @@ -322,6 +373,7 @@ class FormatTest(object): :param date_time: The date_time of this FormatTest. :type: datetime """ + self._date_time = date_time @property @@ -344,6 +396,7 @@ class FormatTest(object): :param uuid: The uuid of this FormatTest. :type: str """ + self._uuid = uuid @property @@ -366,6 +419,14 @@ class FormatTest(object): :param password: The password of this FormatTest. :type: str """ + + if not password: + raise ValueError("Invalid value for `password`, must not be `None`") + if len(password) > 64: + raise ValueError("Invalid value for `password`, length must be less than `64`") + if len(password) < 10: + raise ValueError("Invalid value for `password`, length must be greater than or equal to `10`") + self._password = password def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/model_200_response.py b/samples/client/petstore/python/swagger_client/models/model_200_response.py index 681de963e6e..f99847cbdd5 100644 --- a/samples/client/petstore/python/swagger_client/models/model_200_response.py +++ b/samples/client/petstore/python/swagger_client/models/model_200_response.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Model200Response(object): @@ -66,6 +67,7 @@ class Model200Response(object): :param name: The name of this Model200Response. :type: int """ + self._name = name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/model_return.py b/samples/client/petstore/python/swagger_client/models/model_return.py index 75b46259d6f..8228f41943c 100644 --- a/samples/client/petstore/python/swagger_client/models/model_return.py +++ b/samples/client/petstore/python/swagger_client/models/model_return.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class ModelReturn(object): @@ -66,6 +67,7 @@ class ModelReturn(object): :param _return: The _return of this ModelReturn. :type: int """ + self.__return = _return def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/name.py b/samples/client/petstore/python/swagger_client/models/name.py index 4fbf1a03211..51345d131ff 100644 --- a/samples/client/petstore/python/swagger_client/models/name.py +++ b/samples/client/petstore/python/swagger_client/models/name.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Name(object): @@ -72,6 +73,7 @@ class Name(object): :param name: The name of this Name. :type: int """ + self._name = name @property @@ -94,6 +96,7 @@ class Name(object): :param snake_case: The snake_case of this Name. :type: int """ + self._snake_case = snake_case @property @@ -116,6 +119,7 @@ class Name(object): :param _property: The _property of this Name. :type: str """ + self.__property = _property def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/order.py b/samples/client/petstore/python/swagger_client/models/order.py index 8fe90765e03..07f2c627d91 100644 --- a/samples/client/petstore/python/swagger_client/models/order.py +++ b/samples/client/petstore/python/swagger_client/models/order.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Order(object): @@ -81,6 +82,7 @@ class Order(object): :param id: The id of this Order. :type: int """ + self._id = id @property @@ -103,6 +105,7 @@ class Order(object): :param pet_id: The pet_id of this Order. :type: int """ + self._pet_id = pet_id @property @@ -125,6 +128,7 @@ class Order(object): :param quantity: The quantity of this Order. :type: int """ + self._quantity = quantity @property @@ -147,6 +151,7 @@ class Order(object): :param ship_date: The ship_date of this Order. :type: datetime """ + self._ship_date = ship_date @property @@ -175,6 +180,7 @@ class Order(object): "Invalid value for `status`, must be one of {0}" .format(allowed_values) ) + self._status = status @property @@ -197,6 +203,7 @@ class Order(object): :param complete: The complete of this Order. :type: bool """ + self._complete = complete def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/pet.py b/samples/client/petstore/python/swagger_client/models/pet.py index dfa614b1e9b..60f762238f3 100644 --- a/samples/client/petstore/python/swagger_client/models/pet.py +++ b/samples/client/petstore/python/swagger_client/models/pet.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Pet(object): @@ -81,6 +82,7 @@ class Pet(object): :param id: The id of this Pet. :type: int """ + self._id = id @property @@ -103,6 +105,7 @@ class Pet(object): :param category: The category of this Pet. :type: Category """ + self._category = category @property @@ -125,6 +128,7 @@ class Pet(object): :param name: The name of this Pet. :type: str """ + self._name = name @property @@ -147,6 +151,7 @@ class Pet(object): :param photo_urls: The photo_urls of this Pet. :type: list[str] """ + self._photo_urls = photo_urls @property @@ -169,6 +174,7 @@ class Pet(object): :param tags: The tags of this Pet. :type: list[Tag] """ + self._tags = tags @property @@ -197,6 +203,7 @@ class Pet(object): "Invalid value for `status`, must be one of {0}" .format(allowed_values) ) + self._status = status def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/special_model_name.py b/samples/client/petstore/python/swagger_client/models/special_model_name.py index 191798d7d9a..3e45c0e4496 100644 --- a/samples/client/petstore/python/swagger_client/models/special_model_name.py +++ b/samples/client/petstore/python/swagger_client/models/special_model_name.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class SpecialModelName(object): @@ -66,6 +67,7 @@ class SpecialModelName(object): :param special_property_name: The special_property_name of this SpecialModelName. :type: int """ + self._special_property_name = special_property_name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/tag.py b/samples/client/petstore/python/swagger_client/models/tag.py index 50f829d65e3..f09a4c36df3 100644 --- a/samples/client/petstore/python/swagger_client/models/tag.py +++ b/samples/client/petstore/python/swagger_client/models/tag.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class Tag(object): @@ -69,6 +70,7 @@ class Tag(object): :param id: The id of this Tag. :type: int """ + self._id = id @property @@ -91,6 +93,7 @@ class Tag(object): :param name: The name of this Tag. :type: str """ + self._name = name def to_dict(self): diff --git a/samples/client/petstore/python/swagger_client/models/user.py b/samples/client/petstore/python/swagger_client/models/user.py index fd6d16824b3..87d132a5037 100644 --- a/samples/client/petstore/python/swagger_client/models/user.py +++ b/samples/client/petstore/python/swagger_client/models/user.py @@ -20,6 +20,7 @@ Copyright 2016 SmartBear Software from pprint import pformat from six import iteritems +import re class User(object): @@ -87,6 +88,7 @@ class User(object): :param id: The id of this User. :type: int """ + self._id = id @property @@ -109,6 +111,7 @@ class User(object): :param username: The username of this User. :type: str """ + self._username = username @property @@ -131,6 +134,7 @@ class User(object): :param first_name: The first_name of this User. :type: str """ + self._first_name = first_name @property @@ -153,6 +157,7 @@ class User(object): :param last_name: The last_name of this User. :type: str """ + self._last_name = last_name @property @@ -175,6 +180,7 @@ class User(object): :param email: The email of this User. :type: str """ + self._email = email @property @@ -197,6 +203,7 @@ class User(object): :param password: The password of this User. :type: str """ + self._password = password @property @@ -219,6 +226,7 @@ class User(object): :param phone: The phone of this User. :type: str """ + self._phone = phone @property @@ -241,6 +249,7 @@ class User(object): :param user_status: The user_status of this User. :type: int """ + self._user_status = user_status def to_dict(self): From 3629fbac44d7e36776f411136d70c0421dd779b9 Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Sat, 7 May 2016 14:12:19 +0800 Subject: [PATCH 13/27] add pom.mustache for android api client(using volley HTTP library);update android api client samples(using volley HTTP library); --- .../languages/AndroidClientCodegen.java | 2 +- .../android/libraries/volley/pom.mustache | 48 +++++++++++++++++++ .../client/petstore/android/volley/pom.xml | 17 +++++-- 3 files changed, 61 insertions(+), 6 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.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 c0bead5c695..324453991e0 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 @@ -317,7 +317,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } private void addSupportingFilesForVolley() { - // supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache new file mode 100644 index 00000000000..09f55a743a7 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache @@ -0,0 +1,48 @@ + + + 4.0.0 + io.swagger + volley + 1.0.0 + + + io.swagger + swagger-annotations + ${swagger-annotations-version} + compile + + + org.apache.httpcomponents + httpcore + ${httpcomponents-httpcore-version} + compile + + + org.apache.httpcomponents + httpmime + ${httpcomponents-httpmime-version} + compile + + + com.google.code.gson + gson + ${google-code-gson-version} + compile + + + com.mcxiaoke.volley + library + ${volley-library-version} + aar + compile + + + + 1.5.0 + 4.4.4 + 4.5.2 + 2.3.1 + 1.0.19 + + diff --git a/samples/client/petstore/android/volley/pom.xml b/samples/client/petstore/android/volley/pom.xml index 2a3b8ef2f96..09f55a743a7 100644 --- a/samples/client/petstore/android/volley/pom.xml +++ b/samples/client/petstore/android/volley/pom.xml @@ -9,33 +9,40 @@ io.swagger swagger-annotations - 1.5.0 + ${swagger-annotations-version} compile org.apache.httpcomponents httpcore - 4.4.4 + ${httpcomponents-httpcore-version} compile org.apache.httpcomponents httpmime - 4.5.2 + ${httpcomponents-httpmime-version} compile com.google.code.gson gson - 2.3.1 + ${google-code-gson-version} compile com.mcxiaoke.volley library - 1.0.19 + ${volley-library-version} aar compile + + 1.5.0 + 4.4.4 + 4.5.2 + 2.3.1 + 1.0.19 + From 101f9a4086a795f970cdf999b5cda29207f6eb83 Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Sat, 7 May 2016 14:33:47 +0800 Subject: [PATCH 14/27] add generated markdown files to android api client for default and volley; --- .../languages/AndroidClientCodegen.java | 101 +++++ .../main/resources/android/README.mustache | 125 ++++++ .../main/resources/android/api_doc.mustache | 60 +++ .../main/resources/android/model_doc.mustache | 3 + .../main/resources/android/pojo_doc.mustache | 15 + .../client/petstore/android/default/README.md | 142 +++++++ .../petstore/android/default/docs/Category.md | 11 + .../petstore/android/default/docs/Order.md | 21 + .../petstore/android/default/docs/Pet.md | 21 + .../petstore/android/default/docs/PetApi.md | 365 ++++++++++++++++++ .../petstore/android/default/docs/StoreApi.md | 179 +++++++++ .../petstore/android/default/docs/Tag.md | 11 + .../petstore/android/default/docs/User.md | 17 + .../petstore/android/default/docs/UserApi.md | 354 +++++++++++++++++ .../petstore/android/default/git_push.sh | 4 +- .../client/petstore/android/volley/README.md | 142 +++++++ .../petstore/android/volley/docs/Category.md | 11 + .../petstore/android/volley/docs/Order.md | 21 + .../petstore/android/volley/docs/Pet.md | 21 + .../petstore/android/volley/docs/PetApi.md | 365 ++++++++++++++++++ .../petstore/android/volley/docs/StoreApi.md | 179 +++++++++ .../petstore/android/volley/docs/Tag.md | 11 + .../petstore/android/volley/docs/User.md | 17 + .../petstore/android/volley/docs/UserApi.md | 354 +++++++++++++++++ 24 files changed, 2548 insertions(+), 2 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/android/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/android/api_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/android/model_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/android/pojo_doc.mustache create mode 100644 samples/client/petstore/android/default/README.md create mode 100644 samples/client/petstore/android/default/docs/Category.md create mode 100644 samples/client/petstore/android/default/docs/Order.md create mode 100644 samples/client/petstore/android/default/docs/Pet.md create mode 100644 samples/client/petstore/android/default/docs/PetApi.md create mode 100644 samples/client/petstore/android/default/docs/StoreApi.md create mode 100644 samples/client/petstore/android/default/docs/Tag.md create mode 100644 samples/client/petstore/android/default/docs/User.md create mode 100644 samples/client/petstore/android/default/docs/UserApi.md create mode 100644 samples/client/petstore/android/volley/README.md create mode 100644 samples/client/petstore/android/volley/docs/Category.md create mode 100644 samples/client/petstore/android/volley/docs/Order.md create mode 100644 samples/client/petstore/android/volley/docs/Pet.md create mode 100644 samples/client/petstore/android/volley/docs/PetApi.md create mode 100644 samples/client/petstore/android/volley/docs/StoreApi.md create mode 100644 samples/client/petstore/android/volley/docs/Tag.md create mode 100644 samples/client/petstore/android/volley/docs/User.md create mode 100644 samples/client/petstore/android/volley/docs/UserApi.md 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 324453991e0..0d021eba9f9 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 @@ -3,6 +3,7 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenParameter; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; @@ -32,6 +33,8 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi // requestPackage and authPackage are used by the "volley" template/library protected String requestPackage = "io.swagger.client.request"; protected String authPackage = "io.swagger.client.auth"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; public AndroidClientCodegen() { super(); @@ -123,6 +126,26 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); } + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace( '/', File.separatorChar ); + } + + @Override + public String modelDocFileFolder() { + return ( outputFolder + "/" + modelDocPath ).replace( '/', File.separatorChar ); + } + + @Override + public String toApiDocFilename( String name ) { + return toApiName( name ); + } + + @Override + public String toModelDocFilename( String name ) { + return toModelName( name ); + } + @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { @@ -224,6 +247,70 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi return toModelName(name); } + @Override + public void setParameterExampleValue(CodegenParameter p) { + String example; + + if (p.defaultValue == null) { + example = p.example; + } else { + example = p.defaultValue; + } + + String type = p.baseType; + if (type == null) { + type = p.dataType; + } + + if ("String".equals(type)) { + if (example == null) { + example = p.paramName + "_example"; + } + example = "\"" + escapeText(example) + "\""; + } else if ("Integer".equals(type) || "Short".equals(type)) { + if (example == null) { + example = "56"; + } + } else if ("Long".equals(type)) { + if (example == null) { + example = "56"; + } + example = example + "L"; + } else if ("Float".equals(type)) { + if (example == null) { + example = "3.4"; + } + example = example + "F"; + } else if ("Double".equals(type)) { + example = "3.4"; + example = example + "D"; + } else if ("Boolean".equals(type)) { + if (example == null) { + example = "true"; + } + } else if ("File".equals(type)) { + if (example == null) { + example = "/path/to/file"; + } + example = "new File(\"" + escapeText(example) + "\")"; + } else if ("Date".equals(type)) { + example = "new Date()"; + } else if (!languageSpecificPrimitives.contains(type)) { + // type is a model class, e.g. User + example = "new " + type + "()"; + } + + if (example == null) { + example = "null"; + } else if (Boolean.TRUE.equals(p.isListContainer)) { + example = "Arrays.asList(" + example + ")"; + } else if (Boolean.TRUE.equals(p.isMapContainer)) { + example = "new HashMap()"; + } + + p.example = example; + } + @Override public String toOperationId(String operationId) { // throw exception if method name is empty @@ -290,9 +377,23 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi this.setLibrary((String) additionalProperties.get(CodegenConstants.LIBRARY)); } + //make api and model doc path available in mustache template + additionalProperties.put( "apiDocPath", apiDocPath ); + additionalProperties.put( "modelDocPath", modelDocPath ); + if (StringUtils.isEmpty(getLibrary())) { + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); + //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); addSupportingFilesForDefault(); } else if ("volley".equals(getLibrary())) { + modelDocTemplateFiles.put( "model_doc.mustache", ".md" ); + apiDocTemplateFiles.put( "api_doc.mustache", ".md" ); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + //supportingFiles.add(new SupportingFile("api_doc.mustache", apiDocPath, "api.md")); + //supportingFiles.add(new SupportingFile("model_doc.mustache", modelDocPath, "model.md")); addSupportingFilesForVolley(); } } diff --git a/modules/swagger-codegen/src/main/resources/android/README.mustache b/modules/swagger-codegen/src/main/resources/android/README.mustache new file mode 100644 index 00000000000..8091b0adb06 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/README.mustache @@ -0,0 +1,125 @@ +# {{artifactId}} + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/{{{artifactId}}}-{{{artifactVersion}}}.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +import {{{package}}}.{{{classname}}}; + +public class {{{classname}}}Example { + + public static void main(String[] args) { + {{{classname}}} apiInstance = new {{{classname}}}(); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + e.printStackTrace(); + } + } +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +## Documentation for Authorization + +{{^authMethods}}All endpoints do not require authorization. +{{/authMethods}}Authentication schemes defined for the API: +{{#authMethods}}### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorizatoin URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/android/api_doc.mustache b/modules/swagger-codegen/src/main/resources/android/api_doc.mustache new file mode 100644 index 00000000000..2fdcab749ab --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/api_doc.mustache @@ -0,0 +1,60 @@ +# {{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}** +> {{#returnType}}{{returnType}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + +{{summary}}{{#notes}} + +{{notes}}{{/notes}} + +### Example +```java +// Import classes: +//import {{{package}}}.{{{classname}}}; + +{{{classname}}} apiInstance = new {{{classname}}}(); +{{#allParams}} +{{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} +{{/allParams}} +try { + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{#hasMore}}, {{/hasMore}}{{/allParams}});{{#returnType}} + System.out.println(result);{{/returnType}} +} catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + e.printStackTrace(); +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{#defaultValue}} [default to {{defaultValue}}]{{/defaultValue}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/android/model_doc.mustache b/modules/swagger-codegen/src/main/resources/android/model_doc.mustache new file mode 100644 index 00000000000..658df8d5322 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/model_doc.mustache @@ -0,0 +1,3 @@ +{{#models}}{{#model}} +{{#isEnum}}{{>enum_outer_doc}}{{/isEnum}}{{^isEnum}}{{>pojo_doc}}{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/android/pojo_doc.mustache b/modules/swagger-codegen/src/main/resources/android/pojo_doc.mustache new file mode 100644 index 00000000000..0e4c0749866 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android/pojo_doc.mustache @@ -0,0 +1,15 @@ +# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isPrimitiveType}}**{{datatype}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{datatype}}**]({{complexType}}.md){{/isPrimitiveType}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#readOnly}} [readonly]{{/readOnly}} +{{/vars}} +{{#vars}}{{#isEnum}} + + +## Enum: {{datatypeWithEnum}} +Name | Value +---- | -----{{#allowableValues}}{{#enumVars}} +{{name}} | {{value}}{{/enumVars}}{{/allowableValues}} +{{/isEnum}}{{/vars}} diff --git a/samples/client/petstore/android/default/README.md b/samples/client/petstore/android/default/README.md new file mode 100644 index 00000000000..a1c37674b81 --- /dev/null +++ b/samples/client/petstore/android/default/README.md @@ -0,0 +1,142 @@ +# swagger-android-client + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + io.swagger + swagger-android-client + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-android-client:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-android-client-1.0.0.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import io.swagger.client.api.PetApi; + +public class PetApiExample { + + public static void main(String[] args) { + PetApi apiInstance = new PetApi(); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Category](docs/Category.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@wordnik.com + diff --git a/samples/client/petstore/android/default/docs/Category.md b/samples/client/petstore/android/default/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/android/default/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/android/default/docs/Order.md b/samples/client/petstore/android/default/docs/Order.md new file mode 100644 index 00000000000..5746ce97fad --- /dev/null +++ b/samples/client/petstore/android/default/docs/Order.md @@ -0,0 +1,21 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**Date**](Date.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/android/default/docs/Pet.md b/samples/client/petstore/android/default/docs/Pet.md new file mode 100644 index 00000000000..a4daa24feb6 --- /dev/null +++ b/samples/client/petstore/android/default/docs/Pet.md @@ -0,0 +1,21 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/android/default/docs/PetApi.md b/samples/client/petstore/android/default/docs/PetApi.md new file mode 100644 index 00000000000..f8ba698c05a --- /dev/null +++ b/samples/client/petstore/android/default/docs/PetApi.md @@ -0,0 +1,365 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma seperated strings + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("available"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | [optional] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be fetched +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +String petId = "petId_example"; // String | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **String**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + + +# **uploadFile** +> uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + apiInstance.uploadFile(petId, additionalMetadata, file); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/android/default/docs/StoreApi.md b/samples/client/petstore/android/default/docs/StoreApi.md new file mode 100644 index 00000000000..5d35bca0202 --- /dev/null +++ b/samples/client/petstore/android/default/docs/StoreApi.md @@ -0,0 +1,179 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/android/default/docs/Tag.md b/samples/client/petstore/android/default/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/android/default/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/android/default/docs/User.md b/samples/client/petstore/android/default/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/android/default/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/android/default/docs/UserApi.md b/samples/client/petstore/android/default/docs/UserApi.md new file mode 100644 index 00000000000..f87e8f58827 --- /dev/null +++ b/samples/client/petstore/android/default/docs/UserApi.md @@ -0,0 +1,354 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | [optional] + **password** | **String**| The password for login in clear text | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/android/default/git_push.sh b/samples/client/petstore/android/default/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/android/default/git_push.sh +++ b/samples/client/petstore/android/default/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi diff --git a/samples/client/petstore/android/volley/README.md b/samples/client/petstore/android/volley/README.md new file mode 100644 index 00000000000..6f0a2c65f92 --- /dev/null +++ b/samples/client/petstore/android/volley/README.md @@ -0,0 +1,142 @@ +# swagger-petstore-android-volley + +## Requirements + +Building the API client library requires [Maven](https://maven.apache.org/) to be installed. + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn deploy +``` + +Refer to the [official documentation](https://maven.apache.org/plugins/maven-deploy-plugin/usage.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + io.swagger + swagger-petstore-android-volley + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "io.swagger:swagger-petstore-android-volley:1.0.0" +``` + +### Others + +At first generate the JAR by executing: + + mvn package + +Then manually install the following JARs: + +* target/swagger-petstore-android-volley-1.0.0.jar +* target/lib/*.jar + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import io.swagger.client.api.PetApi; + +public class PetApiExample { + + public static void main(String[] args) { + PetApi apiInstance = new PetApi(); + Pet body = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(body); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [Category](docs/Category.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorizatoin URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issue. + +## Author + +apiteam@wordnik.com + diff --git a/samples/client/petstore/android/volley/docs/Category.md b/samples/client/petstore/android/volley/docs/Category.md new file mode 100644 index 00000000000..e2df0803278 --- /dev/null +++ b/samples/client/petstore/android/volley/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/android/volley/docs/Order.md b/samples/client/petstore/android/volley/docs/Order.md new file mode 100644 index 00000000000..5746ce97fad --- /dev/null +++ b/samples/client/petstore/android/volley/docs/Order.md @@ -0,0 +1,21 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | [**Date**](Date.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/android/volley/docs/Pet.md b/samples/client/petstore/android/volley/docs/Pet.md new file mode 100644 index 00000000000..a4daa24feb6 --- /dev/null +++ b/samples/client/petstore/android/volley/docs/Pet.md @@ -0,0 +1,21 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum +Name | Value +---- | ----- + + + diff --git a/samples/client/petstore/android/volley/docs/PetApi.md b/samples/client/petstore/android/volley/docs/PetApi.md new file mode 100644 index 00000000000..f8ba698c05a --- /dev/null +++ b/samples/client/petstore/android/volley/docs/PetApi.md @@ -0,0 +1,365 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | Pet id to delete +String apiKey = "apiKey_example"; // String | +try { + apiInstance.deletePet(petId, apiKey); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma seperated strings + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +List status = Arrays.asList("available"); // List | Status values that need to be considered for filter +try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [optional] [default to available] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +List tags = Arrays.asList("tags_example"); // List | Tags to filter by +try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | [optional] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet that needs to be fetched +try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updatePet** +> updatePet(body) + +Update an existing pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Pet body = new Pet(); // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/json, application/xml + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +String petId = "petId_example"; // String | ID of pet that needs to be updated +String name = "name_example"; // String | Updated name of the pet +String status = "status_example"; // String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **String**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: application/json, application/xml + + +# **uploadFile** +> uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.PetApi; + +PetApi apiInstance = new PetApi(); +Long petId = 789L; // Long | ID of pet to update +String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server +File file = new File("/path/to/file.txt"); // File | file to upload +try { + apiInstance.uploadFile(petId, additionalMetadata, file); +} catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/android/volley/docs/StoreApi.md b/samples/client/petstore/android/volley/docs/StoreApi.md new file mode 100644 index 00000000000..5d35bca0202 --- /dev/null +++ b/samples/client/petstore/android/volley/docs/StoreApi.md @@ -0,0 +1,179 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +try { + Map result = apiInstance.getInventory(); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**Map<String, Integer>**](Map.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +String orderId = "orderId_example"; // String | ID of pet that needs to be fetched +try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.StoreApi; + +StoreApi apiInstance = new StoreApi(); +Order body = new Order(); // Order | order placed for purchasing the pet +try { + Order result = apiInstance.placeOrder(body); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | [optional] + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + diff --git a/samples/client/petstore/android/volley/docs/Tag.md b/samples/client/petstore/android/volley/docs/Tag.md new file mode 100644 index 00000000000..de6814b55d5 --- /dev/null +++ b/samples/client/petstore/android/volley/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/android/volley/docs/User.md b/samples/client/petstore/android/volley/docs/User.md new file mode 100644 index 00000000000..8b6753dd284 --- /dev/null +++ b/samples/client/petstore/android/volley/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] + + + diff --git a/samples/client/petstore/android/volley/docs/UserApi.md b/samples/client/petstore/android/volley/docs/UserApi.md new file mode 100644 index 00000000000..f87e8f58827 --- /dev/null +++ b/samples/client/petstore/android/volley/docs/UserApi.md @@ -0,0 +1,354 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +User body = new User(); // User | Created user object +try { + apiInstance.createUser(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithArrayInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +List body = Arrays.asList(new User()); // List | List of user object +try { + apiInstance.createUsersWithListInput(body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**List<User>**](User.md)| List of user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be deleted +try { + apiInstance.deleteUser(username); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. +try { + User result = apiInstance.getUserByName(username); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | The user name for login +String password = "password_example"; // String | The password for login in clear text +try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | [optional] + **password** | **String**| The password for login in clear text | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +try { + apiInstance.logoutUser(); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + e.printStackTrace(); +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +//import io.swagger.client.api.UserApi; + +UserApi apiInstance = new UserApi(); +String username = "username_example"; // String | name that need to be deleted +User body = new User(); // User | Updated user object +try { + apiInstance.updateUser(username, body); +} catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + e.printStackTrace(); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | [optional] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json, application/xml + From a71d8d935aa52d1507298af850a1d2b013870f63 Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Sat, 7 May 2016 11:44:51 +0200 Subject: [PATCH 15/27] Use AFHttpSessionManager instead of AFHTTPRequestOperationManager #1981 --- .../resources/objc/ApiClient-body.mustache | 193 +++++++----------- .../resources/objc/ApiClient-header.mustache | 14 +- samples/client/petstore/objc/README.md | 4 +- .../objc/SwaggerClient/SWGApiClient.h | 14 +- .../objc/SwaggerClient/SWGApiClient.m | 193 +++++++----------- samples/client/petstore/objc/git_push.sh | 4 +- 6 files changed, 176 insertions(+), 246 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache index 18b756f78b0..e87a0a414fa 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-body.mustache @@ -14,6 +14,30 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilitySta static void (^reachabilityChangeBlock)(int); +static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) { + if(![response isKindOfClass:[NSHTTPURLResponse class]]) { + return nil; + } + return ((NSHTTPURLResponse*)response).allHeaderFields; +} + +static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + @interface {{classPrefix}}ApiClient () @property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; @@ -99,14 +123,12 @@ static void (^reachabilityChangeBlock)(int); va_end(args); } -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request - error:(NSError*)error { +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - operation.responseString]; + responseObject]; {{classPrefix}}DebugLog(message); } @@ -222,20 +244,14 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if ([obj intValue] == [requestId intValue]) { - return YES; - } - else { - return NO; - } + return [obj intValue] == [requestId intValue]; }]; if (matchingItems.count == 1) { {{classPrefix}}DebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; - } - else { + } else { return NO; } } @@ -246,7 +262,7 @@ static void (^reachabilityChangeBlock)(int); return reachabilityStatus; } -+(bool) getOfflineState { ++(BOOL) getOfflineState { return offlineState; } @@ -257,29 +273,8 @@ static void (^reachabilityChangeBlock)(int); - (void) configureCacheReachibility { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; - switch (status) { - case AFNetworkReachabilityStatusUnknown: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); - [{{classPrefix}}ApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusNotReachable: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); - [{{classPrefix}}ApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusReachableViaWWAN: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); - [{{classPrefix}}ApiClient setOfflineState:false]; - break; - - case AFNetworkReachabilityStatusReachableViaWiFi: - {{classPrefix}}DebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); - [{{classPrefix}}ApiClient setOfflineState:false]; - break; - default: - break; - } + {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -443,92 +438,60 @@ static void (^reachabilityChangeBlock)(int); - (void) operationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id response) { - if ([self executeRequestWithId:requestId]) { - [self logResponse:operation forRequest:request error:nil]; - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - completionBlock(response, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - // Add in the (parsed) response body. - userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); + if(!error) { + completionBlock(responseObject, nil); + return; + } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + [op resume]; } - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString * filename = {{classPrefix}}__fileNameForResponse(response); - NSDictionary *headers = operation.response.allHeaderFields; - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; - } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } + [responseObject writeToURL:file atomically:YES]; - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [operation.responseData writeToURL:file atomically:YES]; - self.HTTPResponseHeaders = headers; - completionBlock(file, nil); - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; - } - - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + completionBlock(file, nil); + }]; + [op resume]; } #pragma mark - Perform Request Methods @@ -653,7 +616,7 @@ static void (^reachabilityChangeBlock)(int); [request setHTTPShouldHandleCookies:NO]; NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"]) { + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 1cf3db5e523..59446d6c490 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -1,6 +1,6 @@ #import #import -#import +#import #import "{{classPrefix}}JSONResponseSerializer.h" #import "{{classPrefix}}JSONRequestSerializer.h" #import "{{classPrefix}}QueryParamCollection.h" @@ -40,7 +40,7 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; */ #define {{classPrefix}}DebugLog(format, ...) [{{classPrefix}}ApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -@interface {{classPrefix}}ApiClient : AFHTTPRequestOperationManager +@interface {{classPrefix}}ApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @@ -80,7 +80,7 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; * * @return The client offline state */ -+(bool) getOfflineState; ++(BOOL) getOfflineState; /** * Sets the client reachability, this may be overridden by the reachability manager if reachability changes @@ -188,12 +188,14 @@ extern NSInteger const {{classPrefix}}TypeMismatchErrorCode; /** * Logs request and response * - * @param operation AFHTTPRequestOperation for the HTTP request. + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. * @param request The HTTP request. * @param error The error of the HTTP request. */ -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request +- (void)logResponse:(NSURLResponse *)response + responseObject:(id)responseObject + request:(NSURLRequest *)request error:(NSError *)error; /** diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index bd0f24851a7..70c2c4c5f49 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-04-25T18:52:19.055+02:00 +- Build date: 2016-05-07T11:41:37.858+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -19,7 +19,7 @@ The SDK requires [**ARC (Automatic Reference Counting)**](http://stackoverflow.c Add the following to the Podfile: ```ruby -pod 'SwaggerClient', :git => 'https://github.com/YOUR_GIT_USR_ID/YOUR_GIT_REPO_ID.git' +pod 'SwaggerClient', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' ``` To specify a particular branch, append `, :branch => 'branch-name-here'` diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h index 5d40ef2f5f0..0918e653972 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.h @@ -1,6 +1,6 @@ #import #import -#import +#import #import "SWGJSONResponseSerializer.h" #import "SWGJSONRequestSerializer.h" #import "SWGQueryParamCollection.h" @@ -44,7 +44,7 @@ extern NSInteger const SWGTypeMismatchErrorCode; */ #define SWGDebugLog(format, ...) [SWGApiClient debugLog:[NSString stringWithFormat:@"%s", __PRETTY_FUNCTION__] message: format, ##__VA_ARGS__]; -@interface SWGApiClient : AFHTTPRequestOperationManager +@interface SWGApiClient : AFHTTPSessionManager @property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; @property(nonatomic, assign) NSTimeInterval timeoutInterval; @@ -84,7 +84,7 @@ extern NSInteger const SWGTypeMismatchErrorCode; * * @return The client offline state */ -+(bool) getOfflineState; ++(BOOL) getOfflineState; /** * Sets the client reachability, this may be overridden by the reachability manager if reachability changes @@ -192,12 +192,14 @@ extern NSInteger const SWGTypeMismatchErrorCode; /** * Logs request and response * - * @param operation AFHTTPRequestOperation for the HTTP request. + * @param response NSURLResponse for the HTTP request. + * @param responseObject response object of the HTTP request. * @param request The HTTP request. * @param error The error of the HTTP request. */ -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request +- (void)logResponse:(NSURLResponse *)response + responseObject:(id)responseObject + request:(NSURLRequest *)request error:(NSError *)error; /** diff --git a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m index ecdf4aaafb2..6fd3206c7a3 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGApiClient.m @@ -14,6 +14,30 @@ static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilitySta static void (^reachabilityChangeBlock)(int); +static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { + if(![response isKindOfClass:[NSHTTPURLResponse class]]) { + return nil; + } + return ((NSHTTPURLResponse*)response).allHeaderFields; +} + +static NSString * SWG__fileNameForResponse(NSURLResponse *response) { + NSDictionary * headers = SWG__headerFieldsForResponse(response); + if(!headers[@"Content-Disposition"]) { + return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = headers[@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; +} + + @interface SWGApiClient () @property (readwrite, nonatomic) NSDictionary *HTTPResponseHeaders; @@ -99,14 +123,12 @@ static void (^reachabilityChangeBlock)(int); va_end(args); } -- (void)logResponse:(AFHTTPRequestOperation *)operation - forRequest:(NSURLRequest *)request - error:(NSError*)error { +- (void)logResponse:(NSURLResponse *)response responseObject:(id)responseObject request:(NSURLRequest *)request error:(NSError *)error { NSString *message = [NSString stringWithFormat:@"\n[DEBUG] HTTP request body \n~BEGIN~\n %@\n~END~\n"\ "[DEBUG] HTTP response body \n~BEGIN~\n %@\n~END~\n", [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], - operation.responseString]; + responseObject]; SWGDebugLog(message); } @@ -222,20 +244,14 @@ static void (^reachabilityChangeBlock)(int); -(Boolean) executeRequestWithId:(NSNumber*) requestId { NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if ([obj intValue] == [requestId intValue]) { - return YES; - } - else { - return NO; - } + return [obj intValue] == [requestId intValue]; }]; if (matchingItems.count == 1) { SWGDebugLog(@"removed request id %@", requestId); [queuedRequests removeObject:requestId]; return YES; - } - else { + } else { return NO; } } @@ -246,7 +262,7 @@ static void (^reachabilityChangeBlock)(int); return reachabilityStatus; } -+(bool) getOfflineState { ++(BOOL) getOfflineState { return offlineState; } @@ -257,29 +273,8 @@ static void (^reachabilityChangeBlock)(int); - (void) configureCacheReachibility { [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { reachabilityStatus = status; - switch (status) { - case AFNetworkReachabilityStatusUnknown: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); - [SWGApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusNotReachable: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); - [SWGApiClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusReachableViaWWAN: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); - [SWGApiClient setOfflineState:false]; - break; - - case AFNetworkReachabilityStatusReachableViaWiFi: - SWGDebugLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); - [SWGApiClient setOfflineState:false]; - break; - default: - break; - } + SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); + [SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; // call the reachability block, if configured if (reachabilityChangeBlock != nil) { @@ -443,92 +438,60 @@ static void (^reachabilityChangeBlock)(int); - (void) operationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id response) { - if ([self executeRequestWithId:requestId]) { - [self logResponse:operation forRequest:request error:nil]; - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - completionBlock(response, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - // Add in the (parsed) response body. - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); + if(!error) { + completionBlock(responseObject, nil); + return; + } + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + // Add in the (parsed) response body. + userInfo[SWGResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + }]; + [op resume]; } - (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request requestId: (NSNumber *) requestId completionBlock: (void (^)(id, NSError *))completionBlock { - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - NSString *directory = nil; - if (config.tempFolderPath) { - directory = config.tempFolderPath; - } - else { - directory = NSTemporaryDirectory(); - } + __weak __typeof(self)weakSelf = self; + NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { + __strong __typeof(weakSelf)strongSelf = weakSelf; + if (![strongSelf executeRequestWithId:requestId]) { + return; + } + strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); + [strongSelf logResponse:response responseObject:responseObject request:request error:error]; + if(error) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (responseObject) { + userInfo[SWGResponseObjectErrorKey] = responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + completionBlock(nil, augmentedError); + } + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + NSString *directory = config.tempFolderPath ?: NSTemporaryDirectory(); + NSString * filename = SWG__fileNameForResponse(response); - NSDictionary *headers = operation.response.allHeaderFields; - NSString *filename = nil; - if ([headers objectForKey:@"Content-Disposition"]) { + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; - NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; - filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; - } - else { - filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; - } + [responseObject writeToURL:file atomically:YES]; - NSString *filepath = [directory stringByAppendingPathComponent:filename]; - NSURL *file = [NSURL fileURLWithPath:filepath]; - - [operation.responseData writeToURL:file atomically:YES]; - self.HTTPResponseHeaders = headers; - completionBlock(file, nil); - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - - if ([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if (operation.responseObject) { - userInfo[SWGResponseObjectErrorKey] = operation.responseObject; - } - - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - - [self logResponse:nil forRequest:request error:augmentedError]; - - NSDictionary *responseHeaders = [[operation response] allHeaderFields]; - self.HTTPResponseHeaders = responseHeaders; - completionBlock(nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; + completionBlock(file, nil); + }]; + [op resume]; } #pragma mark - Perform Request Methods @@ -653,7 +616,7 @@ static void (^reachabilityChangeBlock)(int); [request setHTTPShouldHandleCookies:NO]; NSNumber* requestId = [SWGApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"]) { + if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; diff --git a/samples/client/petstore/objc/git_push.sh b/samples/client/petstore/objc/git_push.sh index 1a36388db02..ed374619b13 100644 --- a/samples/client/petstore/objc/git_push.sh +++ b/samples/client/petstore/objc/git_push.sh @@ -8,12 +8,12 @@ git_repo_id=$2 release_note=$3 if [ "$git_user_id" = "" ]; then - git_user_id="YOUR_GIT_USR_ID" + git_user_id="GIT_USER_ID" echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" fi if [ "$git_repo_id" = "" ]; then - git_repo_id="YOUR_GIT_REPO_ID" + git_repo_id="GIT_REPO_ID" echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" fi From 6709a92cbcedbb4e05e87a846a232fc36e954745 Mon Sep 17 00:00:00 2001 From: zhenjun115 Date: Sat, 7 May 2016 23:38:05 +0800 Subject: [PATCH 16/27] remove pom.mustache from android api client using volley HTTP library; --- .../languages/AndroidClientCodegen.java | 2 +- .../android/libraries/volley/pom.mustache | 48 ------------------- .../client/petstore/android/volley/pom.xml | 48 ------------------- 3 files changed, 1 insertion(+), 97 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache delete mode 100644 samples/client/petstore/android/volley/pom.xml 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 0d021eba9f9..b5978e118a0 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 @@ -418,7 +418,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi } private void addSupportingFilesForVolley() { - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + // supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); // supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); diff --git a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache b/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache deleted file mode 100644 index 09f55a743a7..00000000000 --- a/modules/swagger-codegen/src/main/resources/android/libraries/volley/pom.mustache +++ /dev/null @@ -1,48 +0,0 @@ - - - 4.0.0 - io.swagger - volley - 1.0.0 - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - compile - - - org.apache.httpcomponents - httpcore - ${httpcomponents-httpcore-version} - compile - - - org.apache.httpcomponents - httpmime - ${httpcomponents-httpmime-version} - compile - - - com.google.code.gson - gson - ${google-code-gson-version} - compile - - - com.mcxiaoke.volley - library - ${volley-library-version} - aar - compile - - - - 1.5.0 - 4.4.4 - 4.5.2 - 2.3.1 - 1.0.19 - - diff --git a/samples/client/petstore/android/volley/pom.xml b/samples/client/petstore/android/volley/pom.xml deleted file mode 100644 index 09f55a743a7..00000000000 --- a/samples/client/petstore/android/volley/pom.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - 4.0.0 - io.swagger - volley - 1.0.0 - - - io.swagger - swagger-annotations - ${swagger-annotations-version} - compile - - - org.apache.httpcomponents - httpcore - ${httpcomponents-httpcore-version} - compile - - - org.apache.httpcomponents - httpmime - ${httpcomponents-httpmime-version} - compile - - - com.google.code.gson - gson - ${google-code-gson-version} - compile - - - com.mcxiaoke.volley - library - ${volley-library-version} - aar - compile - - - - 1.5.0 - 4.4.4 - 4.5.2 - 2.3.1 - 1.0.19 - - From 46957bb6aa2bda0f1efaabb827736db8394eb1d9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 8 May 2016 18:48:22 +0800 Subject: [PATCH 17/27] add swagger codegen core team --- README.md | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/README.md b/README.md index 8eca8ecd53e..d5ea495c8a0 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Online Generators](#online-generators) - [Guidelines for Contribution](https://github.com/swagger-api/swagger-codegen/wiki/Guidelines-for-Contribution) - [Companies/Projects using Swagger Codegen](#companiesprojects-using-swagger-codegen) + - [Swagger Codegen Core Team](#swagger-codegen-core-team) - [License](#license) @@ -794,6 +795,77 @@ Here are some companies/projects using Swagger Codegen in production. To add you - [Zalando](https://tech.zalando.com) - [ZEEF.com](https://zeef.com/) +# Swagger Codegen Core Team + +Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. To join the core team, please reach out to wing328hk@gmail.com for more information. + +## API Clients +| Langauges | Core Team (join date) | +|:-------------|:-------------| +| ActionScript | | +| C++ | | +| C# | @jimschubert (2016/05/01) | | +| Clojure | | +| Dart | | +| Groovy | | +| Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | +| Java | @cbornet (2016/05/01) @xhh (2016/05/01) | +| NodeJS/Javascript | | +| ObjC | | +| Perl | @wing328 (2016/05/01) | +| PHP | @arnested (2016/05/01) | +| Python | @scottrw93 (2016/05/01) | +| Ruby | | | +| Scala | | | +| Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | +| TypeScript (Node) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | +| TypeScript (Angular1) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | +| TypeScript (Fetch) | | +| TypeScript (Angular2) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | +## Server Stubs +| Langauges | Core Team (date joined) | +|:------------- |:-------------| +| C# ASP.NET5 | @jimschubert (2016/05/01) | +| Haskell Servant | | +| Java Spring Boot | | +| Java SpringMVC | | +| Java JAX-RS | | +| NodeJS | | +| PHP Lumen | @abcsum (2016/05/01) | +| PHP Silex | | +| PHP Slim | | +| Python Flask | | +| Ruby Sinatra | | | +| Scala Scalatra | | | + +## Template Creator +Here is a list of template creators: + * API Clients: + * Clojure: @xhh + * Dart: @yissachar + * Groovy: @victorgit + * Go: @wing328 + * Java (Retrofit): @0legg + * Java (Retrofi2): @emilianobonassi + * Java (Jersey2): @xhh + * Java (okhttp-gson): @xhh + * Javascript/NodeJS: @jfiala + * Javascript (Closure-annotated Angular) @achew22 + * Perl: @wing328 + * Swift: @tkqubo + * TypeScript (Node): @mhardorf + * TypeScript (Angular1): @mhardorf + * TypeScript (Fetch): @leonyu + * TypeScript (Angular2): @roni-frantchi + * Server Stubs + * C# ASP.NET5: @jimschubert + * Haskell Servant: @algas + * Java Spring Boot: @diyfr + * JAX-RS RestEasy: @chameleon82 + * JAX-RS CXF: @hiveship + * PHP Lumen: @abcsum + * PHP Slim: @jfastnacht + License ------- From fbd6a957990a2d3b940617bffaf1013456d99fac Mon Sep 17 00:00:00 2001 From: Mateusz Mackowiak Date: Sun, 8 May 2016 12:54:12 +0200 Subject: [PATCH 18/27] [Objc] Generator supports binary and BiteArray and maps data to NSData --- .../codegen/languages/ObjcClientCodegen.java | 17 +++++++++++------ .../objc/ResponseDeserializer-body.mustache | 2 +- samples/client/petstore/objc/README.md | 2 +- .../SwaggerClient/SWGResponseDeserializer.m | 2 +- 4 files changed, 14 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 0ecdfb667c9..713ee4286a7 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -28,6 +28,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public static final String AUTHOR_EMAIL = "authorEmail"; public static final String GIT_REPO_URL = "gitRepoURL"; public static final String LICENSE = "license"; + + public static final String BinaryDataType = "ObjcClientCodegenBinaryData"; + protected Set foundationClasses = new HashSet(); protected String podName = "SwaggerClient"; protected String podVersion = "1.0.0"; @@ -65,6 +68,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { defaultIncludes.add("NSDictionary"); defaultIncludes.add("NSMutableArray"); defaultIncludes.add("NSMutableDictionary"); + + defaultIncludes.add(BinaryDataType); languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("NSNumber"); @@ -92,10 +97,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); typeMapping.put("file", "NSURL"); - //TODO binary should be mapped to byte array - // mapped to String as a workaround - typeMapping.put("binary", "NSString"); - typeMapping.put("ByteArray", "NSString"); + typeMapping.put("binary", BinaryDataType); + typeMapping.put("ByteArray", BinaryDataType); // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm setReservedWordsLowerCase( @@ -280,11 +283,13 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { String innerType = getSwaggerType(inner); String innerTypeDeclaration = getTypeDeclaration(inner); - if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - + + if(innerTypeDeclaration.equalsIgnoreCase(BinaryDataType)) { + return "NSData*"; + } // In this codition, type of property p is array of primitive, // return container type with pointer, e.g. `NSArray* /* NSString */' if (languageSpecificPrimitives.contains(innerType)) { diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache index 27a59e39cdc..812ed061c04 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache @@ -33,7 +33,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; formatter.numberStyle = NSNumberFormatterDecimalStyle; _numberFormatter = formatter; _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - _basicReturnTypes = @[@"NSObject", @"id"]; + _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" options:NSRegularExpressionCaseInsensitive error:nil]; diff --git a/samples/client/petstore/objc/README.md b/samples/client/petstore/objc/README.md index a3550545c24..f4b3f2f2f76 100644 --- a/samples/client/petstore/objc/README.md +++ b/samples/client/petstore/objc/README.md @@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build date: 2016-05-06T12:20:47.112+02:00 +- Build date: 2016-05-08T12:06:01.121+02:00 - Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements diff --git a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m b/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m index fa5be3af3d2..a0efd1d5927 100644 --- a/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/SwaggerClient/SWGResponseDeserializer.m @@ -33,7 +33,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; formatter.numberStyle = NSNumberFormatterDecimalStyle; _numberFormatter = formatter; _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - _basicReturnTypes = @[@"NSObject", @"id"]; + _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" options:NSRegularExpressionCaseInsensitive error:nil]; From dcbc8975a083e7d7ea164c054056cc7e3d9f845b Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 8 May 2016 22:24:52 +0800 Subject: [PATCH 19/27] update core team --- README.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index d5ea495c8a0..4102aca5363 100644 --- a/README.md +++ b/README.md @@ -805,7 +805,7 @@ Swaagger Codegen core team members are contributors who have been making signfic | ActionScript | | | C++ | | | C# | @jimschubert (2016/05/01) | | -| Clojure | | +| Clojure | @xhh (2016/05/01) | | Dart | | | Groovy | | | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | @@ -815,8 +815,8 @@ Swaagger Codegen core team members are contributors who have been making signfic | Perl | @wing328 (2016/05/01) | | PHP | @arnested (2016/05/01) | | Python | @scottrw93 (2016/05/01) | -| Ruby | | | -| Scala | | | +| Ruby | @wing328 (2016/05/01) | +| Scala | | | Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | | TypeScript (Node) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | | TypeScript (Angular1) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | @@ -828,14 +828,14 @@ Swaagger Codegen core team members are contributors who have been making signfic | C# ASP.NET5 | @jimschubert (2016/05/01) | | Haskell Servant | | | Java Spring Boot | | -| Java SpringMVC | | +| Java SpringMVC | @kolyjjj (2016/05/01) | | Java JAX-RS | | -| NodeJS | | +| NodeJS | @kolyjjj (2016/05/01) | | PHP Lumen | @abcsum (2016/05/01) | | PHP Silex | | | PHP Slim | | | Python Flask | | -| Ruby Sinatra | | | +| Ruby Sinatra | @wing328 (2016/05/01) | | | Scala Scalatra | | | ## Template Creator From d4383ce4c11ff02c375bfe5280ff8663a093e5ac Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 8 May 2016 22:33:52 +0800 Subject: [PATCH 20/27] update core team (js) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4102aca5363..bdd62248628 100644 --- a/README.md +++ b/README.md @@ -810,7 +810,7 @@ Swaagger Codegen core team members are contributors who have been making signfic | Groovy | | | Go | @guohuang (2016/05/01) @neilotoole (2016/05/01) | | Java | @cbornet (2016/05/01) @xhh (2016/05/01) | -| NodeJS/Javascript | | +| NodeJS/Javascript | @xhh (2016/05/01) | | ObjC | | | Perl | @wing328 (2016/05/01) | | PHP | @arnested (2016/05/01) | From 6b6a559aa521b9611ae40525c4f70b8fd806e757 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 8 May 2016 23:24:14 +0800 Subject: [PATCH 21/27] add .net2.0 template creator --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index bdd62248628..277bb8e9c0c 100644 --- a/README.md +++ b/README.md @@ -841,6 +841,7 @@ Swaagger Codegen core team members are contributors who have been making signfic ## Template Creator Here is a list of template creators: * API Clients: + * C# (.NET 2.0): @who * Clojure: @xhh * Dart: @yissachar * Groovy: @victorgit From 20f3850eb2a1db33d27035e61d693581dde6c454 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 9 May 2016 00:30:55 +0800 Subject: [PATCH 22/27] add guideline for becoming a core team member --- README.md | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 277bb8e9c0c..9a35eb24ef6 100644 --- a/README.md +++ b/README.md @@ -797,7 +797,7 @@ Here are some companies/projects using Swagger Codegen in production. To add you # Swagger Codegen Core Team -Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. To join the core team, please reach out to wing328hk@gmail.com for more information. +Swaagger Codegen core team members are contributors who have been making signficiant contributions (review issues, fix bugs, make enhancements, etc) to the project on a regular basis. ## API Clients | Langauges | Core Team (join date) | @@ -867,6 +867,19 @@ Here is a list of template creators: * PHP Lumen: @abcsum * PHP Slim: @jfastnacht +## How to join the core team + +Here are the requirements to become a core team member: +- rank within top 50 in https://github.com/swagger-api/swagger-codegen/graphs/contributors + - to contribute, here are some good [starting points](https://github.com/swagger-api/swagger-codegen/issues?q=is%3Aopen+is%3Aissue+label%3A%22Need+community+contribution%22) +- regular contributions to the project + - about 3 hours per week + - for contribution, it can be addressing issues, reviewing PRs submitted by others, submitting PR to fix bugs or make enhancements, etc + + To join the core team, please reach out to wing328hk@gmail.com (@wing328) for more information. + + To become a Template Creator, simply submit a PR for new API client (e.g. Rust, Elixir) or server stub (e.g. Ruby Grape) generator. + License ------- From cfa2c54c15567733e52ecfeaf43a0dcf553c88b3 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 9 May 2016 00:45:29 +0800 Subject: [PATCH 23/27] removed kristof --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9a35eb24ef6..bbc611421ca 100644 --- a/README.md +++ b/README.md @@ -818,10 +818,10 @@ Swaagger Codegen core team members are contributors who have been making signfic | Ruby | @wing328 (2016/05/01) | | Scala | | | Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | -| TypeScript (Node) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | -| TypeScript (Angular1) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | +| TypeScript (Node) | @Vrolijkx (2016/05/01) | +| TypeScript (Angular1) | @Vrolijkx (2016/05/01) | | TypeScript (Fetch) | | -| TypeScript (Angular2) | @kristof (2016/05/01) @Vrolijkx (2016/05/01) | +| TypeScript (Angular2) | @Vrolijkx (2016/05/01) | ## Server Stubs | Langauges | Core Team (date joined) | |:------------- |:-------------| From 9e8cbae0ecb14dea0bf11a49fe2174889388fe46 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 9 May 2016 00:46:17 +0800 Subject: [PATCH 24/27] rearrange order for core member list --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index bbc611421ca..541fd2d466d 100644 --- a/README.md +++ b/README.md @@ -820,8 +820,8 @@ Swaagger Codegen core team members are contributors who have been making signfic | Swift | @jaz-ah (2016/05/01) @Edubits (2016/05/01) | | TypeScript (Node) | @Vrolijkx (2016/05/01) | | TypeScript (Angular1) | @Vrolijkx (2016/05/01) | -| TypeScript (Fetch) | | | TypeScript (Angular2) | @Vrolijkx (2016/05/01) | +| TypeScript (Fetch) | | ## Server Stubs | Langauges | Core Team (date joined) | |:------------- |:-------------| From 25ebd5466de888fa2ac49873466b30792c9f70e9 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 9 May 2016 01:11:29 +0100 Subject: [PATCH 25/27] Update pattern to support Perl /pattern/modifiers convention --- .../languages/PythonClientCodegen.java | 56 +++++++++++++++++++ .../src/main/resources/python/api.mustache | 2 +- .../src/main/resources/python/model.mustache | 2 +- samples/client/petstore/python/README.md | 2 +- .../python/swagger_client/apis/fake_api.py | 4 +- .../swagger_client/models/format_test.py | 2 +- 6 files changed, 62 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index 1bc95cfdd67..e4bf48e9d5b 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -3,15 +3,21 @@ package io.swagger.codegen.languages; import io.swagger.codegen.CliOption; import io.swagger.codegen.CodegenConfig; import io.swagger.codegen.CodegenConstants; +import io.swagger.codegen.CodegenModel; import io.swagger.codegen.CodegenParameter; +import io.swagger.codegen.CodegenProperty; import io.swagger.codegen.CodegenType; import io.swagger.codegen.DefaultCodegen; import io.swagger.codegen.SupportingFile; import io.swagger.models.properties.*; import java.io.File; +import java.util.ArrayList; import java.util.Arrays; +import java.util.HashMap; import java.util.HashSet; +import java.util.List; +import java.util.Map; import org.apache.commons.lang.StringUtils; @@ -21,6 +27,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; + protected Map regexModifiers; + private String testFolder; public PythonClientCodegen() { @@ -87,6 +95,14 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig "assert", "else", "if", "pass", "yield", "break", "except", "import", "print", "class", "exec", "in", "raise", "continue", "finally", "is", "return", "def", "for", "lambda", "try", "self")); + + regexModifiers = new HashMap(); + regexModifiers.put('i', "IGNORECASE"); + regexModifiers.put('l', "LOCALE"); + regexModifiers.put('m', "MULTILINE"); + regexModifiers.put('s', "DOTALL"); + regexModifiers.put('u', "UNICODE"); + regexModifiers.put('x', "VERBOSE"); cliOptions.clear(); cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "python package name (convention: snake_case).") @@ -143,6 +159,46 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig private static String dropDots(String str) { return str.replaceAll("\\.", "_"); } + + @Override + public void postProcessParameter(CodegenParameter parameter){ + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + } + + /* + * The swagger pattern spec follows the Perl convention and style of modifiers. Python + * does not support this in as natural a way so it needs to convert it. See + * https://docs.python.org/2/howto/regex.html#compilation-flags for details. + */ + public void postProcessPattern(String pattern, Map vendorExtensions){ + if(pattern != null) { + int i = pattern.lastIndexOf('/'); + + //Must follow Perl /pattern/modifiers convention + if(pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. "+pattern+" is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\'"); + List modifiers = new ArrayList(); + + for(char c : pattern.substring(i).toCharArray()) { + if(regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } @Override public CodegenType getTag() { diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 399c7f58451..94458e3f724 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -116,7 +116,7 @@ class {{classname}}(object): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - if '{{paramName}}' in params and not re.match('{{pattern}}', params['{{paramName}}']): + if '{{paramName}}' in params and not re.search('{{vendorExtensions.x-regex}}', params['{{paramName}}']{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for parameter `{{paramName}}` when calling `{{operationId}}`, must conform to the pattern `{{pattern}}`") {{/pattern}} {{/hasValidation}} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 0cb98a57ef0..e62fa2cbf66 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -103,7 +103,7 @@ class {{classname}}(object): raise ValueError("Invalid value for `{{name}}`, must be a value greater than or equal to `{{minimum}}`") {{/minimum}} {{#pattern}} - if not re.match('{{pattern}}', {{name}}): + if not re.search('{{vendorExtensions.x-regex}}', {{name}}{{#vendorExtensions.x-modifiers}}{{#-first}}, flags={{/-first}}re.{{.}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}): raise ValueError("Invalid value for `{{name}}`, must be a follow pattern or equal to `{{pattern}}`") {{/pattern}} {{/hasValidation}} diff --git a/samples/client/petstore/python/README.md b/samples/client/petstore/python/README.md index 990d5e53651..3cdf5029787 100644 --- a/samples/client/petstore/python/README.md +++ b/samples/client/petstore/python/README.md @@ -5,7 +5,7 @@ This Python package is automatically generated by the [Swagger Codegen](https:// - API version: 1.0.0 - Package version: 1.0.0 -- Build date: 2016-05-06T22:43:12.044+01:00 +- Build date: 2016-05-09T01:08:25.311+01:00 - Build package: class io.swagger.codegen.languages.PythonClientCodegen ## Requirements. diff --git a/samples/client/petstore/python/swagger_client/apis/fake_api.py b/samples/client/petstore/python/swagger_client/apis/fake_api.py index ba79874f6c7..5d3903b2d21 100644 --- a/samples/client/petstore/python/swagger_client/apis/fake_api.py +++ b/samples/client/petstore/python/swagger_client/apis/fake_api.py @@ -112,8 +112,8 @@ class FakeApi(object): raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value less than or equal to `123.4`") if 'double' in params and params['double'] < 67.8: raise ValueError("Invalid value for parameter `double` when calling `test_endpoint_parameters`, must be a value greater than or equal to `67.8`") - if 'string' in params and not re.match('[a-z]+', params['string']): - raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `[a-z]+`") + if 'string' in params and not re.search('[a-z]', params['string'], flags=re.IGNORECASE): + raise ValueError("Invalid value for parameter `string` when calling `test_endpoint_parameters`, must conform to the pattern `/[a-z]/i`") if 'integer' in params and params['integer'] > 100.0: raise ValueError("Invalid value for parameter `integer` when calling `test_endpoint_parameters`, must be a value less than or equal to `100.0`") if 'integer' in params and params['integer'] < 10.0: diff --git a/samples/client/petstore/python/swagger_client/models/format_test.py b/samples/client/petstore/python/swagger_client/models/format_test.py index eee1b5c9ef7..7fce3351dd4 100644 --- a/samples/client/petstore/python/swagger_client/models/format_test.py +++ b/samples/client/petstore/python/swagger_client/models/format_test.py @@ -279,7 +279,7 @@ class FormatTest(object): if not string: raise ValueError("Invalid value for `string`, must not be `None`") - if not re.match('/[a-z]/i', string): + if not re.search('[a-z]', string, flags=re.IGNORECASE): raise ValueError("Invalid value for `string`, must be a follow pattern or equal to `/[a-z]/i`") self._string = string From 4718c34984cc5a8915f8bf6db41ebd98fd001815 Mon Sep 17 00:00:00 2001 From: Scott Williams Date: Mon, 9 May 2016 01:25:13 +0100 Subject: [PATCH 26/27] Replace tabs with spaces --- .../languages/PythonClientCodegen.java | 54 +++++++++---------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java index e4bf48e9d5b..c1e34b981bb 100755 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/PythonClientCodegen.java @@ -162,42 +162,42 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public void postProcessParameter(CodegenParameter parameter){ - postProcessPattern(parameter.pattern, parameter.vendorExtensions); + postProcessPattern(parameter.pattern, parameter.vendorExtensions); } - + @Override public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { - postProcessPattern(property.pattern, property.vendorExtensions); + postProcessPattern(property.pattern, property.vendorExtensions); } - /* - * The swagger pattern spec follows the Perl convention and style of modifiers. Python - * does not support this in as natural a way so it needs to convert it. See - * https://docs.python.org/2/howto/regex.html#compilation-flags for details. - */ + /* + * The swagger pattern spec follows the Perl convention and style of modifiers. Python + * does not support this in as natural a way so it needs to convert it. See + * https://docs.python.org/2/howto/regex.html#compilation-flags for details. + */ public void postProcessPattern(String pattern, Map vendorExtensions){ - if(pattern != null) { - int i = pattern.lastIndexOf('/'); - - //Must follow Perl /pattern/modifiers convention - if(pattern.charAt(0) != '/' || i < 2) { - throw new IllegalArgumentException("Pattern must follow the Perl " - + "/pattern/modifiers convention. "+pattern+" is not valid."); - } + if(pattern != null) { + int i = pattern.lastIndexOf('/'); - String regex = pattern.substring(1, i).replace("'", "\'"); - List modifiers = new ArrayList(); + //Must follow Perl /pattern/modifiers convention + if(pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. "+pattern+" is not valid."); + } - for(char c : pattern.substring(i).toCharArray()) { - if(regexModifiers.containsKey(c)) { - String modifier = regexModifiers.get(c); - modifiers.add(modifier); - } - } + String regex = pattern.substring(1, i).replace("'", "\'"); + List modifiers = new ArrayList(); - vendorExtensions.put("x-regex", regex); - vendorExtensions.put("x-modifiers", modifiers); - } + for(char c : pattern.substring(i).toCharArray()) { + if(regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } } @Override From c039526993893635c16dd4c441bf77ab5c457ee3 Mon Sep 17 00:00:00 2001 From: diyfr Date: Mon, 9 May 2016 08:21:32 +0200 Subject: [PATCH 27/27] Add Springboot documentation --- README.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/README.md b/README.md index 1d97c7675d8..c9eb0d017fe 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ Check out [Swagger-Spec](https://github.com/OAI/OpenAPI-Specification) for addit - [Java JAX-RS (Apache CXF 2 / 3)](#java-jax-rs-apache-cxf-2--3) - [Java JAX-RS (Resteasy)](#java-jax-rs-resteasy) - [Java Spring MVC](#java-spring-mvc) + - [Java SpringBoot](#java-springboot) - [Haskell Servant](#haskell-servant) - [ASP.NET 5 Web API](#aspnet-5-web-api) - [To build the codegen library](#to-build-the-codegen-library) @@ -688,6 +689,31 @@ java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -o samples/server/petstore/spring-mvc ``` +### Java SpringBoot + +``` +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ + -i http://petstore.swagger.io/v2/swagger.json \ + -l springboot \ + -o samples/server/petstore/springboot +``` + +You can also set a Json file with basePackage & configPackage properties : +Example : +``` +{ +"basePackage":"io.swagger", +"configPackage":"io.swagger.config" +} +``` +For use it add option ```-c myOptions.json``` to the generation command + +To Use-it : +in the generated folder try ``` mvn package ``` for build jar. +Start your server ``` java -jar target/swagger-springboot-server-1.0.0.jar ``` +SpringBoot listening on default port 8080 + + ### Haskell Servant ```