From 3d4b5a10c9e1702d86b1214d47d07715d91dcfe9 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 21 May 2015 22:05:46 +0800 Subject: [PATCH 01/41] Add support of HTTP basic and API key auth to Java codegen --- .../codegen/languages/JavaClientCodegen.java | 16 ++++-- .../src/main/resources/Java/api.mustache | 3 +- .../main/resources/Java/apiInvoker.mustache | 15 ++++- .../resources/Java/auth/ApiKeyAuth.mustache | 55 +++++++++++++++++++ .../Java/auth/Authentication.mustache | 7 +++ .../Java/auth/HttpBasicAuth.mustache | 36 ++++++++++++ .../resources/Java/configuration.mustache | 25 +++++++++ 7 files changed, 148 insertions(+), 9 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache create mode 100644 modules/swagger-codegen/src/main/resources/Java/configuration.mustache diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 7c0ac7422ff..00273078436 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -50,13 +50,17 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { additionalProperties.put("artifactId", artifactId); additionalProperties.put("artifactVersion", artifactVersion); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator); + final String authFolder = (sourceFolder + File.separator + invokerPackage + ".auth").replace(".", java.io.File.separator); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("JsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("JsonUtil.mustache", invokerFolder, "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", invokerFolder, "ApiException.java")); + supportingFiles.add(new SupportingFile("configuration.mustache", invokerFolder, "Configuration.java")); + supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); + supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); + supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); languageSpecificPrimitives = new HashSet( Arrays.asList( diff --git a/modules/swagger-codegen/src/main/resources/Java/api.mustache b/modules/swagger-codegen/src/main/resources/Java/api.mustache index 78bac41d9d6..5731bbc6260 100644 --- a/modules/swagger-codegen/src/main/resources/Java/api.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/api.mustache @@ -92,7 +92,8 @@ public class {{classname}} { } try { - String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + String response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return {{#returnType}}({{{returnType}}}) ApiInvoker.deserialize(response, "{{returnContainer}}", {{returnBaseType}}.class){{/returnType}}; } diff --git a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache index ac689046047..94e8f45782d 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache @@ -31,6 +31,8 @@ import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.text.ParseException; +import {{invokerPackage}}.auth.Authentication; + public class ApiInvoker { private static ApiInvoker INSTANCE = new ApiInvoker(); private Map hostMap = new HashMap(); @@ -162,11 +164,12 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException { + processAuthParams(authNames, queryParams, headerParams); + Client client = getClient(host); StringBuilder b = new StringBuilder(); - for(String key : queryParams.keySet()) { String value = queryParams.get(key); if (value != null){ @@ -267,6 +270,14 @@ public class ApiInvoker { } } + private void processAuthParams(String[] authNames, Map queryParams, Map headerParams) { + for(String authName : authNames) { + Authentication auth = Configuration.getAuthentication(authName); + if(auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); + auth.processParams(queryParams, headerParams); + } + } + private Client getClient(String host) { if(!hostMap.containsKey(host)) { Client client = Client.create(); diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..f854bab9170 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -0,0 +1,55 @@ +package {{invokerPackage}}.auth; + +import java.util.Map; + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void processParams(Map queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.put(paramName, value); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache new file mode 100644 index 00000000000..7aba61e631a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -0,0 +1,7 @@ +package {{invokerPackage}}.auth; + +import java.util.Map; + +public interface Authentication { + void processParams(Map queryParams, Map headerParams); +} diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..f77bbf57b75 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -0,0 +1,36 @@ +package {{invokerPackage}}.auth; + +import java.util.Map; + +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void processParams(Map queryParams, Map headerParams) { + try { + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/configuration.mustache new file mode 100644 index 00000000000..13928df05c3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/configuration.mustache @@ -0,0 +1,25 @@ +package {{invokerPackage}}; + +import java.util.Map; +import java.util.HashMap; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; + +public class Configuration { + private static final Map AUTH; + + static { + AUTH = new HashMap(); + {{#authMethods}} + {{#isBasic}}AUTH.put("{{name}}", new HttpBasicAuth());{{/isBasic}} + {{#isApiKey}}AUTH.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}} + {{#isOAuth}}// TODO: support oauth{{/isOAuth}} + {{/authMethods}} + } + + public static Authentication getAuthentication(String authName) { + return AUTH.get(authName); + } +} From f616605e7e17672d38cd76bed06dca906554e6a6 Mon Sep 17 00:00:00 2001 From: xhh Date: Thu, 21 May 2015 22:09:08 +0800 Subject: [PATCH 02/41] Regenerate Java Petstore sample --- .../java/io/swagger/client/ApiInvoker.java | 15 ++++- .../java/io/swagger/client/Configuration.java | 29 ++++++++++ .../java/io/swagger/client/api/PetApi.java | 24 +++++--- .../java/io/swagger/client/api/StoreApi.java | 12 ++-- .../java/io/swagger/client/api/UserApi.java | 24 +++++--- .../io/swagger/client/auth/ApiKeyAuth.java | 55 +++++++++++++++++++ .../swagger/client/auth/Authentication.java | 7 +++ .../io/swagger/client/auth/HttpBasicAuth.java | 36 ++++++++++++ 8 files changed, 180 insertions(+), 22 deletions(-) create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java index ab6f551327f..a667ebf2c65 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java @@ -31,6 +31,8 @@ import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.text.ParseException; +import io.swagger.client.auth.Authentication; + public class ApiInvoker { private static ApiInvoker INSTANCE = new ApiInvoker(); private Map hostMap = new HashMap(); @@ -162,11 +164,12 @@ public class ApiInvoker { } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType) throws ApiException { + public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException { + processAuthParams(authNames, queryParams, headerParams); + Client client = getClient(host); StringBuilder b = new StringBuilder(); - for(String key : queryParams.keySet()) { String value = queryParams.get(key); if (value != null){ @@ -267,6 +270,14 @@ public class ApiInvoker { } } + private void processAuthParams(String[] authNames, Map queryParams, Map headerParams) { + for(String authName : authNames) { + Authentication auth = Configuration.getAuthentication(authName); + if(auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); + auth.processParams(queryParams, headerParams); + } + } + private Client getClient(String host) { if(!hostMap.containsKey(host)) { Client client = Client.create(); diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java new file mode 100644 index 00000000000..366fd5256a4 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -0,0 +1,29 @@ +package io.swagger.client; + +import java.util.Map; +import java.util.HashMap; + +import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; + +public class Configuration { + private static final Map AUTH; + + static { + AUTH = new HashMap(); + + + AUTH.put("api_key", new ApiKeyAuth("header", "api_key")); + + + + + // TODO: support oauth + + } + + public static Authentication getAuthentication(String authName) { + return AUTH.get(authName); + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index 10326d8a2d6..e99bcfafc08 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -74,7 +74,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -124,7 +125,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -176,7 +178,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (List) ApiInvoker.deserialize(response, "array", Pet.class); } @@ -228,7 +231,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (List) ApiInvoker.deserialize(response, "array", Pet.class); } @@ -284,7 +288,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "api_key", "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (Pet) ApiInvoker.deserialize(response, "", Pet.class); } @@ -350,7 +355,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -408,7 +414,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -475,7 +482,8 @@ public class PetApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "petstore_auth" }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java index 6da7b5abb2f..dd3629ab1b7 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/StoreApi.java @@ -73,7 +73,8 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { "api_key" }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (Map) ApiInvoker.deserialize(response, "map", Map.class); } @@ -123,7 +124,8 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (Order) ApiInvoker.deserialize(response, "", Order.class); } @@ -179,7 +181,8 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (Order) ApiInvoker.deserialize(response, "", Order.class); } @@ -235,7 +238,8 @@ public class StoreApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java index d0974d95a52..b627d2c70e9 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/UserApi.java @@ -74,7 +74,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -124,7 +125,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -174,7 +176,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -229,7 +232,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (String) ApiInvoker.deserialize(response, "", String.class); } @@ -278,7 +282,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -334,7 +339,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return (User) ApiInvoker.deserialize(response, "", User.class); } @@ -391,7 +397,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } @@ -447,7 +454,8 @@ public class UserApi { } try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType); + String[] authNames = new String[] { }; + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, postBody, headerParams, formParams, contentType, authNames); if(response != null){ return ; } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..1f84fd12685 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -0,0 +1,55 @@ +package io.swagger.client.auth; + +import java.util.Map; + +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void processParams(Map queryParams, Map headerParams) { + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location == "query") { + queryParams.put(paramName, value); + } else if (location == "header") { + headerParams.put(paramName, value); + } + } +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java new file mode 100644 index 00000000000..50ed42e15f2 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java @@ -0,0 +1,7 @@ +package io.swagger.client.auth; + +import java.util.Map; + +public interface Authentication { + void processParams(Map queryParams, Map headerParams); +} diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..b4a1266a1b4 --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -0,0 +1,36 @@ +package io.swagger.client.auth; + +import java.util.Map; + +import java.io.UnsupportedEncodingException; +import javax.xml.bind.DatatypeConverter; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void processParams(Map queryParams, Map headerParams) { + try { + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } +} From 16ba2a54ea9fcde974aeffffb96e52074d4c72ee Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 22 May 2015 11:17:44 +0800 Subject: [PATCH 03/41] Add test cases for API key and HTTP basic auth --- .../swagger/client/auth/ApiKeyAuthTest.java | 40 +++++++++++++++++++ .../client/auth/HttpBasicAuthTest.java | 33 +++++++++++++++ 2 files changed, 73 insertions(+) create mode 100644 samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java create mode 100644 samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java new file mode 100644 index 00000000000..13289a7c495 --- /dev/null +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,40 @@ +package io.swagger.client.auth; + +import java.util.Map; +import java.util.HashMap; + +import static org.junit.Assert.*; +import org.junit.*; + +public class ApiKeyAuthTest { + @Test + public void testProcessParamsInQuery() { + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.processParams(queryParams, headerParams); + + assertEquals(1, queryParams.size()); + assertEquals("my-api-key", queryParams.get("api_key")); + // no changes to header parameters + assertEquals(0, headerParams.size()); + } + + @Test + public void testProcessParamsInHeaderWithPrefix() { + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.processParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java new file mode 100644 index 00000000000..8c4db19adfa --- /dev/null +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,33 @@ +package io.swagger.client.auth; + +import java.util.Map; +import java.util.HashMap; + +import static org.junit.Assert.*; +import org.junit.*; + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testProcessParams() { + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.processParams(queryParams, headerParams); + + // no changes to query parameters + assertEquals(0, queryParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix + final String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + } +} From 43cfc7d401634b5e7d031181f173d3736e2f7f01 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 22 May 2015 12:07:08 +0800 Subject: [PATCH 04/41] Setup authentications in test cases --- .../swagger/codegen/languages/JavaClientCodegen.java | 1 + .../src/main/resources/Java/auth/OAuth.mustache | 10 ++++++++++ .../src/main/resources/Java/configuration.mustache | 4 +++- .../src/main/java/io/swagger/client/Configuration.java | 4 +++- .../src/main/java/io/swagger/client/auth/OAuth.java | 10 ++++++++++ .../test/java/io/swagger/petstore/test/PetApiTest.java | 8 ++++++++ .../java/io/swagger/petstore/test/StoreApiTest.java | 8 ++++++++ .../java/io/swagger/petstore/test/UserApiTest.java | 8 ++++++++ 8 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache create mode 100644 samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 00273078436..4cc6fc7aa1b 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -61,6 +61,7 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("auth/Authentication.mustache", authFolder, "Authentication.java")); supportingFiles.add(new SupportingFile("auth/HttpBasicAuth.mustache", authFolder, "HttpBasicAuth.java")); supportingFiles.add(new SupportingFile("auth/ApiKeyAuth.mustache", authFolder, "ApiKeyAuth.java")); + supportingFiles.add(new SupportingFile("auth/OAuth.mustache", authFolder, "OAuth.java")); languageSpecificPrimitives = new HashSet( Arrays.asList( diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache new file mode 100644 index 00000000000..f970481426d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -0,0 +1,10 @@ +package {{invokerPackage}}.auth; + +import java.util.Map; + +public class OAuth implements Authentication { + @Override + public void processParams(Map queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/modules/swagger-codegen/src/main/resources/Java/configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/configuration.mustache index 13928df05c3..aaeb532829b 100644 --- a/modules/swagger-codegen/src/main/resources/Java/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/configuration.mustache @@ -6,16 +6,18 @@ import java.util.HashMap; import {{invokerPackage}}.auth.Authentication; import {{invokerPackage}}.auth.HttpBasicAuth; import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; public class Configuration { private static final Map AUTH; static { + // setup authentications AUTH = new HashMap(); {{#authMethods}} {{#isBasic}}AUTH.put("{{name}}", new HttpBasicAuth());{{/isBasic}} {{#isApiKey}}AUTH.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}} - {{#isOAuth}}// TODO: support oauth{{/isOAuth}} + {{#isOAuth}}AUTH.put("{{name}}", new OAuth());{{/isOAuth}} {{/authMethods}} } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java index 366fd5256a4..753a3f215cc 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -6,11 +6,13 @@ import java.util.HashMap; import io.swagger.client.auth.Authentication; import io.swagger.client.auth.HttpBasicAuth; import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; public class Configuration { private static final Map AUTH; static { + // setup authentications AUTH = new HashMap(); @@ -19,7 +21,7 @@ public class Configuration { - // TODO: support oauth + AUTH.put("petstore_auth", new OAuth()); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java new file mode 100644 index 00000000000..e4b6ab49c0d --- /dev/null +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java @@ -0,0 +1,10 @@ +package io.swagger.client.auth; + +import java.util.Map; + +public class OAuth implements Authentication { + @Override + public void processParams(Map queryParams, Map headerParams) { + // TODO: support oauth + } +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 97f3b5f8006..ccb73755d28 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -1,8 +1,10 @@ package io.swagger.petstore.test; import io.swagger.client.ApiException; +import io.swagger.client.Configuration; import io.swagger.client.api.*; import io.swagger.client.model.*; +import io.swagger.client.auth.*; import java.util.*; import java.io.*; @@ -13,6 +15,12 @@ import org.junit.*; public class PetApiTest { PetApi api = null; + @BeforeClass + public static void initAuth() { + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + @Before public void setup() { api = new PetApi(); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java index 25a52009b9e..c5e2a9b8719 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -1,8 +1,10 @@ package io.swagger.petstore.test; import io.swagger.client.ApiException; +import io.swagger.client.Configuration; import io.swagger.client.api.*; import io.swagger.client.model.*; +import io.swagger.client.auth.*; import java.util.*; import java.io.*; @@ -13,6 +15,12 @@ import org.junit.*; public class StoreApiTest { StoreApi api = null; + @BeforeClass + public static void initAuth() { + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + @Before public void setup() { api = new StoreApi(); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java index 9d683faab7a..8fcb621b85e 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -1,8 +1,10 @@ package io.swagger.petstore.test; import io.swagger.client.ApiException; +import io.swagger.client.Configuration; import io.swagger.client.api.*; import io.swagger.client.model.*; +import io.swagger.client.auth.*; import java.util.*; import java.io.*; @@ -13,6 +15,12 @@ import org.junit.*; public class UserApiTest { UserApi api = null; + @BeforeClass + public static void initAuth() { + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + } + @Before public void setup() { api = new UserApi(); From 6eb1a89205b0ca495ce81bda098cd8e46585b88d Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 29 May 2015 11:28:03 +0800 Subject: [PATCH 05/41] Add authentication helper methods and test cases --- .../resources/Java/configuration.mustache | 44 +++++++++++++++ .../java/io/swagger/client/Configuration.java | 44 +++++++++++++++ .../io/swagger/client/ConfigurationTest.java | 56 +++++++++++++++++++ 3 files changed, 144 insertions(+) create mode 100644 samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java diff --git a/modules/swagger-codegen/src/main/resources/Java/configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/configuration.mustache index aaeb532829b..cd367c65704 100644 --- a/modules/swagger-codegen/src/main/resources/Java/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/configuration.mustache @@ -24,4 +24,48 @@ public class Configuration { public static Authentication getAuthentication(String authName) { return AUTH.get(authName); } + + /** Set username for the first HTTP basic authentication. */ + public static void setUsername(String username) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** Set password for the first HTTP basic authentication. */ + public static void setPassword(String password) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** Set API key value for the first API key authentication. */ + public static void setApiKey(String apiKey) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** Set API key prefix for the first API key authentication. */ + public static void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java index 753a3f215cc..6fb5fb56e7c 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -28,4 +28,48 @@ public class Configuration { public static Authentication getAuthentication(String authName) { return AUTH.get(authName); } + + /** Set username for the first HTTP basic authentication. */ + public static void setUsername(String username) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** Set password for the first HTTP basic authentication. */ + public static void setPassword(String password) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** Set API key value for the first API key authentication. */ + public static void setApiKey(String apiKey) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** Set API key prefix for the first API key authentication. */ + public static void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : AUTH.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java new file mode 100644 index 00000000000..b7c51739359 --- /dev/null +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java @@ -0,0 +1,56 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import static org.junit.Assert.*; +import org.junit.*; + +public class ConfigurationTest { + @Test + public void testGetAuthentication() { + Authentication auth = Configuration.getAuthentication("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = Configuration.getAuthentication("petstore_auth"); + assertTrue(auth instanceof OAuth); + + assertNull(Configuration.getAuthentication("unknown")); + } + + @Test + public void testSetUsername() { + try { + Configuration.setUsername("my-username"); + fail("should throw RuntimeException"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetPassword() { + try { + Configuration.setPassword("my-password"); + fail("should throw RuntimeException"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + Configuration.setApiKey("my-api-key"); + Configuration.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } +} From e10e1f5249c12c64fe109233e34dcef68a8863dc Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 29 May 2015 11:29:06 +0800 Subject: [PATCH 06/41] Refactor auth method naming, add comments --- .../src/main/resources/Java/apiInvoker.mustache | 7 ++++--- .../src/main/resources/Java/auth/ApiKeyAuth.mustache | 2 +- .../src/main/resources/Java/auth/Authentication.mustache | 3 ++- .../src/main/resources/Java/auth/HttpBasicAuth.mustache | 2 +- .../src/main/resources/Java/auth/OAuth.mustache | 2 +- .../java/src/main/java/io/swagger/client/ApiInvoker.java | 7 ++++--- .../src/main/java/io/swagger/client/auth/ApiKeyAuth.java | 2 +- .../main/java/io/swagger/client/auth/Authentication.java | 3 ++- .../main/java/io/swagger/client/auth/HttpBasicAuth.java | 2 +- .../java/src/main/java/io/swagger/client/auth/OAuth.java | 2 +- .../test/java/io/swagger/client/auth/ApiKeyAuthTest.java | 8 ++++---- .../java/io/swagger/client/auth/HttpBasicAuthTest.java | 4 ++-- 12 files changed, 24 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache index f1025bc88d3..fb116161d55 100644 --- a/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/apiInvoker.mustache @@ -166,7 +166,7 @@ public class ApiInvoker { } public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException { - processAuthParams(authNames, queryParams, headerParams); + updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(host); @@ -266,11 +266,12 @@ public class ApiInvoker { } } - private void processAuthParams(String[] authNames, Map queryParams, Map headerParams) { + /* Update hearder and query params based on authentication settings. */ + private void updateParamsForAuth(String[] authNames, Map queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = Configuration.getAuthentication(authName); if (auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); - auth.processParams(queryParams, headerParams); + auth.applyToParams(queryParams, headerParams); } } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache index f854bab9170..65720b958cb 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/ApiKeyAuth.mustache @@ -39,7 +39,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void processParams(Map queryParams, Map headerParams) { + public void applyToParams(Map queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache index 7aba61e631a..1b2e2bc2fbe 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/Authentication.mustache @@ -3,5 +3,6 @@ package {{invokerPackage}}.auth; import java.util.Map; public interface Authentication { - void processParams(Map queryParams, Map headerParams); + /** Apply authentication settings to header and query params. */ + void applyToParams(Map queryParams, Map headerParams); } diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index f77bbf57b75..28d5703b757 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -26,7 +26,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void processParams(Map queryParams, Map headerParams) { + public void applyToParams(Map queryParams, Map headerParams) { try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache index f970481426d..ef84b8cc05e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/OAuth.mustache @@ -4,7 +4,7 @@ import java.util.Map; public class OAuth implements Authentication { @Override - public void processParams(Map queryParams, Map headerParams) { + public void applyToParams(Map queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java index 8ed18b62c15..841a348e0b3 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiInvoker.java @@ -166,7 +166,7 @@ public class ApiInvoker { } public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, Map formParams, String contentType, String[] authNames) throws ApiException { - processAuthParams(authNames, queryParams, headerParams); + updateParamsForAuth(authNames, queryParams, headerParams); Client client = getClient(host); @@ -266,11 +266,12 @@ public class ApiInvoker { } } - private void processAuthParams(String[] authNames, Map queryParams, Map headerParams) { + /* Update hearder and query params based on authentication settings. */ + private void updateParamsForAuth(String[] authNames, Map queryParams, Map headerParams) { for (String authName : authNames) { Authentication auth = Configuration.getAuthentication(authName); if (auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); - auth.processParams(queryParams, headerParams); + auth.applyToParams(queryParams, headerParams); } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java index 1f84fd12685..ce55babb51d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/ApiKeyAuth.java @@ -39,7 +39,7 @@ public class ApiKeyAuth implements Authentication { } @Override - public void processParams(Map queryParams, Map headerParams) { + public void applyToParams(Map queryParams, Map headerParams) { String value; if (apiKeyPrefix != null) { value = apiKeyPrefix + " " + apiKey; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java index 50ed42e15f2..3f372404c8d 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/Authentication.java @@ -3,5 +3,6 @@ package io.swagger.client.auth; import java.util.Map; public interface Authentication { - void processParams(Map queryParams, Map headerParams); + /** Apply authentication settings to header and query params. */ + void applyToParams(Map queryParams, Map headerParams); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index b4a1266a1b4..37ceffa1638 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -26,7 +26,7 @@ public class HttpBasicAuth implements Authentication { } @Override - public void processParams(Map queryParams, Map headerParams) { + public void applyToParams(Map queryParams, Map headerParams) { try { headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java index e4b6ab49c0d..d834f4580c2 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/OAuth.java @@ -4,7 +4,7 @@ import java.util.Map; public class OAuth implements Authentication { @Override - public void processParams(Map queryParams, Map headerParams) { + public void applyToParams(Map queryParams, Map headerParams) { // TODO: support oauth } } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java index 13289a7c495..f90ee3d7b22 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/ApiKeyAuthTest.java @@ -8,13 +8,13 @@ import org.junit.*; public class ApiKeyAuthTest { @Test - public void testProcessParamsInQuery() { + public void testApplyToParamsInQuery() { Map queryParams = new HashMap(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); auth.setApiKey("my-api-key"); - auth.processParams(queryParams, headerParams); + auth.applyToParams(queryParams, headerParams); assertEquals(1, queryParams.size()); assertEquals("my-api-key", queryParams.get("api_key")); @@ -23,14 +23,14 @@ public class ApiKeyAuthTest { } @Test - public void testProcessParamsInHeaderWithPrefix() { + public void testApplyToParamsInHeaderWithPrefix() { Map queryParams = new HashMap(); Map headerParams = new HashMap(); ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); auth.setApiKey("my-api-token"); auth.setApiKeyPrefix("Token"); - auth.processParams(queryParams, headerParams); + auth.applyToParams(queryParams, headerParams); // no changes to query parameters assertEquals(0, queryParams.size()); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java index 8c4db19adfa..dc57a61391a 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -15,13 +15,13 @@ public class HttpBasicAuthTest { } @Test - public void testProcessParams() { + public void testApplyToParams() { Map queryParams = new HashMap(); Map headerParams = new HashMap(); auth.setUsername("my-username"); auth.setPassword("my-password"); - auth.processParams(queryParams, headerParams); + auth.applyToParams(queryParams, headerParams); // no changes to query parameters assertEquals(0, queryParams.size()); From 6a6473ede3be20e5b6e91de7b1f7d81126e8d1a7 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 29 May 2015 11:55:48 +0800 Subject: [PATCH 07/41] Allow omitting username/password for HTTP basic auth --- .../resources/Java/auth/HttpBasicAuth.mustache | 3 ++- .../io/swagger/client/auth/HttpBasicAuth.java | 3 ++- .../swagger/client/auth/HttpBasicAuthTest.java | 17 ++++++++++++++++- 3 files changed, 20 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache index 28d5703b757..22a64b1a24e 100644 --- a/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/auth/HttpBasicAuth.mustache @@ -27,8 +27,9 @@ public class HttpBasicAuth implements Authentication { @Override public void applyToParams(Map queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { - headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"))); + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java index 37ceffa1638..24bff8c2266 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/auth/HttpBasicAuth.java @@ -27,8 +27,9 @@ public class HttpBasicAuth implements Authentication { @Override public void applyToParams(Map queryParams, Map headerParams) { + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); try { - headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary((username + ":" + password).getBytes("UTF-8"))); + headerParams.put("Authorization", "Basic " + DatatypeConverter.printBase64Binary(str.getBytes("UTF-8"))); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java index dc57a61391a..87d6eca8b82 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/auth/HttpBasicAuthTest.java @@ -27,7 +27,22 @@ public class HttpBasicAuthTest { assertEquals(0, queryParams.size()); assertEquals(1, headerParams.size()); // the string below is base64-encoded result of "my-username:my-password" with the "Basic " prefix - final String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; assertEquals(expected, headerParams.get("Authorization")); } } From 049299f07f8ed5560afcaa0a98c1eacaa8376d86 Mon Sep 17 00:00:00 2001 From: Fredrik Gustafsson Date: Fri, 29 May 2015 10:53:48 +0200 Subject: [PATCH 08/41] Updated 'api.mustache' to generate asynchronous methods aswell --- .../src/main/resources/csharp/api.mustache | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index f7cc79c5255..50e80ae6497 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using RestSharp; using {{invokerPackage}}; using {{modelPackage}}; @@ -78,7 +79,49 @@ namespace {{package}} { {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} } + + /// + /// {{summary}} {{notes}} + /// +{{#allParams}} /// {{description}} +{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} + public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + + var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); + + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} + + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + + _request.AddUrlSegment("format", "json"); // set format to json by default + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + {{/pathParams}} + {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{/formParams}} + {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{/bodyParam}} + + // make the HTTP request + IRestResponse response = await restClient.ExecuteTaskAsync(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); + } + {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + return;{{/returnType}} + } {{/operation}} - } + } {{/operations}} } From 41e4fc79ae184e90e26bcc06cf31006e0086d804 Mon Sep 17 00:00:00 2001 From: Fredrik Gustafsson Date: Fri, 29 May 2015 12:19:28 +0200 Subject: [PATCH 09/41] Extended the api-class generation by a interface generation --- .../src/main/resources/csharp/api.mustache | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 50e80ae6497..bf7da6efdb8 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -9,7 +9,16 @@ using {{modelPackage}}; namespace {{package}} { {{#operations}} - public class {{classname}} { + + public interface I{{classname}} { + {{#operation}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} + } + + public class {{classname}} : I{{classname}} { string basePath; protected RestClient restClient; From b5429d9e8ec2afe852980551443defc7f5c9e1d0 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 30 May 2015 18:04:20 +0800 Subject: [PATCH 10/41] Added authentication for objc client. --- .../codegen/languages/ObjcClientCodegen.java | 2 + .../src/main/resources/objc/SWGApiClient.h | 15 +++ .../src/main/resources/objc/SWGApiClient.m | 58 ++++++++- .../objc/SWGConfiguration-body.mustache | 91 ++++++++++++++ .../objc/SWGConfiguration-header.mustache | 51 ++++++++ .../resources/objc/SWGQueryParamCollection.m | 2 +- .../src/main/resources/objc/api-body.mustache | 5 + .../main/resources/objc/api-header.mustache | 1 + .../apiBodyResponseWithContainer.mustache | 1 + .../objc/apiNonPrimitiveResponse.mustache | 1 + .../objc/apiPrimitiveResponse.mustache | 1 + .../main/resources/objc/voidResponse.mustache | 1 + .../PetstoreClient.xcodeproj/project.pbxproj | 6 + .../xcschemes/PetstoreClient.xcscheme | 112 ++++++++++++++++++ .../xcschemes/xcschememanagement.plist | 27 +++++ .../PetstoreClient/ViewController.m | 9 ++ .../PetstoreClientTests/SWGApiClientTest.m | 44 ++++++- samples/client/petstore/objc/Podfile.lock | 4 +- .../petstore/objc/client/SWGApiClient.h | 15 +++ .../petstore/objc/client/SWGApiClient.m | 58 ++++++++- .../petstore/objc/client/SWGConfiguration.h | 51 ++++++++ .../petstore/objc/client/SWGConfiguration.m | 91 ++++++++++++++ .../client/petstore/objc/client/SWGPetApi.m | 34 ++++++ .../objc/client/SWGQueryParamCollection.m | 2 +- .../client/petstore/objc/client/SWGStoreApi.h | 1 + .../client/petstore/objc/client/SWGStoreApi.m | 18 +++ .../client/petstore/objc/client/SWGUserApi.h | 1 + .../client/petstore/objc/client/SWGUserApi.m | 34 ++++++ 28 files changed, 721 insertions(+), 15 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/PetstoreClient.xcscheme create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/xcschememanagement.plist create mode 100644 samples/client/petstore/objc/client/SWGConfiguration.h create mode 100644 samples/client/petstore/objc/client/SWGConfiguration.m diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index d1e227ce744..9020a5f8170 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -122,6 +122,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("SWGConfiguration-body.mustache", sourceFolder, "SWGConfiguration.m")); + supportingFiles.add(new SupportingFile("SWGConfiguration-header.mustache", sourceFolder, "SWGConfiguration.h")); supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); } diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h index cd6f52db5c6..d1f9203f180 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h @@ -54,11 +54,16 @@ extern NSString *const SWGResponseObjectErrorKey; -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey; +- (void) updateHeaderParams:(NSDictionary **)headers + queryParams:(NSDictionary **)querys + WithAuthSettings:(NSArray *)authSettings; + -(NSNumber*) dictionary:(NSString*) path method:(NSString*) method queryParams:(NSDictionary*) queryParams body:(id) body headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType:(NSString*) requestContentType responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; @@ -68,8 +73,18 @@ extern NSString *const SWGResponseObjectErrorKey; queryParams:(NSDictionary*) queryParams body:(id) body headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType:(NSString*) requestContentType responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSString*, NSError *))completionBlock; @end + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m index b38b02e0e03..5e2985bbe79 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.m @@ -1,6 +1,7 @@ #import "SWGApiClient.h" #import "SWGFile.h" #import "SWGQueryParamCollection.h" +#import "SWGConfiguration.h" @implementation SWGApiClient @@ -15,10 +16,22 @@ static NSOperationQueue* sharedQueue; static void (^reachabilityChangeBlock)(int); static bool loggingEnabled = true; +#pragma mark - Log Methods + +(void)setLoggingEnabled:(bool) state { loggingEnabled = state; } +- (void)logRequest:(NSURLRequest*)request { + NSLog(@"request: %@", [self descriptionForRequest:request]); +} + +- (void)logResponse:(id)data forRequest:(NSURLRequest*)request error:(NSError*)error { + NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); +} + +#pragma mark - + +(void)clearCache { [[NSURLCache sharedURLCache] removeAllCachedResponses]; } @@ -305,19 +318,47 @@ static bool loggingEnabled = true; return [[request URL] absoluteString]; } -- (void)logRequest:(NSURLRequest*)request { - NSLog(@"request: %@", [self descriptionForRequest:request]); + +/** + * Update header and query params based on authentication settings + */ +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if (!authSettings || [authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; + + if (authSetting) { + if ([authSetting[@"in"] isEqualToString:@"header"]) { + [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + else if ([authSetting[@"in"] isEqualToString:@"query"]) { + [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (void)logResponse:(id)data forRequest:(NSURLRequest*)request error:(NSError*)error { - NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); -} +#pragma mark - Perform Request Methods -(NSNumber*) dictionary: (NSString*) path method: (NSString*) method queryParams: (NSDictionary*) queryParams body: (id) body headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType: (NSString*) requestContentType responseContentType: (NSString*) responseContentType completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock { @@ -342,6 +383,9 @@ static bool loggingEnabled = true; else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; NSMutableURLRequest * request = nil; if (body != nil && [body isKindOfClass:[NSArray class]]){ @@ -476,6 +520,7 @@ static bool loggingEnabled = true; queryParams: (NSDictionary*) queryParams body: (id) body headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType: (NSString*) requestContentType responseContentType: (NSString*) responseContentType completionBlock: (void (^)(NSString*, NSError *))completionBlock { @@ -500,6 +545,9 @@ static bool loggingEnabled = true; else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; NSMutableURLRequest * request = nil; if (body != nil && [body isKindOfClass:[NSArray class]]){ diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache new file mode 100644 index 00000000000..b326244fe0a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache @@ -0,0 +1,91 @@ +#import "SWGConfiguration.h" + +@interface SWGConfiguration () + +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; + +@end + +@implementation SWGConfiguration + +#pragma mark - Singletion Methods + ++ (instancetype) sharedConfig { + static SWGConfiguration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype) init { + self = [super init]; + if (self) { + self.username = @""; + self.password = @""; + self.mutableApiKey = [NSMutableDictionary dictionary]; + self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + } + return self; +} + +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { + return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + } + else if ([self.apiKey objectForKey:key]) { + return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + } + else { + return @""; + } +} + +#pragma mark - Setter Methods + +- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { + [self.mutableApiKey setValue:value forKey:field]; +} + +- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { + [self.mutableApiKeyPrefix setValue:value forKey:field]; +} + +#pragma mark - Getter Methods + +- (NSDictionary *) apiKey { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; +} + +- (NSDictionary *) apiKeyPrefix { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{ {{#authMethods}}{{#isApiKey}} + @"{{name}}": @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, + {{/isApiKey}}{{#isBasic}} + @"{{name}}": @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, + {{/isBasic}}{{/authMethods}} + }; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache new file mode 100644 index 00000000000..0ddac56acdf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache @@ -0,0 +1,51 @@ +#import + +@interface SWGConfiguration : NSObject + + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setValue:forApiKeyField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Usename and Password for Basic type Authentication + */ +@property (nonatomic) NSString *username; +@property (nonatomic) NSString *password; + +/** + * Get configuration singleton instance + */ ++ (instancetype) sharedConfig; + +/** + * Sets field in `apiKey` + */ +- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; + +/** + * Sets field in `apiKeyPrefix` + */ +- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; + +/** + * Get API key (with prefix if set) + */ +- (NSString *) getApiKeyWithPrefix:(NSString *) key; + +/** + * Get Authentication Setings + */ +- (NSDictionary *) authSettings; + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGQueryParamCollection.m b/modules/swagger-codegen/src/main/resources/objc/SWGQueryParamCollection.m index 9ce319940dd..83303045185 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGQueryParamCollection.m +++ b/modules/swagger-codegen/src/main/resources/objc/SWGQueryParamCollection.m @@ -13,4 +13,4 @@ return self; } -@end \ No newline at end of file +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index abe4376d1ac..40d75bd806b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -39,6 +39,8 @@ static NSString * basePath = @"{{basePath}}"; return self; } +#pragma mark - + +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static {{classname}}* singletonAPI = nil; @@ -129,6 +131,9 @@ static NSString * basePath = @"{{basePath}}"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + // Authentication setting + NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; + id bodyDictionary = nil; {{#bodyParam}} id __body = {{paramName}}; diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 4d571f756ce..65f4c39e0b3 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -10,6 +10,7 @@ @property(nonatomic, assign)SWGApiClient *apiClient; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; diff --git a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache index 5aabef86841..acaeaf2ddf5 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiBodyResponseWithContainer.mustache @@ -4,6 +4,7 @@ queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { diff --git a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache index 81cf1343e53..da8ea063bfb 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache @@ -5,6 +5,7 @@ queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { diff --git a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache index 3d6b105f227..d44d356526d 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiPrimitiveResponse.mustache @@ -4,6 +4,7 @@ queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { diff --git a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache index ab4062a6dbe..7bbbc14c066 100644 --- a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache @@ -3,6 +3,7 @@ queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index 723caec2cdb..5c1bfabf608 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -8,6 +8,7 @@ /* Begin PBXBuildFile section */ BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; + CF0560EB1B1855CF00C0D4EC /* SWGConfiguration.m in Sources */ = {isa = PBXBuildFile; fileRef = CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */; }; CF31D0991B105E4B00509935 /* SWGApiClientTest.m in Sources */ = {isa = PBXBuildFile; fileRef = CF31D0981B105E4B00509935 /* SWGApiClientTest.m */; }; CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; @@ -56,6 +57,8 @@ /* Begin PBXFileReference section */ 73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; A425648B5C0A4849C7668069 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + CF0560E91B1855CF00C0D4EC /* SWGConfiguration.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGConfiguration.h; sourceTree = ""; }; + CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGConfiguration.m; sourceTree = ""; }; CF31D0981B105E4B00509935 /* SWGApiClientTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClientTest.m; sourceTree = ""; }; CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = ""; }; CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = ""; }; @@ -234,6 +237,8 @@ EA8B8AA31AC6683700638FBB /* SWGQueryParamCollection.m */, EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */, EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */, + CF0560E91B1855CF00C0D4EC /* SWGConfiguration.h */, + CF0560EA1B1855CF00C0D4EC /* SWGConfiguration.m */, EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */, EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */, EAEA85D21811D3AE00F06E69 /* SWGFile.h */, @@ -395,6 +400,7 @@ buildActionMask = 2147483647; files = ( EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */, + CF0560EB1B1855CF00C0D4EC /* SWGConfiguration.m in Sources */, EAEA85ED1811D3AE00F06E69 /* SWGTag.m in Sources */, EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */, EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */, diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/PetstoreClient.xcscheme b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/PetstoreClient.xcscheme new file mode 100644 index 00000000000..1a2a738abea --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/PetstoreClient.xcscheme @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/xcschememanagement.plist b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/xcschememanagement.plist new file mode 100644 index 00000000000..912710bdccc --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/geekerzp.xcuserdatad/xcschemes/xcschememanagement.plist @@ -0,0 +1,27 @@ + + + + + SchemeUserState + + PetstoreClient.xcscheme + + orderHint + 4 + + + SuppressBuildableAutocreation + + EA6699951811D2FA00A70D03 + + primary + + + EA6699B91811D2FB00A70D03 + + primary + + + + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m index 7c47bb1f271..d56bc037206 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m @@ -8,6 +8,7 @@ #import "ViewController.h" #import "SWGPetApi.h" +#import "SWGConfiguration.h" @interface ViewController () @@ -53,6 +54,14 @@ // } ]; */ + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + config.username = @"foo"; + config.password = @"bar"; + SWGPetApi *api = [[SWGPetApi alloc] init]; + [api addPetWithCompletionBlock:nil + completionHandler:^(NSError *error) { + + }]; } - (void)didReceiveMemoryWarning diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m index 0464bf569e9..61925b16960 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/SWGApiClientTest.m @@ -1,16 +1,19 @@ #import #import #import "SWGApiClient.h" +#import "SWGConfiguration.h" @interface SWGApiClientTest : XCTestCase +@property (nonatomic) SWGApiClient *apiClient; + @end @implementation SWGApiClientTest - (void)setUp { [super setUp]; - // Put setup code here. This method is called before the invocation of each test method in the class. + self.apiClient = [[SWGApiClient alloc] init]; } - (void)tearDown { @@ -56,4 +59,43 @@ XCTAssertEqualObjects([SWGApiClient selectHeaderContentType:contentTypes], @"application/json"); } +- (void)testConfiguration { + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + [config setValue:@"123456" forApiKeyField:@"api_key"]; + [config setValue:@"PREFIX" forApiKeyPrefixField:@"api_key"]; + config.username = @"test_username"; + config.password = @"test_password"; + + NSDictionary *headerParams = @{@"test1": @"value1"}; + NSDictionary *queryParams = @{@"test2": @"value2"}; + NSArray *authSettings = @[@"api_key", @"unknown"]; + + // test prefix + XCTAssertEqualObjects(@"PREFIX", config.apiKeyPrefix[@"api_key"]); + [self.apiClient updateHeaderParams:&headerParams + queryParams:&queryParams + WithAuthSettings:authSettings]; + + // test api key auth + XCTAssertEqualObjects(headerParams[@"test1"], @"value1"); + XCTAssertEqualObjects(headerParams[@"api_key"], @"PREFIX 123456"); + XCTAssertEqualObjects(queryParams[@"test2"], @"value2"); + + // test basic auth + XCTAssertEqualObjects(@"test_username", config.username); + XCTAssertEqualObjects(@"test_password", config.password); +} + +- (void)testGetBasicAuthToken { + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + config.username = @"test_username"; + config.password = @"test_password"; + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", config.username, config.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + XCTAssertEqualObjects(basicAuthCredentials, [config getBasicAuthToken]); +} + @end diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index 6ac776ab37a..48b1f809658 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -20,7 +20,7 @@ PODS: - AFNetworking/UIKit (2.5.4): - AFNetworking/NSURLConnection - AFNetworking/NSURLSession - - ISO8601 (0.2.0) + - ISO8601 (0.3.0) - JSONModel (1.1.0) DEPENDENCIES: @@ -30,7 +30,7 @@ DEPENDENCIES: SPEC CHECKSUMS: AFNetworking: 05edc0ac4c4c8cf57bcf4b84be5b0744b6d8e71e - ISO8601: 962282de75074c38bbfaa7b133b0e743ed6deb8d + ISO8601: 8d8a22d5edf0554a1cf75bac028c76c1dc0ffaef JSONModel: ec77e9865236a7a09d9cf7668df6b4b328d9ec1d COCOAPODS: 0.37.1 diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index cd6f52db5c6..d1f9203f180 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -54,11 +54,16 @@ extern NSString *const SWGResponseObjectErrorKey; -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey; +- (void) updateHeaderParams:(NSDictionary **)headers + queryParams:(NSDictionary **)querys + WithAuthSettings:(NSArray *)authSettings; + -(NSNumber*) dictionary:(NSString*) path method:(NSString*) method queryParams:(NSDictionary*) queryParams body:(id) body headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType:(NSString*) requestContentType responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; @@ -68,8 +73,18 @@ extern NSString *const SWGResponseObjectErrorKey; queryParams:(NSDictionary*) queryParams body:(id) body headerParams:(NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType:(NSString*) requestContentType responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSString*, NSError *))completionBlock; @end + + + + + + + + + diff --git a/samples/client/petstore/objc/client/SWGApiClient.m b/samples/client/petstore/objc/client/SWGApiClient.m index b38b02e0e03..5e2985bbe79 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.m +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -1,6 +1,7 @@ #import "SWGApiClient.h" #import "SWGFile.h" #import "SWGQueryParamCollection.h" +#import "SWGConfiguration.h" @implementation SWGApiClient @@ -15,10 +16,22 @@ static NSOperationQueue* sharedQueue; static void (^reachabilityChangeBlock)(int); static bool loggingEnabled = true; +#pragma mark - Log Methods + +(void)setLoggingEnabled:(bool) state { loggingEnabled = state; } +- (void)logRequest:(NSURLRequest*)request { + NSLog(@"request: %@", [self descriptionForRequest:request]); +} + +- (void)logResponse:(id)data forRequest:(NSURLRequest*)request error:(NSError*)error { + NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); +} + +#pragma mark - + +(void)clearCache { [[NSURLCache sharedURLCache] removeAllCachedResponses]; } @@ -305,19 +318,47 @@ static bool loggingEnabled = true; return [[request URL] absoluteString]; } -- (void)logRequest:(NSURLRequest*)request { - NSLog(@"request: %@", [self descriptionForRequest:request]); + +/** + * Update header and query params based on authentication settings + */ +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if (!authSettings || [authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + SWGConfiguration *config = [SWGConfiguration sharedConfig]; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; + + if (authSetting) { + if ([authSetting[@"in"] isEqualToString:@"header"]) { + [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + else if ([authSetting[@"in"] isEqualToString:@"query"]) { + [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (void)logResponse:(id)data forRequest:(NSURLRequest*)request error:(NSError*)error { - NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); -} +#pragma mark - Perform Request Methods -(NSNumber*) dictionary: (NSString*) path method: (NSString*) method queryParams: (NSDictionary*) queryParams body: (id) body headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType: (NSString*) requestContentType responseContentType: (NSString*) responseContentType completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock { @@ -342,6 +383,9 @@ static bool loggingEnabled = true; else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; NSMutableURLRequest * request = nil; if (body != nil && [body isKindOfClass:[NSArray class]]){ @@ -476,6 +520,7 @@ static bool loggingEnabled = true; queryParams: (NSDictionary*) queryParams body: (id) body headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings requestContentType: (NSString*) requestContentType responseContentType: (NSString*) responseContentType completionBlock: (void (^)(NSString*, NSError *))completionBlock { @@ -500,6 +545,9 @@ static bool loggingEnabled = true; else { self.responseSerializer = [AFHTTPResponseSerializer serializer]; } + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; NSMutableURLRequest * request = nil; if (body != nil && [body isKindOfClass:[NSArray class]]){ diff --git a/samples/client/petstore/objc/client/SWGConfiguration.h b/samples/client/petstore/objc/client/SWGConfiguration.h new file mode 100644 index 00000000000..0ddac56acdf --- /dev/null +++ b/samples/client/petstore/objc/client/SWGConfiguration.h @@ -0,0 +1,51 @@ +#import + +@interface SWGConfiguration : NSObject + + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setValue:forApiKeyField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Usename and Password for Basic type Authentication + */ +@property (nonatomic) NSString *username; +@property (nonatomic) NSString *password; + +/** + * Get configuration singleton instance + */ ++ (instancetype) sharedConfig; + +/** + * Sets field in `apiKey` + */ +- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; + +/** + * Sets field in `apiKeyPrefix` + */ +- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; + +/** + * Get API key (with prefix if set) + */ +- (NSString *) getApiKeyWithPrefix:(NSString *) key; + +/** + * Get Authentication Setings + */ +- (NSDictionary *) authSettings; + +@end diff --git a/samples/client/petstore/objc/client/SWGConfiguration.m b/samples/client/petstore/objc/client/SWGConfiguration.m new file mode 100644 index 00000000000..f98c5f081de --- /dev/null +++ b/samples/client/petstore/objc/client/SWGConfiguration.m @@ -0,0 +1,91 @@ +#import "SWGConfiguration.h" + +@interface SWGConfiguration () + +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; + +@end + +@implementation SWGConfiguration + +#pragma mark - Singletion Methods + ++ (instancetype) sharedConfig { + static SWGConfiguration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype) init { + self = [super init]; + if (self) { + self.username = @""; + self.password = @""; + self.mutableApiKey = [NSMutableDictionary dictionary]; + self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + } + return self; +} + +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { + return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + } + else if ([self.apiKey objectForKey:key]) { + return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + } + else { + return @""; + } +} + +#pragma mark - Setter Methods + +- (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { + [self.mutableApiKey setValue:value forKey:field]; +} + +- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field { + [self.mutableApiKeyPrefix setValue:value forKey:field]; +} + +#pragma mark - Getter Methods + +- (NSDictionary *) apiKey { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; +} + +- (NSDictionary *) apiKeyPrefix { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{ + @"api_key": @{ + @"type": @"api_key", + @"in": @"header", + @"key": @"api_key", + @"value": [self getApiKeyWithPrefix:@"api_key"] + }, + + @"basic_auth": @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, + + }; +} + +@end diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 9487713984b..0b2c059fb3b 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -38,6 +38,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return self; } +#pragma mark - + +(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGPetApi* singletonAPI = nil; @@ -115,6 +117,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + id bodyDictionary = nil; id __body = body; @@ -160,6 +165,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -218,6 +224,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; + // Authentication setting + NSArray *authSettings = @[@"basic_auth"]; + id bodyDictionary = nil; id __body = body; @@ -263,6 +272,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -327,6 +337,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + id bodyDictionary = nil; @@ -346,6 +359,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -427,6 +441,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + id bodyDictionary = nil; @@ -446,6 +463,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -525,6 +543,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + id bodyDictionary = nil; @@ -552,6 +573,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -627,6 +649,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/x-www-form-urlencoded"]]; + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + id bodyDictionary = nil; @@ -665,6 +690,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -731,6 +757,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + id bodyDictionary = nil; @@ -753,6 +782,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -819,6 +849,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"multipart/form-data"]]; + // Authentication setting + NSArray *authSettings = @[@"petstore_auth"]; + id bodyDictionary = nil; @@ -864,6 +897,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { diff --git a/samples/client/petstore/objc/client/SWGQueryParamCollection.m b/samples/client/petstore/objc/client/SWGQueryParamCollection.m index 9ce319940dd..83303045185 100644 --- a/samples/client/petstore/objc/client/SWGQueryParamCollection.m +++ b/samples/client/petstore/objc/client/SWGQueryParamCollection.m @@ -13,4 +13,4 @@ return self; } -@end \ No newline at end of file +@end diff --git a/samples/client/petstore/objc/client/SWGStoreApi.h b/samples/client/petstore/objc/client/SWGStoreApi.h index c2d0dd6b36b..49d8db806c8 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -8,6 +8,7 @@ @property(nonatomic, assign)SWGApiClient *apiClient; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index 98b9d9a4eec..a112db6d639 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -37,6 +37,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return self; } +#pragma mark - + +(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGStoreApi* singletonAPI = nil; @@ -112,6 +114,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[@"api_key"]; + id bodyDictionary = nil; @@ -131,6 +136,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -199,6 +205,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; id __body = body; @@ -249,6 +258,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -320,6 +330,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; @@ -347,6 +360,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -418,6 +432,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; @@ -440,6 +457,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { diff --git a/samples/client/petstore/objc/client/SWGUserApi.h b/samples/client/petstore/objc/client/SWGUserApi.h index d9d5a8abc18..e6e73ddfba6 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.h +++ b/samples/client/petstore/objc/client/SWGUserApi.h @@ -8,6 +8,7 @@ @property(nonatomic, assign)SWGApiClient *apiClient; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index 97a79f01b6d..e2fe69aca8d 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -37,6 +37,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return self; } +#pragma mark - + +(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static SWGUserApi* singletonAPI = nil; @@ -114,6 +116,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; id __body = body; @@ -159,6 +164,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -217,6 +223,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; id __body = body; @@ -262,6 +271,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -320,6 +330,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; id __body = body; @@ -365,6 +378,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -433,6 +447,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; @@ -457,6 +474,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -524,6 +542,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; @@ -546,6 +567,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -608,6 +630,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; @@ -635,6 +660,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSDictionary *data, NSError *error) { @@ -708,6 +734,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; id __body = body; @@ -753,6 +782,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { @@ -815,6 +845,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; // request content type NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[]]; + // Authentication setting + NSArray *authSettings = @[]; + id bodyDictionary = nil; @@ -837,6 +870,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; queryParams: queryParams body: bodyDictionary headerParams: headerParams + authSettings: authSettings requestContentType: requestContentType responseContentType: responseContentType completionBlock: ^(NSString *data, NSError *error) { From 83d069d05341c9136221b340cf958a9ce54a8745 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 31 May 2015 09:49:24 +0800 Subject: [PATCH 11/41] add support for obj, remove null from serialized json string --- .../codegen/languages/PhpClientCodegen.java | 1 + .../src/main/resources/php/APIClient.mustache | 6 +++-- .../php/SwaggerClient-php/lib/APIClient.php | 4 +++- samples/client/petstore/php/test.php | 24 +++++++++++++++++++ 4 files changed, 32 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java index 55d358154f8..9d29baffbe2 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -82,6 +82,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("map", "map"); typeMapping.put("array", "array"); typeMapping.put("list", "array"); + typeMapping.put("object", "object"); supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); supportingFiles.add(new SupportingFile("configuration.mustache", packagePath + "/lib", "Configuration.php")); diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 70717056b9e..9d360b6482a 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -278,7 +278,9 @@ class APIClient { } else if (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); + if ($data->$property !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); + } } $sanitized = $values; } else { @@ -383,7 +385,7 @@ class APIClient { $deserialized = $values; } elseif ($class == 'DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool'))) { + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; } else { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index f7002fba18d..44766040a7a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -283,7 +283,9 @@ class APIClient { } else if (is_object($data)) { $values = array(); foreach (array_keys($data::$swaggerTypes) as $property) { - $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); + if ($data->$property !== null) { + $values[$data::$attributeMap[$property]] = $this->sanitizeForSerialization($data->$property); + } } $sanitized = $values; } else { diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 41c206ee6b0..78f8b225665 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -8,13 +8,37 @@ require_once('SwaggerClient-php/SwaggerClient.php'); $petId = 10005; // ID of pet that needs to be fetched try { + // get pet by id //$pet_api = new SwaggerClient\PetAPI($api_client); $pet_api = new SwaggerClient\PetAPI(); // return Pet (model) $response = $pet_api->getPetById($petId); var_dump($response); + + // add pet (post json) + $new_pet_id = 10005; + $new_pet = new SwaggerClient\models\Pet; + $new_pet->id = $new_pet_id; + $new_pet->name = "PHP Unit Test"; + // new tag + $tag= new SwaggerClient\models\Tag; + $tag->id = $new_pet_id; // use the same id as pet + //$tag->name = "test php tag"; + // new category + $category = new SwaggerClient\models\Category; + $category->id = 0; // use the same id as pet + //$category->name = "test php category"; + + $new_pet->tags = array($tag); + $new_pet->category = $category; + + $pet_api = new SwaggerClient\PetAPI(); + // add a new pet (model) + $add_response = $pet_api->addPet($new_pet); + } catch (Exception $e) { echo 'Caught exception: ', $e->getMessage(), "\n"; } + ?> From 8d708c2442b7f1c3760cde84a85acfe4f2e35daf Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 31 May 2015 11:17:59 +0800 Subject: [PATCH 12/41] add test case for default header --- .../src/main/resources/php/APIClient.mustache | 2 +- .../petstore/php/SwaggerClient-php/lib/APIClient.php | 11 ++++------- samples/client/petstore/php/test.php | 4 ++++ 3 files changed, 9 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 9d360b6482a..aa85a2b1a37 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -182,7 +182,7 @@ class APIClient { $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); # construct the http header - if ($headerParams != null) { + if ($headerParams !== null) { # add default header $headerParams = array_merge((array)self::$default_header, $headerParams); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 44766040a7a..de75c7252e1 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -187,13 +187,10 @@ class APIClient { $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); # construct the http header - if ($headerParams != null) { - # add default header - $headerParams = array_merge((array)self::$default_header, $headerParams); + $headerParams = array_merge((array)self::$default_header, (array)$headerParams); - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; } // form data @@ -390,7 +387,7 @@ class APIClient { $deserialized = $values; } elseif ($class == 'DateTime') { $deserialized = new \DateTime($data); - } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool'))) { + } elseif (in_array($class, array('string', 'int', 'float', 'double', 'bool', 'object'))) { settype($data, $class); $deserialized = $data; } else { diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 78f8b225665..7bc755f72e6 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -2,6 +2,8 @@ //require_once('vendor/autoload.php'); require_once('SwaggerClient-php/SwaggerClient.php'); +$c = array_merge((array)$a, (array)$b); + // initialize the API client //$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); //$api_client->addDefaultHeader("test1", "value1"); @@ -11,6 +13,8 @@ try { // get pet by id //$pet_api = new SwaggerClient\PetAPI($api_client); $pet_api = new SwaggerClient\PetAPI(); + // test default header + $pet_api->getApiClient()->addDefaultHeader("TEST_API_KEY", "09182sdkanafndsl903"); // return Pet (model) $response = $pet_api->getPetById($petId); var_dump($response); From f357f4c9d75fae5ebf40729b9bfdb74e80733e9b Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 1 Jun 2015 14:24:09 +0800 Subject: [PATCH 13/41] fix default header --- .../src/main/resources/php/APIClient.mustache | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index aa85a2b1a37..cbde8987da9 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -182,13 +182,10 @@ class APIClient { $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); # construct the http header - if ($headerParams !== null) { - # add default header - $headerParams = array_merge((array)self::$default_header, $headerParams); + $headerParams = array_merge((array)self::$default_header, (array)$headerParams); - foreach ($headerParams as $key => $val) { - $headers[] = "$key: $val"; - } + foreach ($headerParams as $key => $val) { + $headers[] = "$key: $val"; } // form data From 762a3279ea68a6124073112b2ff5b840524e41de Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 1 Jun 2015 14:50:57 +0800 Subject: [PATCH 14/41] clean up test.php --- samples/client/petstore/php/test.php | 2 -- 1 file changed, 2 deletions(-) diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 7bc755f72e6..de5f4ba3f12 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -2,8 +2,6 @@ //require_once('vendor/autoload.php'); require_once('SwaggerClient-php/SwaggerClient.php'); -$c = array_merge((array)$a, (array)$b); - // initialize the API client //$api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); //$api_client->addDefaultHeader("test1", "value1"); From 86971ee752842bee8dba1bd5965e92168c690783 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 2 Jun 2015 11:50:47 +0800 Subject: [PATCH 15/41] added comments for objc client --- .../src/main/resources/objc/SWGApiClient.h | 77 ++++++++++++++++--- .../petstore/objc/client/SWGApiClient.h | 77 ++++++++++++++++--- .../petstore/objc/client/SWGConfiguration.m | 7 -- .../client/petstore/objc/client/SWGPetApi.m | 2 +- 4 files changed, 133 insertions(+), 30 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h index d1f9203f180..fa48aa70965 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h @@ -3,7 +3,7 @@ /** * A key for `NSError` user info dictionaries. - * + * * The corresponding value is the parsed response body for an HTTP error. */ extern NSString *const SWGResponseObjectErrorKey; @@ -20,44 +20,104 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, assign) BOOL logHTTP; @property(nonatomic, readonly) NSOperationQueue* queue; +/** + * Get the Api Client instance from pool + */ +(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; +/** + * Get the operations queue + */ +(NSOperationQueue*) sharedQueue; +/** + * Turn on logging + */ +(void)setLoggingEnabled:(bool) state; +/** + * Clear Cache + */ +(void)clearCache; +/** + * Turn on cache + */ +(void)setCacheEnabled:(BOOL) enabled; +/** + * Get the request queue size + */ +(unsigned long)requestQueueSize; +/** + * Set the client unreachable + */ +(void) setOfflineState:(BOOL) state; +/** + * Get the client reachability + */ +(AFNetworkReachabilityStatus) getReachabilityStatus; +/** + * Get the next request id + */ +(NSNumber*) nextRequestId; +/** + * Generate request id and add it to the queue + */ +(NSNumber*) queueRequest; +/** + * Remove request id from the queue + */ +(void) cancelRequest:(NSNumber*)requestId; +/** + * URL encode NSString + */ +(NSString*) escape:(id)unescaped; +/** + * Set the client reachability + */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; +/** + * Set the client reachability strategy + */ +(void) configureCacheReachibilityForHost:(NSString*)host; +/** + * Detect Accept header from accepts NSArray + */ +(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detect Content-Type header from contentTypes NSArray + */ +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; +/** + * Set header for request + */ -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey; +/** + * Update header parameters and query parameters for authentication + */ - (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; +/** + * Perform request + * + * @discussion Request with non-empty response + */ -(NSNumber*) dictionary:(NSString*) path method:(NSString*) method queryParams:(NSDictionary*) queryParams @@ -68,6 +128,11 @@ extern NSString *const SWGResponseObjectErrorKey; responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; +/** + * Perform request + * + * @discussion Request with empty response + */ -(NSNumber*) stringWithCompletionBlock:(NSString*) path method:(NSString*) method queryParams:(NSDictionary*) queryParams @@ -78,13 +143,3 @@ extern NSString *const SWGResponseObjectErrorKey; responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSString*, NSError *))completionBlock; @end - - - - - - - - - - diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index d1f9203f180..fa48aa70965 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -3,7 +3,7 @@ /** * A key for `NSError` user info dictionaries. - * + * * The corresponding value is the parsed response body for an HTTP error. */ extern NSString *const SWGResponseObjectErrorKey; @@ -20,44 +20,104 @@ extern NSString *const SWGResponseObjectErrorKey; @property(nonatomic, assign) BOOL logHTTP; @property(nonatomic, readonly) NSOperationQueue* queue; +/** + * Get the Api Client instance from pool + */ +(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; +/** + * Get the operations queue + */ +(NSOperationQueue*) sharedQueue; +/** + * Turn on logging + */ +(void)setLoggingEnabled:(bool) state; +/** + * Clear Cache + */ +(void)clearCache; +/** + * Turn on cache + */ +(void)setCacheEnabled:(BOOL) enabled; +/** + * Get the request queue size + */ +(unsigned long)requestQueueSize; +/** + * Set the client unreachable + */ +(void) setOfflineState:(BOOL) state; +/** + * Get the client reachability + */ +(AFNetworkReachabilityStatus) getReachabilityStatus; +/** + * Get the next request id + */ +(NSNumber*) nextRequestId; +/** + * Generate request id and add it to the queue + */ +(NSNumber*) queueRequest; +/** + * Remove request id from the queue + */ +(void) cancelRequest:(NSNumber*)requestId; +/** + * URL encode NSString + */ +(NSString*) escape:(id)unescaped; +/** + * Set the client reachability + */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; +/** + * Set the client reachability strategy + */ +(void) configureCacheReachibilityForHost:(NSString*)host; +/** + * Detect Accept header from accepts NSArray + */ +(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detect Content-Type header from contentTypes NSArray + */ +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; +/** + * Set header for request + */ -(void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey; +/** + * Update header parameters and query parameters for authentication + */ - (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; +/** + * Perform request + * + * @discussion Request with non-empty response + */ -(NSNumber*) dictionary:(NSString*) path method:(NSString*) method queryParams:(NSDictionary*) queryParams @@ -68,6 +128,11 @@ extern NSString *const SWGResponseObjectErrorKey; responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; +/** + * Perform request + * + * @discussion Request with empty response + */ -(NSNumber*) stringWithCompletionBlock:(NSString*) path method:(NSString*) method queryParams:(NSDictionary*) queryParams @@ -78,13 +143,3 @@ extern NSString *const SWGResponseObjectErrorKey; responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSString*, NSError *))completionBlock; @end - - - - - - - - - - diff --git a/samples/client/petstore/objc/client/SWGConfiguration.m b/samples/client/petstore/objc/client/SWGConfiguration.m index f98c5f081de..0c477edbfc5 100644 --- a/samples/client/petstore/objc/client/SWGConfiguration.m +++ b/samples/client/petstore/objc/client/SWGConfiguration.m @@ -78,13 +78,6 @@ @"value": [self getApiKeyWithPrefix:@"api_key"] }, - @"basic_auth": @{ - @"type": @"basic", - @"in": @"header", - @"key": @"Authorization", - @"value": [self getBasicAuthToken] - }, - }; } diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 0b2c059fb3b..c14da125af5 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -225,7 +225,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; NSString *requestContentType = [SWGApiClient selectHeaderContentType:@[@"application/json", @"application/xml"]]; // Authentication setting - NSArray *authSettings = @[@"basic_auth"]; + NSArray *authSettings = @[@"petstore_auth"]; id bodyDictionary = nil; From 699df0029be55ef354437a1766b7f40d2321109d Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 2 Jun 2015 15:33:33 +0800 Subject: [PATCH 16/41] updated comments for objc client. --- .../src/main/resources/objc/SWGApiClient.h | 79 ++++++++++++++++++- .../objc/SWGConfiguration-body.mustache | 8 ++ .../objc/SWGConfiguration-header.mustache | 5 ++ .../petstore/objc/client/SWGApiClient.h | 79 ++++++++++++++++++- .../petstore/objc/client/SWGConfiguration.h | 5 ++ .../petstore/objc/client/SWGConfiguration.m | 8 ++ 6 files changed, 176 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h index fa48aa70965..250811c4016 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h +++ b/modules/swagger-codegen/src/main/resources/objc/SWGApiClient.h @@ -22,16 +22,24 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Get the Api Client instance from pool + * + * @param baseUrl The base url of api client. + * + * @return The SWGApiClient instance. */ +(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; /** * Get the operations queue + * + * @return The `shardQueue` static variable. */ +(NSOperationQueue*) sharedQueue; /** * Turn on logging + * + * @param state logging state, must be `YES` or `NO` */ +(void)setLoggingEnabled:(bool) state; @@ -42,72 +50,109 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Turn on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** * Get the request queue size + * + * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** * Set the client unreachable + * + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** * Get the client reachability + * + * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** * Get the next request id + * + * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** * Generate request id and add it to the queue + * + * @return The next executed request id. */ +(NSNumber*) queueRequest; /** * Remove request id from the queue + * + * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** * URL encode NSString + * + * @param unescaped The string which will be escaped. + * + * @return The escaped string. */ +(NSString*) escape:(id)unescaped; /** - * Set the client reachability + * Customize the behavior when the reachability changed + * + * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** * Set the client reachability strategy + * + * @param host The host of SWGApiClient. */ +(void) configureCacheReachibilityForHost:(NSString*)host; /** * Detect Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header */ +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** * Detect Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header */ +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** * Set header for request + * + * @param value The header value + * @param forKey The header key */ -(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; + forKey:(NSString*) forKey; /** * Update header parameters and query parameters for authentication + * + * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param querys The query parameters will be updated, passed by pointer to pointer. + * @param authSettings The authentication names NSArray. */ - (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys @@ -116,7 +161,19 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Perform request * - * @discussion Request with non-empty response + * Request with non-empty response + * + * @param path Request url. + * @param method Request method. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The request id. */ -(NSNumber*) dictionary:(NSString*) path method:(NSString*) method @@ -131,7 +188,19 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Perform request * - * @discussion Request with empty response + * Request with empty response + * + * @param path Request url. + * @param method Request method. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The request id. */ -(NSNumber*) stringWithCompletionBlock:(NSString*) path method:(NSString*) method @@ -143,3 +212,5 @@ extern NSString *const SWGResponseObjectErrorKey; responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSString*, NSError *))completionBlock; @end + + diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache index b326244fe0a..1e5e7135574 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-body.mustache @@ -47,6 +47,14 @@ } } +- (NSString *) getBasicAuthToken { + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + #pragma mark - Setter Methods - (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache index 0ddac56acdf..33023ca3c6f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/SWGConfiguration-header.mustache @@ -43,6 +43,11 @@ */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; +/** + * Get Basic Auth token + */ +- (NSString *) getBasicAuthToken; + /** * Get Authentication Setings */ diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h index fa48aa70965..250811c4016 100644 --- a/samples/client/petstore/objc/client/SWGApiClient.h +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -22,16 +22,24 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Get the Api Client instance from pool + * + * @param baseUrl The base url of api client. + * + * @return The SWGApiClient instance. */ +(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; /** * Get the operations queue + * + * @return The `shardQueue` static variable. */ +(NSOperationQueue*) sharedQueue; /** * Turn on logging + * + * @param state logging state, must be `YES` or `NO` */ +(void)setLoggingEnabled:(bool) state; @@ -42,72 +50,109 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Turn on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` */ +(void)setCacheEnabled:(BOOL) enabled; /** * Get the request queue size + * + * @return The size of `queuedRequests` static variable. */ +(unsigned long)requestQueueSize; /** * Set the client unreachable + * + * @param state off line state, must be `YES` or `NO` */ +(void) setOfflineState:(BOOL) state; /** * Get the client reachability + * + * @return The client reachability. */ +(AFNetworkReachabilityStatus) getReachabilityStatus; /** * Get the next request id + * + * @return The next executed request id. */ +(NSNumber*) nextRequestId; /** * Generate request id and add it to the queue + * + * @return The next executed request id. */ +(NSNumber*) queueRequest; /** * Remove request id from the queue + * + * @param requestId The request which will be removed. */ +(void) cancelRequest:(NSNumber*)requestId; /** * URL encode NSString + * + * @param unescaped The string which will be escaped. + * + * @return The escaped string. */ +(NSString*) escape:(id)unescaped; /** - * Set the client reachability + * Customize the behavior when the reachability changed + * + * @param changeBlock The block will be executed when the reachability changed. */ +(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; /** * Set the client reachability strategy + * + * @param host The host of SWGApiClient. */ +(void) configureCacheReachibilityForHost:(NSString*)host; /** * Detect Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header */ +(NSString *) selectHeaderAccept:(NSArray *)accepts; /** * Detect Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header */ +(NSString *) selectHeaderContentType:(NSArray *)contentTypes; /** * Set header for request + * + * @param value The header value + * @param forKey The header key */ -(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; + forKey:(NSString*) forKey; /** * Update header parameters and query parameters for authentication + * + * @param headers The header parameter will be udpated, passed by pointer to pointer. + * @param querys The query parameters will be updated, passed by pointer to pointer. + * @param authSettings The authentication names NSArray. */ - (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys @@ -116,7 +161,19 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Perform request * - * @discussion Request with non-empty response + * Request with non-empty response + * + * @param path Request url. + * @param method Request method. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The request id. */ -(NSNumber*) dictionary:(NSString*) path method:(NSString*) method @@ -131,7 +188,19 @@ extern NSString *const SWGResponseObjectErrorKey; /** * Perform request * - * @discussion Request with empty response + * Request with empty response + * + * @param path Request url. + * @param method Request method. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The request id. */ -(NSNumber*) stringWithCompletionBlock:(NSString*) path method:(NSString*) method @@ -143,3 +212,5 @@ extern NSString *const SWGResponseObjectErrorKey; responseContentType:(NSString*) responseContentType completionBlock:(void (^)(NSString*, NSError *))completionBlock; @end + + diff --git a/samples/client/petstore/objc/client/SWGConfiguration.h b/samples/client/petstore/objc/client/SWGConfiguration.h index 0ddac56acdf..33023ca3c6f 100644 --- a/samples/client/petstore/objc/client/SWGConfiguration.h +++ b/samples/client/petstore/objc/client/SWGConfiguration.h @@ -43,6 +43,11 @@ */ - (NSString *) getApiKeyWithPrefix:(NSString *) key; +/** + * Get Basic Auth token + */ +- (NSString *) getBasicAuthToken; + /** * Get Authentication Setings */ diff --git a/samples/client/petstore/objc/client/SWGConfiguration.m b/samples/client/petstore/objc/client/SWGConfiguration.m index 0c477edbfc5..89d5a597946 100644 --- a/samples/client/petstore/objc/client/SWGConfiguration.m +++ b/samples/client/petstore/objc/client/SWGConfiguration.m @@ -47,6 +47,14 @@ } } +- (NSString *) getBasicAuthToken { + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + #pragma mark - Setter Methods - (void) setValue:(NSString *)value forApiKeyField:(NSString *)field { From 1a75489b42d2be4ae6884d1b58421f54c538e7db Mon Sep 17 00:00:00 2001 From: Andrew B Date: Tue, 2 Jun 2015 09:04:50 -0700 Subject: [PATCH 17/41] Enabling cli config options for android generator --- .../languages/AndroidClientCodegen.java | 117 +++++++++++++++--- .../resources/android-java/build.mustache | 4 +- .../resources/android-java/jsonUtil.mustache | 2 +- 3 files changed, 100 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java index 62fc70efdea..377c8de24d9 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -47,26 +47,6 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi "native", "super", "while") ); - additionalProperties.put("invokerPackage", invokerPackage); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); - - supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); - additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); - - 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")); - supportingFiles.add(new SupportingFile("apiInvoker.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); - supportingFiles.add(new SupportingFile("httpPatch.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java")); - supportingFiles.add(new SupportingFile("jsonUtil.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); - supportingFiles.add(new SupportingFile("apiException.mustache", - (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); - languageSpecificPrimitives = new HashSet( Arrays.asList( "String", @@ -80,6 +60,13 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi ); instantiationTypes.put("array", "ArrayList"); instantiationTypes.put("map", "HashMap"); + + cliOptions.add(new CliOption("invokerPackage", "root package to use for the generated code")); + cliOptions.add(new CliOption("groupId", "groupId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption("artifactId", "artifactId for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption("artifactVersion", "artifact version for use in the generated build.gradle and pom.xml")); + cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); + cliOptions.add(new CliOption("useAndroidMavenGradlePlugin", "A flag to toggle android-maven gradle plugin. Default is true.")); } @Override @@ -177,6 +164,96 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi return camelize(operationId, true); } + + @Override + public void processOpts() { + super.processOpts(); + + if(additionalProperties.containsKey("invokerPackage")) { + this.setInvokerPackage((String)additionalProperties.get("invokerPackage")); + } + else{ + //not set, use default to be passed to template + additionalProperties.put("invokerPackage", invokerPackage); + } + + if(additionalProperties.containsKey("groupId")) { + this.setGroupId((String)additionalProperties.get("groupId")); + } + else{ + //not set, use to be passed to template + additionalProperties.put("groupId", groupId); + } + + if(additionalProperties.containsKey("artifactId")) { + this.setArtifactId((String)additionalProperties.get("artifactId")); + } + else{ + //not set, use to be passed to template + additionalProperties.put("artifactId", artifactId); + } + + if(additionalProperties.containsKey("artifactVersion")) { + this.setArtifactVersion((String)additionalProperties.get("artifactVersion")); + } + else{ + //not set, use to be passed to template + additionalProperties.put("artifactVersion", artifactVersion); + } + + if(additionalProperties.containsKey("sourceFolder")) { + this.setSourceFolder((String)additionalProperties.get("sourceFolder")); + } + if(additionalProperties.containsKey("useAndroidMavenGradlePlugin")) { + this.setUseAndroidMavenGradlePlugin((Boolean)additionalProperties.get("useAndroidMavenGradlePlugin")); + } + else{ + additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + } + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + + 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")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiInvoker.java")); + supportingFiles.add(new SupportingFile("httpPatch.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "HttpPatch.java")); + supportingFiles.add(new SupportingFile("jsonUtil.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "JsonUtil.java")); + supportingFiles.add(new SupportingFile("apiException.mustache", + (sourceFolder + File.separator + invokerPackage).replace(".", java.io.File.separator), "ApiException.java")); + } + + public Boolean getUseAndroidMavenGradlePlugin() { + return useAndroidMavenGradlePlugin; + } + + public void setUseAndroidMavenGradlePlugin(Boolean useAndroidMavenGradlePlugin) { + this.useAndroidMavenGradlePlugin = useAndroidMavenGradlePlugin; + } + + public void setInvokerPackage(String invokerPackage) { + this.invokerPackage = invokerPackage; + } + + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + public void setArtifactId(String artifactId) { + this.artifactId = artifactId; + } + + public void setArtifactVersion(String artifactVersion) { + this.artifactVersion = artifactVersion; + } + + public void setSourceFolder(String sourceFolder) { + this.sourceFolder = sourceFolder; + } } diff --git a/modules/swagger-codegen/src/main/resources/android-java/build.mustache b/modules/swagger-codegen/src/main/resources/android-java/build.mustache index 62a56bf066e..66fcef2a371 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -60,10 +60,10 @@ dependencies { compile "com.google.code.gson:gson:$gson_version" compile "org.apache.httpcomponents:httpcore:$httpclient_version" compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { + compile ("org.apache.httpcomponents:httpcore:$httpclient_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } - compile ("org.apache.httpcomponents:httpmime:$httpmime_version") { + compile ("org.apache.httpcomponents:httpmime:$httpclient_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } testCompile "junit:junit:$junit_version" diff --git a/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache b/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache index 3a6ff4111d1..ae8d18d3731 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/jsonUtil.mustache @@ -5,7 +5,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; -import io.swagger.client.model.*; +import {{modelPackage}}.*; public class JsonUtil { public static GsonBuilder gsonBuilder; From 217765998dcc6d3154309ce5f15f85144ae7b039 Mon Sep 17 00:00:00 2001 From: Fredrik Gustafsson Date: Wed, 3 Jun 2015 16:23:45 +0200 Subject: [PATCH 18/41] Extended the APIException by ErrorContent from response body --- .../swagger-codegen/src/main/resources/csharp/api.mustache | 4 ++-- .../src/main/resources/csharp/apiException.mustache | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index bf7da6efdb8..7d69bea2488 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -83,7 +83,7 @@ namespace {{package}} { // make the HTTP request IRestResponse response = restClient.Execute(_request); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); } {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} @@ -125,7 +125,7 @@ namespace {{package}} { // make the HTTP request IRestResponse response = await restClient.ExecuteTaskAsync(_request); if (((int)response.StatusCode) >= 400) { - throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content, response.Content); } {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache index f28eb8de6f7..5b2509d0f0b 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -6,12 +6,19 @@ namespace {{invokerPackage}} { public int ErrorCode { get; set; } + public dynamic ErrorContent { get; private set; } + public ApiException() {} public ApiException(int errorCode, string message) : base(message) { this.ErrorCode = errorCode; } + public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { + this.errorCode = errorCode; + this.errorContent = errorContent; + } + } } From 58feda7c8e075d6f41f003ee86aaf42bfd80b004 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 4 Jun 2015 16:44:12 +0800 Subject: [PATCH 19/41] Updated test case `testCreateAndGetPet` of objc client. --- .../PetstoreClientTests/PetApiTest.m | 30 ++++++++++++++++++- 1 file changed, 29 insertions(+), 1 deletion(-) diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m index 6fb2b6e57c2..32625dce467 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m @@ -27,6 +27,24 @@ } if(output){ XCTAssertNotNil([output _id], @"token was nil"); + + // test category of pet is correct + XCTAssertEqualObjects(output.category._id, pet.category._id); + XCTAssertEqualObjects(output.category.name, pet.category.name); + + // test tags of pet is correct + XCTAssertTrue([output.tags isKindOfClass:[NSArray class]]); + [pet.tags enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + SWGTag *foundTag = [[SWGTag alloc] init]; + for (SWGTag *tag in output.tags) { + if ([tag _id] == [obj _id]) { + foundTag = tag; + } + } + XCTAssertNotNil(foundTag); + XCTAssertEqualObjects([foundTag _id], [obj _id]); + XCTAssertEqualObjects([foundTag name], [obj name]); + }]; } [expectation fulfill]; }]; @@ -221,10 +239,20 @@ SWGPet * pet = [[SWGPet alloc] init]; pet._id = [[NSNumber alloc] initWithLong:[[NSDate date] timeIntervalSince1970]]; pet.name = @"monkey"; + SWGCategory * category = [[SWGCategory alloc] init]; + category._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; category.name = @"super-happy"; - pet.category = category; + + SWGTag *tag1 = [[SWGTag alloc] init]; + tag1._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag1.name = @"test tag 1"; + SWGTag *tag2 = [[SWGTag alloc] init]; + tag2._id = [[NSNumber alloc] initWithInteger:arc4random_uniform(100000)]; + tag2.name = @"test tag 2"; + pet.tags = (NSArray *)[[NSArray alloc] initWithObjects:tag1, tag2, nil]; + pet.status = @"available"; NSArray * photos = [[NSArray alloc] initWithObjects:@"http://foo.bar.com/3", @"http://foo.bar.com/4", nil]; From 0ca97e4b68444636d0233ffa97bdfa59eff64219 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 27 May 2015 11:06:52 +0800 Subject: [PATCH 20/41] added authentication for python client. Not completed --- .../src/main/resources/python/config.mustache | 10 ++------ .../main/resources/python/swagger.mustache | 23 ++++++++++++++++++- 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/config.mustache b/modules/swagger-codegen/src/main/resources/python/config.mustache index e8c36aee77b..3063b4ff026 100644 --- a/modules/swagger-codegen/src/main/resources/python/config.mustache +++ b/modules/swagger-codegen/src/main/resources/python/config.mustache @@ -1,8 +1,2 @@ -from __future__ import absolute_import - -from .swagger import ApiClient - -# Configuration variables - -api_client = ApiClient("{{basePath}}") - +# Default Base url +HOST = "{{basePath}}" diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 21430c469c8..b97d4ed515a 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -28,6 +28,7 @@ except ImportError: # for python2 from urllib import quote +from . import config class ApiClient(object): """ @@ -37,7 +38,7 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API :param header_value: a header value to pass when making calls to the API """ - def __init__(self, host=None, header_name=None, header_value=None): + def __init__(self, host=config.HOST, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -279,3 +280,23 @@ class ApiClient(object): return 'application/json' else: return content_types[0] + + def get_api_key_with_prefix(api_key): + """ + Get API key (with prefix if possible) + """ + if config.api_prefix[api_key]: + return config.api_prefix[api_key] + config.api_key[api_key] + else: + return config.api_key[api_key] + + def update_params_for_auth(headers, querys, auths): + """ + Update header and query params based on authentication setting + """ + auths_map = { + {{#authMethods}} + + {{/authMethods}} + } + From b09250ed333857f30c503fc6028d60371712a325 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 27 May 2015 17:07:43 +0800 Subject: [PATCH 21/41] added authentication for python client. completed. --- .../src/main/resources/python/api.mustache | 5 +- .../src/main/resources/python/config.mustache | 49 ++++++++++++++++++- .../main/resources/python/swagger.mustache | 36 +++++++------- .../SwaggerPetstore/apis/pet_api.py | 40 ++++++++++++--- .../SwaggerPetstore/apis/store_api.py | 20 ++++++-- .../SwaggerPetstore/apis/user_api.py | 40 ++++++++++++--- .../SwaggerPetstore/config.py | 40 +++++++++++++-- .../SwaggerPetstore/swagger.py | 27 +++++++++- .../tests/test_api_client.py | 26 ++++++++++ 9 files changed, 238 insertions(+), 45 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index d5e24398f0e..55bfd9e82a4 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -81,9 +81,12 @@ class {{classname}}(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}]) + # Authentication setting + auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}) + response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}, auth_settings=auth_settings) {{#returnType}} return response {{/returnType}}{{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/python/config.mustache b/modules/swagger-codegen/src/main/resources/python/config.mustache index 3063b4ff026..a6de7299cba 100644 --- a/modules/swagger-codegen/src/main/resources/python/config.mustache +++ b/modules/swagger-codegen/src/main/resources/python/config.mustache @@ -1,2 +1,49 @@ +import base64 + + +def get_api_key_with_prefix(key): + global api_key + global api_key_prefix + + if api_key_prefix[key]: + return api_key_prefix[key] + ' ' + api_key[key] + else: + return api_key[key] + +def get_basic_auth_token(): + global username + global password + + return base64.base64encode('Basic ' + username + password) + +def auth_settings(): + return { {{#authMethods}}{{#isApiKey}} + '{{name}}': { + 'type': 'api_key', + 'in': {{#isKeyInHeader}}'header'{{/isKeyInHeader}}{{#isKeyInQuery}}'query'{{/isKeyInQuery}}, + 'key': '{{keyParamName}}', + 'value': get_api_key_with_prefix('{{keyParamName}}') + }, + {{/isApiKey}}{{#isBasic}} + '{{name}}': { + 'type': 'basic', + 'in': 'header', + 'key': 'Authorization', + 'value': get_basic_auth_token() + }, + {{/isBasic}}{{/authMethods}} + } + + + # Default Base url -HOST = "{{basePath}}" +host = "{{basePath}}" + +# Authentication settings + +api_key = {} +api_key_prefix = {} +username = '' +password = '' + + diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index b97d4ed515a..bd478820435 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -38,7 +38,7 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API :param header_value: a header value to pass when making calls to the API """ - def __init__(self, host=config.HOST, header_name=None, header_value=None): + def __init__(self, host=config.host, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -59,7 +59,7 @@ class ApiClient(object): self.default_headers[header_name] = header_value def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response=None): + body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters headers = self.default_headers.copy() @@ -86,6 +86,9 @@ class ApiClient(object): post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) + # body if body: body = self.sanitize_for_serialization(body) @@ -281,22 +284,21 @@ class ApiClient(object): else: return content_types[0] - def get_api_key_with_prefix(api_key): - """ - Get API key (with prefix if possible) - """ - if config.api_prefix[api_key]: - return config.api_prefix[api_key] + config.api_key[api_key] - else: - return config.api_key[api_key] - - def update_params_for_auth(headers, querys, auths): + def update_params_for_auth(self, headers, querys, auth_settings): """ Update header and query params based on authentication setting """ - auths_map = { - {{#authMethods}} - - {{/authMethods}} - } + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = config.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError('Authentication token must be in `query` or `header`') + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index ad4bad57412..37da9901597 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -76,9 +76,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def add_pet(self, **kwargs): """ @@ -117,9 +120,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['application/json', 'application/xml']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def find_pets_by_status(self, **kwargs): """ @@ -158,9 +164,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='list[Pet]') + response='list[Pet]', auth_settings=auth_settings) return response @@ -201,9 +210,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='list[Pet]') + response='list[Pet]', auth_settings=auth_settings) return response @@ -248,9 +260,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['api_key', 'petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='Pet') + response='Pet', auth_settings=auth_settings) return response @@ -297,9 +312,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['application/x-www-form-urlencoded']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def delete_pet(self, pet_id, **kwargs): """ @@ -343,9 +361,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def upload_file(self, pet_id, **kwargs): """ @@ -390,9 +411,12 @@ class PetApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type(['multipart/form-data']) + # Authentication setting + auth_settings = ['petstore_auth'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index e973d3a6ba5..649cb5f704d 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -75,9 +75,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = ['api_key'] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='map(String, int)') + response='map(String, int)', auth_settings=auth_settings) return response @@ -118,9 +121,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='Order') + response='Order', auth_settings=auth_settings) return response @@ -165,9 +171,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='Order') + response='Order', auth_settings=auth_settings) return response @@ -212,9 +221,12 @@ class StoreApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 82874000d59..3f2b36a85fa 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -76,9 +76,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def create_users_with_array_input(self, **kwargs): """ @@ -117,9 +120,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def create_users_with_list_input(self, **kwargs): """ @@ -158,9 +164,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def login_user(self, **kwargs): """ @@ -200,9 +209,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='str') + response='str', auth_settings=auth_settings) return response @@ -242,9 +254,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def get_user_by_name(self, username, **kwargs): """ @@ -287,9 +302,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response='User') + response='User', auth_settings=auth_settings) return response @@ -335,9 +353,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) def delete_user(self, username, **kwargs): """ @@ -380,9 +401,12 @@ class UserApi(object): # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.select_header_content_type([]) + # Authentication setting + auth_settings = [] + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, body=body_params, post_params=form_params, files=files, - response=None) + response=None, auth_settings=auth_settings) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py index 6e158eedd70..edcee6fe90b 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py @@ -1,8 +1,40 @@ -from __future__ import absolute_import +import base64 -from .swagger import ApiClient -# Configuration variables +def get_api_key_with_prefix(key): + global api_key + global api_key_prefix -api_client = ApiClient("http://petstore.swagger.io/v2") + if api_key_prefix[key]: + return api_key_prefix[key] + ' ' + api_key[key] + else: + return api_key[key] +def get_basic_auth_token(): + global username + global password + + return base64.base64encode('Basic ' + username + password) + +def auth_settings(): + return { + 'api_key': { + 'type': 'api_key', + 'in': 'header', + 'key': 'api_key', + 'value': get_api_key_with_prefix('api_key') + }, + + } + + + +# Default Base url +host = "http://petstore.swagger.io/v2" + +# Authentication settings + +api_key = {} +api_key_prefix = {} +username = '' +password = '' diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py index 21430c469c8..bd478820435 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py @@ -28,6 +28,7 @@ except ImportError: # for python2 from urllib import quote +from . import config class ApiClient(object): """ @@ -37,7 +38,7 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API :param header_value: a header value to pass when making calls to the API """ - def __init__(self, host=None, header_name=None, header_value=None): + def __init__(self, host=config.host, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -58,7 +59,7 @@ class ApiClient(object): self.default_headers[header_name] = header_value def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, response=None): + body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters headers = self.default_headers.copy() @@ -85,6 +86,9 @@ class ApiClient(object): post_params = self.prepare_post_parameters(post_params, files) post_params = self.sanitize_for_serialization(post_params) + # auth setting + self.update_params_for_auth(header_params, query_params, auth_settings) + # body if body: body = self.sanitize_for_serialization(body) @@ -279,3 +283,22 @@ class ApiClient(object): return 'application/json' else: return content_types[0] + + def update_params_for_auth(self, headers, querys, auth_settings): + """ + Update header and query params based on authentication setting + """ + if not auth_settings: + return + + for auth in auth_settings: + auth_setting = config.auth_settings().get(auth) + if auth_setting: + if auth_setting['in'] == 'header': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + querys[auth_setting['key']] = auth_setting['value'] + else: + raise ValueError('Authentication token must be in `query` or `header`') + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py index 5243430a93a..6bc3000f267 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py @@ -12,6 +12,7 @@ import time import unittest import SwaggerPetstore +import SwaggerPetstore.config HOST = 'http://petstore.swagger.io/v2' @@ -21,6 +22,31 @@ class ApiClientTests(unittest.TestCase): def setUp(self): self.api_client = SwaggerPetstore.ApiClient(HOST) + def test_configuratjion(self): + SwaggerPetstore.config.api_key['api_key'] = '123456' + SwaggerPetstore.config.api_key_prefix['api_key'] = 'PREFIX' + SwaggerPetstore.config.username = 'test_username' + SwaggerPetstore.config.password = 'test_password' + + header_params = {'test1': 'value1'} + query_params = {'test2': 'value2'} + auth_settings = ['api_key', 'unknown'] + + # test prefix + self.assertEqual('PREFIX', SwaggerPetstore.config.api_key_prefix['api_key']) + + # update parameters based on auth setting + self.api_client.update_params_for_auth(header_params, query_params, auth_settings) + + # test api key auth + self.assertEqual(header_params['test1'], 'value1') + self.assertEqual(header_params['api_key'], 'PREFIX 123456') + self.assertEqual(query_params['test2'], 'value2') + + # test basic auth + self.assertEqual('test_username', SwaggerPetstore.config.username) + self.assertEqual('test_password', SwaggerPetstore.config.password) + def test_select_header_accept(self): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] accept = self.api_client.select_header_accept(accepts) From d7aaaea0df842c9da2d7b3e8aca287c1aadde2c2 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 27 May 2015 18:37:34 +0800 Subject: [PATCH 22/41] updated config.py of python client. --- .../src/main/resources/python/config.mustache | 8 +++++--- .../src/main/resources/python/swagger.mustache | 2 +- .../SwaggerPetstore-python/SwaggerPetstore/config.py | 8 +++++--- .../SwaggerPetstore-python/SwaggerPetstore/swagger.py | 2 +- 4 files changed, 12 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/config.mustache b/modules/swagger-codegen/src/main/resources/python/config.mustache index a6de7299cba..5fb2db28329 100644 --- a/modules/swagger-codegen/src/main/resources/python/config.mustache +++ b/modules/swagger-codegen/src/main/resources/python/config.mustache @@ -1,20 +1,22 @@ import base64 +import urllib3 def get_api_key_with_prefix(key): global api_key global api_key_prefix - if api_key_prefix[key]: + if api_key.get(key) and api_key_prefix.get(key): return api_key_prefix[key] + ' ' + api_key[key] - else: + elif api_key.get(key): return api_key[key] def get_basic_auth_token(): global username global password - return base64.base64encode('Basic ' + username + password) + if username and password: + return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') def auth_settings(): return { {{#authMethods}}{{#isApiKey}} diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index bd478820435..f01192dd46b 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -87,7 +87,7 @@ class ApiClient(object): post_params = self.sanitize_for_serialization(post_params) # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) + self.update_params_for_auth(headers, query_params, auth_settings) # body if body: diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py index edcee6fe90b..ec3dbe8efb4 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py @@ -1,20 +1,22 @@ import base64 +import urllib3 def get_api_key_with_prefix(key): global api_key global api_key_prefix - if api_key_prefix[key]: + if api_key.get(key) and api_key_prefix.get(key): return api_key_prefix[key] + ' ' + api_key[key] - else: + elif api_key.get(key): return api_key[key] def get_basic_auth_token(): global username global password - return base64.base64encode('Basic ' + username + password) + if username and password: + return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') def auth_settings(): return { diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py index bd478820435..f01192dd46b 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py @@ -87,7 +87,7 @@ class ApiClient(object): post_params = self.sanitize_for_serialization(post_params) # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) + self.update_params_for_auth(headers, query_params, auth_settings) # body if body: From eac884d85b7053379a451d99e2d0a9bfdb5db9d8 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 27 May 2015 20:35:59 +0800 Subject: [PATCH 23/41] updated ApiClient of python sdk. --- .../src/main/resources/python/config.mustache | 3 +-- .../main/resources/python/swagger.mustache | 13 +++++---- .../python/SwaggerPetstore-python/.coverage | Bin 0 -> 3297 bytes .../SwaggerPetstore.egg-info/PKG-INFO | 12 +++++++++ .../SwaggerPetstore.egg-info/SOURCES.txt | 25 ++++++++++++++++++ .../dependency_links.txt | 1 + .../SwaggerPetstore.egg-info/requires.txt | 2 ++ .../SwaggerPetstore.egg-info/top_level.txt | 2 ++ .../dev-requirements.txt.log | 5 ++++ 9 files changed, 54 insertions(+), 9 deletions(-) create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/.coverage create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log diff --git a/modules/swagger-codegen/src/main/resources/python/config.mustache b/modules/swagger-codegen/src/main/resources/python/config.mustache index 5fb2db28329..928aac21edf 100644 --- a/modules/swagger-codegen/src/main/resources/python/config.mustache +++ b/modules/swagger-codegen/src/main/resources/python/config.mustache @@ -15,8 +15,7 @@ def get_basic_auth_token(): global username global password - if username and password: - return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') + return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') def auth_settings(): return { {{#authMethods}}{{#isApiKey}} diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index f01192dd46b..0483041116d 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -62,12 +62,11 @@ class ApiClient(object): body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters - headers = self.default_headers.copy() - headers.update(header_params) + headers_params = self.default_headers.copy().update(header_params) if self.cookie: - headers['Cookie'] = self.cookie - if headers: - headers = self.sanitize_for_serialization(headers) + headers_params['Cookie'] = self.cookie + if headers_params: + headers_params = ApiClient.sanitize_for_serialization(headers_params) # path parameters if path_params: @@ -87,7 +86,7 @@ class ApiClient(object): post_params = self.sanitize_for_serialization(post_params) # auth setting - self.update_params_for_auth(headers, query_params, auth_settings) + self.update_params_for_auth(headers_params, query_params, auth_settings) # body if body: @@ -97,7 +96,7 @@ class ApiClient(object): url = self.host + resource_path # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=headers, + response_data = self.request(method, url, query_params=query_params, headers=headers_params, post_params=post_params, body=body) # deserialize response data diff --git a/samples/client/petstore/python/SwaggerPetstore-python/.coverage b/samples/client/petstore/python/SwaggerPetstore-python/.coverage new file mode 100644 index 0000000000000000000000000000000000000000..50a2ec114f96392ad885009385cd17ebb246e395 GIT binary patch literal 3297 zcmc(iX>e0z6ox&eh3+kT7g|bNXee!B3xa|OZp`TG!BV)Qz$J$CBMqcUZju%X6c7;v zSrt@7(Q(EF_ibF!(NSD+8%G`ShvN@*+(yS;T+jD4wbbeF^j9)>CO2=+ea`!Q*_hVl zkju*QM?xXxPefu)npNPBbf}mwpei~hyQjGuoIzGbC>U08C%wzba9JBYR$Rs6o`6y- zRcuYv6JO;E1XQf&wca0TQ2`b9#C>hikcxZ!p`Z#UJW-X1%Qq-bv@_8f347*uf2=8a zxxW9)o;JB#NN(aws6Zsv>5g_fgKcMs3&Su1MJT~IRH6zKPy-k0;6bCZ)~7b2FB*({ z+GQwSd8Y$r+D?`WBQZ(>7Gn&`Q6V9#CE|Q+z`Z!m8N}0wTS-}61CUi7MNiah+sWxK z>Uas;fXSGG(=ZLEV>)JFCeFev%*NR`2j^oBE(GIZG-00nEE`^24j=qz!Eyu;#0soL z2yF<%K@1(}#9FLFmkeMVuE7rM#BS`twYU!ZaXoIpjW~dta0?FMcHDuxa5oOisP4xT zcnVMB89a;U@H}3?i+Bk~@iJb)t9S#)@DAR?`}hDK;v;;F&+#R`#y9vLKj26Fj9>68 ze#7rLfxqxKr;(og5aLYYEaDvEJmM1KGUBns6~yC+tB9+KClJ>VPb97-o5noBXnRpBFR^n~M+lhA&?5lT>sGK`gdbzvfEF$wi> z<5VNJExx@X996CC(=kWp339nZ_%Y54@aDkAH3=CESRQV?dDzu%U{{<4rGE-ihNe@M0Eh?r* zG|YB}_eyAvveu<`^OAYAc66K(wllIfPLs0M4oDm^i%v7jc1HK6={9sV#v4oP&95`N z?~(1FB6gWBW|=K}FGFlkZR(hco4iG~Q|v+-1_|-q4VG`ZtGl_1<&;rsG_ECHn@ryz z&80g_CqK{F5Ykq2lSXV7CoV9pb(yr*Vl0v7(tcbfhE!t6R`FvSqQ;GJBus~CL#`J; zUV%;6jH|F!x@?y;*{=t6w+WA__ICHb;8cs) literal 0 HcmV?d00001 diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO new file mode 100644 index 00000000000..ade0b731202 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO @@ -0,0 +1,12 @@ +Metadata-Version: 1.0 +Name: SwaggerPetstore +Version: 1.0.0 +Summary: Swagger Petstore +Home-page: UNKNOWN +Author: UNKNOWN +Author-email: apiteam@wordnik.com +License: UNKNOWN +Description: This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters + +Keywords: Swagger,Swagger Petstore +Platform: UNKNOWN diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt new file mode 100644 index 00000000000..94955251c31 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt @@ -0,0 +1,25 @@ +setup.cfg +setup.py +SwaggerPetstore/__init__.py +SwaggerPetstore/config.py +SwaggerPetstore/rest.py +SwaggerPetstore/swagger.py +SwaggerPetstore/util.py +SwaggerPetstore.egg-info/PKG-INFO +SwaggerPetstore.egg-info/SOURCES.txt +SwaggerPetstore.egg-info/dependency_links.txt +SwaggerPetstore.egg-info/requires.txt +SwaggerPetstore.egg-info/top_level.txt +SwaggerPetstore/apis/__init__.py +SwaggerPetstore/apis/pet_api.py +SwaggerPetstore/apis/store_api.py +SwaggerPetstore/apis/user_api.py +SwaggerPetstore/models/__init__.py +SwaggerPetstore/models/category.py +SwaggerPetstore/models/order.py +SwaggerPetstore/models/pet.py +SwaggerPetstore/models/tag.py +SwaggerPetstore/models/user.py +tests/__init__.py +tests/test_api_client.py +tests/test_pet_api.py \ No newline at end of file diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt new file mode 100644 index 00000000000..cf46870af1e --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt @@ -0,0 +1,2 @@ +urllib3 >= 1.10 +six >= 1.9 \ No newline at end of file diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt new file mode 100644 index 00000000000..58cccc9f2e4 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt @@ -0,0 +1,2 @@ +tests +SwaggerPetstore diff --git a/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log new file mode 100644 index 00000000000..0549f97e65f --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log @@ -0,0 +1,5 @@ +Requirement already satisfied (use --upgrade to upgrade): nose in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) +Requirement already satisfied (use --upgrade to upgrade): tox in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) +Requirement already satisfied (use --upgrade to upgrade): coverage in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) +Requirement already satisfied (use --upgrade to upgrade): randomize in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) +Cleaning up... From 654a73c5a8163080cb760fc3d8af5964b0d94cc5 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 27 May 2015 20:50:04 +0800 Subject: [PATCH 24/41] rebuild python client --- .../main/resources/python/swagger.mustache | 14 +++++----- .../python/SwaggerPetstore-python/.coverage | Bin 3297 -> 0 bytes .../SwaggerPetstore.egg-info/PKG-INFO | 12 --------- .../SwaggerPetstore.egg-info/SOURCES.txt | 25 ------------------ .../dependency_links.txt | 1 - .../SwaggerPetstore.egg-info/requires.txt | 2 -- .../SwaggerPetstore.egg-info/top_level.txt | 2 -- .../SwaggerPetstore/config.py | 3 +-- .../SwaggerPetstore/swagger.py | 15 ++++++----- .../dev-requirements.txt.log | 5 ---- 10 files changed, 17 insertions(+), 62 deletions(-) delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/.coverage delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 0483041116d..d7b896d3c0e 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -62,11 +62,12 @@ class ApiClient(object): body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters - headers_params = self.default_headers.copy().update(header_params) + header_params = header_params or {} + header_params.update(self.default_headers) if self.cookie: - headers_params['Cookie'] = self.cookie - if headers_params: - headers_params = ApiClient.sanitize_for_serialization(headers_params) + header_params['Cookie'] = self.cookie + if header_params: + header_params = ApiClient.sanitize_for_serialization(header_params) # path parameters if path_params: @@ -86,7 +87,7 @@ class ApiClient(object): post_params = self.sanitize_for_serialization(post_params) # auth setting - self.update_params_for_auth(headers_params, query_params, auth_settings) + self.update_params_for_auth(header_params, query_params, auth_settings) # body if body: @@ -96,7 +97,7 @@ class ApiClient(object): url = self.host + resource_path # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=headers_params, + response_data = self.request(method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body) # deserialize response data @@ -301,3 +302,4 @@ class ApiClient(object): raise ValueError('Authentication token must be in `query` or `header`') + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/.coverage b/samples/client/petstore/python/SwaggerPetstore-python/.coverage deleted file mode 100644 index 50a2ec114f96392ad885009385cd17ebb246e395..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 3297 zcmc(iX>e0z6ox&eh3+kT7g|bNXee!B3xa|OZp`TG!BV)Qz$J$CBMqcUZju%X6c7;v zSrt@7(Q(EF_ibF!(NSD+8%G`ShvN@*+(yS;T+jD4wbbeF^j9)>CO2=+ea`!Q*_hVl zkju*QM?xXxPefu)npNPBbf}mwpei~hyQjGuoIzGbC>U08C%wzba9JBYR$Rs6o`6y- zRcuYv6JO;E1XQf&wca0TQ2`b9#C>hikcxZ!p`Z#UJW-X1%Qq-bv@_8f347*uf2=8a zxxW9)o;JB#NN(aws6Zsv>5g_fgKcMs3&Su1MJT~IRH6zKPy-k0;6bCZ)~7b2FB*({ z+GQwSd8Y$r+D?`WBQZ(>7Gn&`Q6V9#CE|Q+z`Z!m8N}0wTS-}61CUi7MNiah+sWxK z>Uas;fXSGG(=ZLEV>)JFCeFev%*NR`2j^oBE(GIZG-00nEE`^24j=qz!Eyu;#0soL z2yF<%K@1(}#9FLFmkeMVuE7rM#BS`twYU!ZaXoIpjW~dta0?FMcHDuxa5oOisP4xT zcnVMB89a;U@H}3?i+Bk~@iJb)t9S#)@DAR?`}hDK;v;;F&+#R`#y9vLKj26Fj9>68 ze#7rLfxqxKr;(og5aLYYEaDvEJmM1KGUBns6~yC+tB9+KClJ>VPb97-o5noBXnRpBFR^n~M+lhA&?5lT>sGK`gdbzvfEF$wi> z<5VNJExx@X996CC(=kWp339nZ_%Y54@aDkAH3=CESRQV?dDzu%U{{<4rGE-ihNe@M0Eh?r* zG|YB}_eyAvveu<`^OAYAc66K(wllIfPLs0M4oDm^i%v7jc1HK6={9sV#v4oP&95`N z?~(1FB6gWBW|=K}FGFlkZR(hco4iG~Q|v+-1_|-q4VG`ZtGl_1<&;rsG_ECHn@ryz z&80g_CqK{F5Ykq2lSXV7CoV9pb(yr*Vl0v7(tcbfhE!t6R`FvSqQ;GJBus~CL#`J; zUV%;6jH|F!x@?y;*{=t6w+WA__ICHb;8cs) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO deleted file mode 100644 index ade0b731202..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/PKG-INFO +++ /dev/null @@ -1,12 +0,0 @@ -Metadata-Version: 1.0 -Name: SwaggerPetstore -Version: 1.0.0 -Summary: Swagger Petstore -Home-page: UNKNOWN -Author: UNKNOWN -Author-email: apiteam@wordnik.com -License: UNKNOWN -Description: This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters - -Keywords: Swagger,Swagger Petstore -Platform: UNKNOWN diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt deleted file mode 100644 index 94955251c31..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/SOURCES.txt +++ /dev/null @@ -1,25 +0,0 @@ -setup.cfg -setup.py -SwaggerPetstore/__init__.py -SwaggerPetstore/config.py -SwaggerPetstore/rest.py -SwaggerPetstore/swagger.py -SwaggerPetstore/util.py -SwaggerPetstore.egg-info/PKG-INFO -SwaggerPetstore.egg-info/SOURCES.txt -SwaggerPetstore.egg-info/dependency_links.txt -SwaggerPetstore.egg-info/requires.txt -SwaggerPetstore.egg-info/top_level.txt -SwaggerPetstore/apis/__init__.py -SwaggerPetstore/apis/pet_api.py -SwaggerPetstore/apis/store_api.py -SwaggerPetstore/apis/user_api.py -SwaggerPetstore/models/__init__.py -SwaggerPetstore/models/category.py -SwaggerPetstore/models/order.py -SwaggerPetstore/models/pet.py -SwaggerPetstore/models/tag.py -SwaggerPetstore/models/user.py -tests/__init__.py -tests/test_api_client.py -tests/test_pet_api.py \ No newline at end of file diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt deleted file mode 100644 index cf46870af1e..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/requires.txt +++ /dev/null @@ -1,2 +0,0 @@ -urllib3 >= 1.10 -six >= 1.9 \ No newline at end of file diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt deleted file mode 100644 index 58cccc9f2e4..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore.egg-info/top_level.txt +++ /dev/null @@ -1,2 +0,0 @@ -tests -SwaggerPetstore diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py index ec3dbe8efb4..46e60ccf417 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py @@ -15,8 +15,7 @@ def get_basic_auth_token(): global username global password - if username and password: - return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') + return urllib3.util.make_headers(basic_auth=username + ':' + password).get('authorization') def auth_settings(): return { diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py index f01192dd46b..d7b896d3c0e 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py @@ -62,12 +62,12 @@ class ApiClient(object): body=None, post_params=None, files=None, response=None, auth_settings=None): # headers parameters - headers = self.default_headers.copy() - headers.update(header_params) + header_params = header_params or {} + header_params.update(self.default_headers) if self.cookie: - headers['Cookie'] = self.cookie - if headers: - headers = self.sanitize_for_serialization(headers) + header_params['Cookie'] = self.cookie + if header_params: + header_params = ApiClient.sanitize_for_serialization(header_params) # path parameters if path_params: @@ -87,7 +87,7 @@ class ApiClient(object): post_params = self.sanitize_for_serialization(post_params) # auth setting - self.update_params_for_auth(headers, query_params, auth_settings) + self.update_params_for_auth(header_params, query_params, auth_settings) # body if body: @@ -97,7 +97,7 @@ class ApiClient(object): url = self.host + resource_path # perform request and return response - response_data = self.request(method, url, query_params=query_params, headers=headers, + response_data = self.request(method, url, query_params=query_params, headers=header_params, post_params=post_params, body=body) # deserialize response data @@ -302,3 +302,4 @@ class ApiClient(object): raise ValueError('Authentication token must be in `query` or `header`') + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log deleted file mode 100644 index 0549f97e65f..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt.log +++ /dev/null @@ -1,5 +0,0 @@ -Requirement already satisfied (use --upgrade to upgrade): nose in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 1)) -Requirement already satisfied (use --upgrade to upgrade): tox in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 2)) -Requirement already satisfied (use --upgrade to upgrade): coverage in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 3)) -Requirement already satisfied (use --upgrade to upgrade): randomize in /Users/geekerzp/.virtualenvs/python2/lib/python2.7/site-packages (from -r dev-requirements.txt (line 4)) -Cleaning up... From 51887c64b518f60c0568e8b07340904830ee44be Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 29 May 2015 10:47:07 +0800 Subject: [PATCH 25/41] Updated python codegen. Use File.separatorChar to create invokerPacakge variable instread of '\' char. --- .../swagger/codegen/languages/PythonClientCodegen.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index 590e17f6326..44dfaeefcd4 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -27,7 +27,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig super(); eggPackage = module + "-python"; - invokerPackage = eggPackage + "/" + module; + + invokerPackage = eggPackage + "." + module; + invokerPackage = invokerPackage.replace('.', File.separatorChar); outputFolder = "generated-code/python"; modelTemplateFiles.put("model.mustache", ".py"); From ab6f327f35a2b54a22b7161151262e3bb4dbd026 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 2 Jun 2015 18:14:46 +0800 Subject: [PATCH 26/41] Updated python client. * Rename `ResponseError` exception to `ApiException` * Use `File.separatorChar` to build file path in PythonClientCodegen.java * Rename `config.py` module to `configuration.py` * Rename `swagger.py` module to `api_client.py` --- .../codegen/languages/PythonClientCodegen.java | 17 ++++++++--------- .../resources/python/__init__package.mustache | 2 +- .../src/main/resources/python/api.mustache | 2 +- .../{swagger.mustache => api_client.mustache} | 6 +++--- .../{config.mustache => configuration.mustache} | 0 .../src/main/resources/python/rest.mustache | 4 ++-- .../SwaggerPetstore/__init__.py | 2 +- .../{swagger.py => api_client.py} | 6 +++--- .../SwaggerPetstore/apis/pet_api.py | 2 +- .../SwaggerPetstore/apis/store_api.py | 2 +- .../SwaggerPetstore/apis/user_api.py | 2 +- .../{config.py => configuration.py} | 0 .../SwaggerPetstore/rest.py | 4 ++-- .../tests/test_api_client.py | 16 ++++++++-------- .../tests/test_pet_api.py | 7 +++---- 15 files changed, 35 insertions(+), 37 deletions(-) rename modules/swagger-codegen/src/main/resources/python/{swagger.mustache => api_client.mustache} (98%) rename modules/swagger-codegen/src/main/resources/python/{config.mustache => configuration.mustache} (100%) rename samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/{swagger.py => api_client.py} (98%) rename samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/{config.py => configuration.py} (100%) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index 44dfaeefcd4..4cb96497aff 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -28,16 +28,15 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig eggPackage = module + "-python"; - invokerPackage = eggPackage + "." + module; - invokerPackage = invokerPackage.replace('.', File.separatorChar); + invokerPackage = eggPackage + File.separatorChar + module; - outputFolder = "generated-code/python"; + outputFolder = "generated-code" + File.separatorChar + "python"; modelTemplateFiles.put("model.mustache", ".py"); apiTemplateFiles.put("api.mustache", ".py"); templateDir = "python"; - apiPackage = invokerPackage + ".apis"; - modelPackage = invokerPackage + ".models"; + apiPackage = invokerPackage + File.separatorChar + "apis"; + modelPackage = invokerPackage + File.separatorChar + "models"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); @@ -70,13 +69,13 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); - supportingFiles.add(new SupportingFile("swagger.mustache", invokerPackage, "swagger.py")); + supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py")); supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); supportingFiles.add(new SupportingFile("util.mustache", invokerPackage, "util.py")); - supportingFiles.add(new SupportingFile("config.mustache", invokerPackage, "config.py")); + supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage.replace('.', File.separatorChar), "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage, "__init__.py")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache index 7b48136d3a9..921f4dac0eb 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache @@ -7,4 +7,4 @@ from __future__ import absolute_import {{#apiInfo}}{{#apis}}from .apis.{{classVarName}} import {{classname}} {{/apis}}{{/apiInfo}} # import ApiClient -from .swagger import ApiClient +from .api_client import ApiClient diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 55bfd9e82a4..69c90491b95 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -29,7 +29,7 @@ from six import iteritems from ..util import remove_none -from .. import config +from ..api_client import ApiClient {{#operations}} class {{classname}}(object): diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache similarity index 98% rename from modules/swagger-codegen/src/main/resources/python/swagger.mustache rename to modules/swagger-codegen/src/main/resources/python/api_client.mustache index d7b896d3c0e..4ba445e2fa6 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -28,7 +28,7 @@ except ImportError: # for python2 from urllib import quote -from . import config +from . import configuration class ApiClient(object): """ @@ -38,7 +38,7 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API :param header_value: a header value to pass when making calls to the API """ - def __init__(self, host=config.host, header_name=None, header_value=None): + def __init__(self, host=configuration.host, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -292,7 +292,7 @@ class ApiClient(object): return for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) + auth_setting = configuration.auth_settings().get(auth) if auth_setting: if auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] diff --git a/modules/swagger-codegen/src/main/resources/python/config.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/python/config.mustache rename to modules/swagger-codegen/src/main/resources/python/configuration.mustache diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index da99abc2493..44a1022906b 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -120,7 +120,7 @@ class RESTClientObject(object): r = RESTResponse(r) if r.status not in range(200, 206): - raise ErrorResponse(r) + raise ApiException(r) return self.process_response(r) @@ -157,7 +157,7 @@ class RESTClientObject(object): return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) -class ErrorResponse(Exception): +class ApiException(Exception): """ Non-2xx HTTP response """ diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py index 9d4b2db3de5..3e7b51b8467 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py @@ -13,4 +13,4 @@ from .apis.pet_api import PetApi from .apis.store_api import StoreApi # import ApiClient -from .swagger import ApiClient +from .api_client import ApiClient diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py similarity index 98% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py rename to samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py index d7b896d3c0e..4ba445e2fa6 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py @@ -28,7 +28,7 @@ except ImportError: # for python2 from urllib import quote -from . import config +from . import configuration class ApiClient(object): """ @@ -38,7 +38,7 @@ class ApiClient(object): :param header_name: a header to pass when making calls to the API :param header_value: a header value to pass when making calls to the API """ - def __init__(self, host=config.host, header_name=None, header_value=None): + def __init__(self, host=configuration.host, header_name=None, header_value=None): self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value @@ -292,7 +292,7 @@ class ApiClient(object): return for auth in auth_settings: - auth_setting = config.auth_settings().get(auth) + auth_setting = configuration.auth_settings().get(auth) if auth_setting: if auth_setting['in'] == 'header': headers[auth_setting['key']] = auth_setting['value'] diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index 37da9901597..1a738e4c317 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -29,7 +29,7 @@ from six import iteritems from ..util import remove_none -from .. import config +from ..api_client import ApiClient class PetApi(object): diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index 649cb5f704d..aab7d0f11b6 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -29,7 +29,7 @@ from six import iteritems from ..util import remove_none -from .. import config +from ..api_client import ApiClient class StoreApi(object): diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 3f2b36a85fa..66cb235c3d7 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -29,7 +29,7 @@ from six import iteritems from ..util import remove_none -from .. import config +from ..api_client import ApiClient class UserApi(object): diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py similarity index 100% rename from samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/config.py rename to samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py index da99abc2493..44a1022906b 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py @@ -120,7 +120,7 @@ class RESTClientObject(object): r = RESTResponse(r) if r.status not in range(200, 206): - raise ErrorResponse(r) + raise ApiException(r) return self.process_response(r) @@ -157,7 +157,7 @@ class RESTClientObject(object): return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) -class ErrorResponse(Exception): +class ApiException(Exception): """ Non-2xx HTTP response """ diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py index 6bc3000f267..560d01d0f3d 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py @@ -12,7 +12,7 @@ import time import unittest import SwaggerPetstore -import SwaggerPetstore.config +import SwaggerPetstore.configuration HOST = 'http://petstore.swagger.io/v2' @@ -23,17 +23,17 @@ class ApiClientTests(unittest.TestCase): self.api_client = SwaggerPetstore.ApiClient(HOST) def test_configuratjion(self): - SwaggerPetstore.config.api_key['api_key'] = '123456' - SwaggerPetstore.config.api_key_prefix['api_key'] = 'PREFIX' - SwaggerPetstore.config.username = 'test_username' - SwaggerPetstore.config.password = 'test_password' + SwaggerPetstore.configuration.api_key['api_key'] = '123456' + SwaggerPetstore.configuration.api_key_prefix['api_key'] = 'PREFIX' + SwaggerPetstore.configuration.username = 'test_username' + SwaggerPetstore.configuration.password = 'test_password' header_params = {'test1': 'value1'} query_params = {'test2': 'value2'} auth_settings = ['api_key', 'unknown'] # test prefix - self.assertEqual('PREFIX', SwaggerPetstore.config.api_key_prefix['api_key']) + self.assertEqual('PREFIX', SwaggerPetstore.configuration.api_key_prefix['api_key']) # update parameters based on auth setting self.api_client.update_params_for_auth(header_params, query_params, auth_settings) @@ -44,8 +44,8 @@ class ApiClientTests(unittest.TestCase): self.assertEqual(query_params['test2'], 'value2') # test basic auth - self.assertEqual('test_username', SwaggerPetstore.config.username) - self.assertEqual('test_password', SwaggerPetstore.config.password) + self.assertEqual('test_username', SwaggerPetstore.configuration.username) + self.assertEqual('test_password', SwaggerPetstore.configuration.password) def test_select_header_accept(self): accepts = ['APPLICATION/JSON', 'APPLICATION/XML'] diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index ee8c5dde14e..2c50ac861a1 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -12,8 +12,7 @@ import time import unittest import SwaggerPetstore -from SwaggerPetstore.rest import ErrorResponse -from SwaggerPetstore import config +from SwaggerPetstore.rest import ApiException HOST = 'http://petstore.swagger.io/v2' @@ -126,7 +125,7 @@ class PetApiTests(unittest.TestCase): additional_metadata=additional_metadata, file=self.foo ) - except ErrorResponse as e: + except ApiException as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) def test_delete_pet(self): @@ -136,7 +135,7 @@ class PetApiTests(unittest.TestCase): try: self.pet_api.get_pet_by_id(pet_id=self.pet.id) raise "expected an error" - except ErrorResponse as e: + except ApiException as e: self.assertEqual(404, e.status) if __name__ == '__main__': From fbe327ac2f8b59854c13971515a6e8b66d861615 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 2 Jun 2015 18:23:55 +0800 Subject: [PATCH 27/41] Updated PythonClientCodegen.java * updated method apiFileFolder. * udpated method modelFileFolder. --- .../swagger/codegen/languages/PythonClientCodegen.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index 4cb96497aff..679b3174c7c 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -85,11 +85,11 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + apiPackage().replace('.', File.separatorChar); } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + modelPackage().replace('.', File.separatorChar); } @Override From 5fbda0e2069797cdd9b2c515c029ad32678f86fd Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 3 Jun 2015 10:46:32 +0800 Subject: [PATCH 28/41] added test case for 404 response of python client --- .../SwaggerPetstore/rest.py | 6 ++++ .../tests/test_api_exception.py | 31 +++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py index 44a1022906b..e7051886dcd 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py @@ -1,4 +1,10 @@ # coding: utf-8 + +""" +Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: +https://www.dropbox.com/developers/core/sdks/python +""" + import sys import io import json diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py new file mode 100644 index 00000000000..6e306753989 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py @@ -0,0 +1,31 @@ +# coding: utf-8 + +""" +Run the tests. +$ pip install nose (optional) +$ cd SwaggerPetstore-python +$ nosetests -v +""" + +import os +import time +import unittest + +import SwaggerPetstore +from SwaggerPetstore.rest import ApiException + + +class ApiExceptionTests(unittest.TestCase): + + def setUp(self): + self.api_client = SwaggerPetstore.ApiClient() + self.pet_api = SwaggerPetstore.PetApi(self.api_client) + + def tearDown(self): + time.sleep(1) + + def test_404_error(self): + self.pet_api.delete_pet(pet_id=1234) + + with self.assertRaisesRegexp(ApiException, "Pet not found"): + self.pet_api.get_pet_by_id(pet_id=1234) From 8ef4c4401e3fac538b77e8242f87548c1783aba4 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 3 Jun 2015 10:50:32 +0800 Subject: [PATCH 29/41] updated rest.mustache of python client --- .../swagger-codegen/src/main/resources/python/rest.mustache | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index 44a1022906b..e7051886dcd 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -1,4 +1,10 @@ # coding: utf-8 + +""" +Credit: this file (rest.py) is modified based on rest.py in Dropbox Python SDK: +https://www.dropbox.com/developers/core/sdks/python +""" + import sys import io import json From 813c0119aafe79e8f5be23c7af75bbd4ffc0b875 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 3 Jun 2015 15:04:36 +0800 Subject: [PATCH 30/41] added test case for 500 response of python client --- .../src/main/resources/python/rest.mustache | 5 +- .../src/main/resources/python/util.mustache | 13 +++-- .../SwaggerPetstore/rest.py | 5 +- .../SwaggerPetstore/util.py | 13 +++-- .../tests/test_api_exception.py | 49 ++++++++++++++++++- 5 files changed, 67 insertions(+), 18 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache index e7051886dcd..508f3d6693a 100644 --- a/modules/swagger-codegen/src/main/resources/python/rest.mustache +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -190,7 +190,10 @@ class ApiException(Exception): """ Custom error response messages """ - return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + return "({0})\n"\ + "Reason: {1}\n"\ + "HTTP response headers: {2}\n"\ + "HTTP response body: {3}\n".\ format(self.status, self.reason, self.headers, self.body) class RESTClient(object): diff --git a/modules/swagger-codegen/src/main/resources/python/util.mustache b/modules/swagger-codegen/src/main/resources/python/util.mustache index 1137a5d2d23..92df1e37e3a 100644 --- a/modules/swagger-codegen/src/main/resources/python/util.mustache +++ b/modules/swagger-codegen/src/main/resources/python/util.mustache @@ -1,6 +1,12 @@ +# coding: utf-8 + from six import iteritems def remove_none(obj): + """ + Remove None from `list`, `tuple`, `set`. + Remove None value from `dict`. + """ if isinstance(obj, (list, tuple, set)): return type(obj)(remove_none(x) for x in obj if x is not None) elif isinstance(obj, dict): @@ -8,10 +14,3 @@ def remove_none(obj): for k, v in iteritems(obj) if k is not None and v is not None) else: return obj - - -def inspect_vars(obj): - if not hasattr(obj, '__dict__'): - return obj - else: - return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py index e7051886dcd..508f3d6693a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py @@ -190,7 +190,10 @@ class ApiException(Exception): """ Custom error response messages """ - return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + return "({0})\n"\ + "Reason: {1}\n"\ + "HTTP response headers: {2}\n"\ + "HTTP response body: {3}\n".\ format(self.status, self.reason, self.headers, self.body) class RESTClient(object): diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py index 1137a5d2d23..92df1e37e3a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py @@ -1,6 +1,12 @@ +# coding: utf-8 + from six import iteritems def remove_none(obj): + """ + Remove None from `list`, `tuple`, `set`. + Remove None value from `dict`. + """ if isinstance(obj, (list, tuple, set)): return type(obj)(remove_none(x) for x in obj if x is not None) elif isinstance(obj, dict): @@ -8,10 +14,3 @@ def remove_none(obj): for k, v in iteritems(obj) if k is not None and v is not None) else: return obj - - -def inspect_vars(obj): - if not hasattr(obj, '__dict__'): - return obj - else: - return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py index 6e306753989..d1b786241e8 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_exception.py @@ -20,12 +20,57 @@ class ApiExceptionTests(unittest.TestCase): def setUp(self): self.api_client = SwaggerPetstore.ApiClient() self.pet_api = SwaggerPetstore.PetApi(self.api_client) + self.setUpModels() + + def setUpModels(self): + self.category = SwaggerPetstore.Category() + self.category.id = int(time.time()) + self.category.name = "dog" + self.tag = SwaggerPetstore.Tag() + self.tag.id = int(time.time()) + self.tag.name = "blank" + self.pet = SwaggerPetstore.Pet() + self.pet.id = int(time.time()) + self.pet.name = "hello kity" + self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] + self.pet.status = "sold" + self.pet.category = self.category + self.pet.tags = [self.tag] def tearDown(self): time.sleep(1) def test_404_error(self): - self.pet_api.delete_pet(pet_id=1234) + self.pet_api.add_pet(body=self.pet) + self.pet_api.delete_pet(pet_id=self.pet.id) with self.assertRaisesRegexp(ApiException, "Pet not found"): - self.pet_api.get_pet_by_id(pet_id=1234) + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + + try: + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + except ApiException as e: + self.assertEqual(e.status, 404) + self.assertEqual(e.reason, "Not Found") + self.assertDictEqual(e.body, {'message': 'Pet not found', 'code': 1, 'type': 'error'}) + + def test_500_error(self): + self.pet_api.add_pet(body=self.pet) + + with self.assertRaisesRegexp(ApiException, "Internal Server Error"): + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata="special", + file=None + ) + + try: + self.pet_api.upload_file( + pet_id=self.pet.id, + additional_metadata="special", + file=None + ) + except ApiException as e: + self.assertEqual(e.status, 500) + self.assertEqual(e.reason, "Internal Server Error") + self.assertRegexpMatches(e.body, "Error 500 Internal Server Error") From a30f537f5fdb645f5fdbd8baed3b7b9e46364d3c Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 3 Jun 2015 15:07:50 +0800 Subject: [PATCH 31/41] fixed typo --- .../python/SwaggerPetstore-python/tests/test_api_client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py index 560d01d0f3d..0ef4314d0f4 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_api_client.py @@ -22,7 +22,7 @@ class ApiClientTests(unittest.TestCase): def setUp(self): self.api_client = SwaggerPetstore.ApiClient(HOST) - def test_configuratjion(self): + def test_configuration(self): SwaggerPetstore.configuration.api_key['api_key'] = '123456' SwaggerPetstore.configuration.api_key_prefix['api_key'] = 'PREFIX' SwaggerPetstore.configuration.username = 'test_username' From ddc5293e6a43713a8cbbb86de1b0b91014165dae Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 3 Jun 2015 18:26:51 +0800 Subject: [PATCH 32/41] updated api.mustache of python. --- .../languages/PythonClientCodegen.java | 1 - .../src/main/resources/python/api.mustache | 35 +++- .../main/resources/python/api_client.mustache | 11 +- .../src/main/resources/python/util.mustache | 16 -- .../SwaggerPetstore/api_client.py | 11 +- .../SwaggerPetstore/apis/pet_api.py | 176 ++++++++++++------ .../SwaggerPetstore/apis/store_api.py | 77 +++++--- .../SwaggerPetstore/apis/user_api.py | 165 ++++++++++------ .../SwaggerPetstore/util.py | 16 -- 9 files changed, 323 insertions(+), 185 deletions(-) delete mode 100644 modules/swagger-codegen/src/main/resources/python/util.mustache delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index 679b3174c7c..7f9a77d3132 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -71,7 +71,6 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); supportingFiles.add(new SupportingFile("api_client.mustache", invokerPackage, "api_client.py")); supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); - supportingFiles.add(new SupportingFile("util.mustache", invokerPackage, "util.py")); supportingFiles.add(new SupportingFile("configuration.mustache", invokerPackage, "configuration.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage, "__init__.py")); diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index 69c90491b95..a91797d71b6 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -27,8 +27,6 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - from ..api_client import ApiClient {{#operations}} @@ -66,13 +64,32 @@ class {{classname}}(object): resource_path = '{{path}}'.replace('{format}', 'json') method = '{{httpMethod}}' - path_params = remove_none(dict({{#pathParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/pathParams}})) - query_params = remove_none(dict({{#queryParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/queryParams}})) - header_params = remove_none(dict({{#headerParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/headerParams}})) - form_params = remove_none(dict({{#formParams}}{{^isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) - files = remove_none(dict({{#formParams}}{{#isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) - body_params = {{#bodyParam}}params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}}None{{/bodyParam}} - + path_params = {} + {{#pathParams}} + if '{{paramName}}' in params: + path_params['{{baseName}}'] = params['{{paramName}}'] + {{/pathParams}} + query_params = {} + {{#queryParams}} + if '{{paramName}}' in params: + query_params['{{baseName}}'] = params['{{paramName}}'] + {{/queryParams}} + header_params = {} + {{#headerParams}} + if '{{paramName}}' in params: + header_params['{{baseName}}'] = params['{{paramName}}'] + {{/headerParams}} + form_params = {} + files = {} + {{#formParams}} + if '{{paramName}}' in params: + {{#notFile}}form_params['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} + {{/formParams}} + body_params = None + {{#bodyParam}} + if '{{paramName}}' in params: + body_params = params['{{paramName}}'] + {{/bodyParam}} # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept([{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}]) if not header_params['Accept']: diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 4ba445e2fa6..75c6e336a07 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -248,11 +248,12 @@ class ApiClient(object): if files: for k, v in iteritems(files): - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) + if v: + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) return params diff --git a/modules/swagger-codegen/src/main/resources/python/util.mustache b/modules/swagger-codegen/src/main/resources/python/util.mustache deleted file mode 100644 index 92df1e37e3a..00000000000 --- a/modules/swagger-codegen/src/main/resources/python/util.mustache +++ /dev/null @@ -1,16 +0,0 @@ -# coding: utf-8 - -from six import iteritems - -def remove_none(obj): - """ - Remove None from `list`, `tuple`, `set`. - Remove None value from `dict`. - """ - if isinstance(obj, (list, tuple, set)): - return type(obj)(remove_none(x) for x in obj if x is not None) - elif isinstance(obj, dict): - return type(obj)((remove_none(k), remove_none(v)) - for k, v in iteritems(obj) if k is not None and v is not None) - else: - return obj diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py index 4ba445e2fa6..75c6e336a07 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py @@ -248,11 +248,12 @@ class ApiClient(object): if files: for k, v in iteritems(files): - with open(v, 'rb') as f: - filename = os.path.basename(f.name) - filedata = f.read() - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - params[k] = tuple([filename, filedata, mimetype]) + if v: + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) return params diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index 1a738e4c317..ec0a8c0f5fd 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -27,8 +27,6 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - from ..api_client import ApiClient class PetApi(object): @@ -61,13 +59,20 @@ class PetApi(object): resource_path = '/pet'.replace('{format}', 'json') method = 'PUT' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -105,13 +110,20 @@ class PetApi(object): resource_path = '/pet'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -149,13 +161,20 @@ class PetApi(object): resource_path = '/pet/findByStatus'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict(status=params.get('status'))) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + if 'status' in params: + query_params['status'] = params['status'] + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -195,13 +214,20 @@ class PetApi(object): resource_path = '/pet/findByTags'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict(tags=params.get('tags'))) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + if 'tags' in params: + query_params['tags'] = params['tags'] + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -245,13 +271,20 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -297,13 +330,26 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict(name=params.get('name'), status=params.get('status'))) - files = remove_none(dict()) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + if 'name' in params: + form_params['name'] = params['name'] + + if 'status' in params: + form_params['status'] = params['status'] + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -346,13 +392,23 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'DELETE' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict(api_key=params.get('api_key'))) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + if 'api_key' in params: + header_params['api_key'] = params['api_key'] + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -396,13 +452,26 @@ class PetApi(object): resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict(petId=params.get('pet_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict(additionalMetadata=params.get('additional_metadata'), )) - files = remove_none(dict(file=params.get('file'))) + path_params = {} + + if 'pet_id' in params: + path_params['petId'] = params['pet_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + if 'additional_metadata' in params: + form_params['additionalMetadata'] = params['additional_metadata'] + + if 'file' in params: + files['file'] = params['file'] + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -427,3 +496,6 @@ class PetApi(object): + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index aab7d0f11b6..03f0b2ec170 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -27,8 +27,6 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - from ..api_client import ApiClient class StoreApi(object): @@ -60,13 +58,17 @@ class StoreApi(object): resource_path = '/store/inventory'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -106,13 +108,20 @@ class StoreApi(object): resource_path = '/store/order'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -156,13 +165,20 @@ class StoreApi(object): resource_path = '/store/order/{orderId}'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict(orderId=params.get('order_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'order_id' in params: + path_params['orderId'] = params['order_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -206,13 +222,20 @@ class StoreApi(object): resource_path = '/store/order/{orderId}'.replace('{format}', 'json') method = 'DELETE' - path_params = remove_none(dict(orderId=params.get('order_id'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'order_id' in params: + path_params['orderId'] = params['order_id'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 66cb235c3d7..223566b8684 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -27,8 +27,6 @@ import os # python 2 and python 3 compatibility library from six import iteritems -from ..util import remove_none - from ..api_client import ApiClient class UserApi(object): @@ -61,13 +59,20 @@ class UserApi(object): resource_path = '/user'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -105,13 +110,20 @@ class UserApi(object): resource_path = '/user/createWithArray'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -149,13 +161,20 @@ class UserApi(object): resource_path = '/user/createWithList'.replace('{format}', 'json') method = 'POST' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -194,13 +213,23 @@ class UserApi(object): resource_path = '/user/login'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict(username=params.get('username'), password=params.get('password'))) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + if 'username' in params: + query_params['username'] = params['username'] + + if 'password' in params: + query_params['password'] = params['password'] + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -239,13 +268,17 @@ class UserApi(object): resource_path = '/user/logout'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict()) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -287,13 +320,20 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'GET' - path_params = remove_none(dict(username=params.get('username'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -338,13 +378,23 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'PUT' - path_params = remove_none(dict(username=params.get('username'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) - body_params = params.get('body') - + path_params = {} + + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + + body_params = None + + if 'body' in params: + body_params = params['body'] + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: @@ -386,13 +436,20 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'DELETE' - path_params = remove_none(dict(username=params.get('username'))) - query_params = remove_none(dict()) - header_params = remove_none(dict()) - form_params = remove_none(dict()) - files = remove_none(dict()) + path_params = {} + + if 'username' in params: + path_params['username'] = params['username'] + + query_params = {} + + header_params = {} + + form_params = {} + files = {} + body_params = None - + # HTTP header `Accept` header_params['Accept'] = self.api_client.select_header_accept(['application/json', 'application/xml']) if not header_params['Accept']: diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py deleted file mode 100644 index 92df1e37e3a..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py +++ /dev/null @@ -1,16 +0,0 @@ -# coding: utf-8 - -from six import iteritems - -def remove_none(obj): - """ - Remove None from `list`, `tuple`, `set`. - Remove None value from `dict`. - """ - if isinstance(obj, (list, tuple, set)): - return type(obj)(remove_none(x) for x in obj if x is not None) - elif isinstance(obj, dict): - return type(obj)((remove_none(k), remove_none(v)) - for k, v in iteritems(obj) if k is not None and v is not None) - else: - return obj From 61a7d848f72ddfeb2f20f8b71805d1ff89ecb155 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 5 Jun 2015 17:00:11 +0800 Subject: [PATCH 33/41] rename files in csharp and perl to fix issue --- .../csharp/{apiException.mustache => ApiException.mustache} | 0 .../resources/{perlApiClient.mustache => perl/ApiClient.mustache} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename modules/swagger-codegen/src/main/resources/csharp/{apiException.mustache => ApiException.mustache} (100%) rename modules/swagger-codegen/src/main/resources/{perlApiClient.mustache => perl/ApiClient.mustache} (100%) diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/csharp/apiException.mustache rename to modules/swagger-codegen/src/main/resources/csharp/ApiException.mustache diff --git a/modules/swagger-codegen/src/main/resources/perlApiClient.mustache b/modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/perlApiClient.mustache rename to modules/swagger-codegen/src/main/resources/perl/ApiClient.mustache From eb90b907e7d19a087746f57794103f5c545ee413 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 5 Jun 2015 17:02:38 +0800 Subject: [PATCH 34/41] rebuild python client --- .../src/main/resources/python/api.mustache | 6 +++++- .../src/main/resources/python/api_client.mustache | 5 +---- .../src/main/resources/python/configuration.mustache | 7 ++++--- .../SwaggerPetstore-python/SwaggerPetstore/api_client.py | 5 +---- .../SwaggerPetstore/apis/pet_api.py | 9 +++++---- .../SwaggerPetstore/apis/store_api.py | 6 +++++- .../SwaggerPetstore/apis/user_api.py | 6 +++++- .../SwaggerPetstore/configuration.py | 9 ++++++--- .../python/SwaggerPetstore-python/tests/test_pet_api.py | 4 ++-- 9 files changed, 34 insertions(+), 23 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index a91797d71b6..7153ee2b040 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -27,6 +27,7 @@ import os # python 2 and python 3 compatibility library from six import iteritems +from .. import configuration from ..api_client import ApiClient {{#operations}} @@ -36,7 +37,10 @@ class {{classname}}(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('{{basePath}}') + self.api_client = configuration.api_client + {{#operation}} def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): """ diff --git a/modules/swagger-codegen/src/main/resources/python/api_client.mustache b/modules/swagger-codegen/src/main/resources/python/api_client.mustache index 75c6e336a07..b8cc4cc2a84 100644 --- a/modules/swagger-codegen/src/main/resources/python/api_client.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api_client.mustache @@ -67,7 +67,7 @@ class ApiClient(object): if self.cookie: header_params['Cookie'] = self.cookie if header_params: - header_params = ApiClient.sanitize_for_serialization(header_params) + header_params = self.sanitize_for_serialization(header_params) # path parameters if path_params: @@ -301,6 +301,3 @@ class ApiClient(object): querys[auth_setting['key']] = auth_setting['value'] else: raise ValueError('Authentication token must be in `query` or `header`') - - - diff --git a/modules/swagger-codegen/src/main/resources/python/configuration.mustache b/modules/swagger-codegen/src/main/resources/python/configuration.mustache index 928aac21edf..d3a7093a02a 100644 --- a/modules/swagger-codegen/src/main/resources/python/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/python/configuration.mustache @@ -1,7 +1,7 @@ +from __future__ import absolute_import import base64 import urllib3 - def get_api_key_with_prefix(key): global api_key global api_key_prefix @@ -35,11 +35,12 @@ def auth_settings(): {{/isBasic}}{{/authMethods}} } - - # Default Base url host = "{{basePath}}" +# Default api client +api_client = None + # Authentication settings api_key = {} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py index 75c6e336a07..b8cc4cc2a84 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/api_client.py @@ -67,7 +67,7 @@ class ApiClient(object): if self.cookie: header_params['Cookie'] = self.cookie if header_params: - header_params = ApiClient.sanitize_for_serialization(header_params) + header_params = self.sanitize_for_serialization(header_params) # path parameters if path_params: @@ -301,6 +301,3 @@ class ApiClient(object): querys[auth_setting['key']] = auth_setting['value'] else: raise ValueError('Authentication token must be in `query` or `header`') - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index ec0a8c0f5fd..549b7fe956f 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -27,6 +27,7 @@ import os # python 2 and python 3 compatibility library from six import iteritems +from .. import configuration from ..api_client import ApiClient class PetApi(object): @@ -35,7 +36,10 @@ class PetApi(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('http://petstore.swagger.io/v2') + self.api_client = configuration.api_client + def update_pet(self, **kwargs): """ @@ -496,6 +500,3 @@ class PetApi(object): - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index 03f0b2ec170..bd2fd9b8080 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -27,6 +27,7 @@ import os # python 2 and python 3 compatibility library from six import iteritems +from .. import configuration from ..api_client import ApiClient class StoreApi(object): @@ -35,7 +36,10 @@ class StoreApi(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('http://petstore.swagger.io/v2') + self.api_client = configuration.api_client + def get_inventory(self, **kwargs): """ diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 223566b8684..5aca93818d0 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -27,6 +27,7 @@ import os # python 2 and python 3 compatibility library from six import iteritems +from .. import configuration from ..api_client import ApiClient class UserApi(object): @@ -35,7 +36,10 @@ class UserApi(object): if api_client: self.api_client = api_client else: - self.api_client = config.api_client + if not configuration.api_client: + configuration.api_client = ApiClient('http://petstore.swagger.io/v2') + self.api_client = configuration.api_client + def create_user(self, **kwargs): """ diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py index 46e60ccf417..b5bd0a64e0a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/configuration.py @@ -1,7 +1,7 @@ +from __future__ import absolute_import import base64 import urllib3 - def get_api_key_with_prefix(key): global api_key global api_key_prefix @@ -28,14 +28,17 @@ def auth_settings(): } - - # Default Base url host = "http://petstore.swagger.io/v2" +# Default api client +api_client = None + # Authentication settings api_key = {} api_key_prefix = {} username = '' password = '' + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index 2c50ac861a1..3bf18607729 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -61,11 +61,11 @@ class PetApiTests(unittest.TestCase): # same default api client self.assertEqual(pet_api.api_client, pet_api2.api_client) # confirm using the default api client in the config module - self.assertEqual(pet_api.api_client, config.api_client) + self.assertEqual(pet_api.api_client, SwaggerPetstore.configuration.api_client) # 2 different api clients are not the same self.assertNotEqual(api_client3, api_client4) # customized pet api not using the default api client - self.assertNotEqual(pet_api3.api_client, config.api_client) + self.assertNotEqual(pet_api3.api_client, SwaggerPetstore.configuration.api_client) # customized pet api not using the old pet api's api client self.assertNotEqual(pet_api3.api_client, pet_api2.api_client) From a1f156ca1948c5d873a91411d157fee2aca90c8d Mon Sep 17 00:00:00 2001 From: Fredrik Gustafsson Date: Fri, 29 May 2015 10:53:48 +0200 Subject: [PATCH 35/41] Updated 'api.mustache' to generate asynchronous methods aswell --- .../src/main/resources/csharp/api.mustache | 45 ++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 8e4a468add3..b5c8bfaeac2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Threading.Tasks; using RestSharp; using {{invokerPackage}}; using {{modelPackage}}; @@ -103,7 +104,49 @@ namespace {{package}} { {{#returnType}}return ({{{returnType}}}) apiClient.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} return;{{/returnType}} } + + /// + /// {{summary}} {{notes}} + /// +{{#allParams}} /// {{description}} +{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} + public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { + + var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); + + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} + + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + + _request.AddUrlSegment("format", "json"); // set format to json by default + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + {{/pathParams}} + {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{/formParams}} + {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{/bodyParam}} + + // make the HTTP request + IRestResponse response = await restClient.ExecuteTaskAsync(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); + } + {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + return;{{/returnType}} + } {{/operation}} - } + } {{/operations}} } From 31c6a0a9da90652c8e7f91006eed295f161bc5a3 Mon Sep 17 00:00:00 2001 From: Fredrik Gustafsson Date: Fri, 29 May 2015 12:19:28 +0200 Subject: [PATCH 36/41] Extended the api-class generation by a interface generation --- .../main/resources/csharp/ApiClient.mustache | 14 +++- .../src/main/resources/csharp/api.mustache | 65 ++++++++++++------- 2 files changed, 55 insertions(+), 24 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache index c5b72977cf5..ad57cffdf34 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/ApiClient.mustache @@ -4,6 +4,7 @@ using System.IO; using System.Linq; using System.Net; using System.Text; +using System.Threading.Tasks; using Newtonsoft.Json; using RestSharp; @@ -36,7 +37,16 @@ namespace {{invokerPackage}} { private Dictionary defaultHeaderMap = new Dictionary(); - public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + public Object CallApi(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, + Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { + var response = Task.Run(async () => { + var resp = await CallApiAsync(Path, Method, QueryParams, PostBody, HeaderParams, FormParams, FileParams, AuthSettings); + return resp; + }); + return response.Result; + } + + public async Task CallApiAsync(String Path, RestSharp.Method Method, Dictionary QueryParams, String PostBody, Dictionary HeaderParams, Dictionary FormParams, Dictionary FileParams, String[] AuthSettings) { var request = new RestRequest(Path, Method); @@ -67,7 +77,7 @@ namespace {{invokerPackage}} { request.AddParameter("application/json", PostBody, ParameterType.RequestBody); // http body (model) parameter } - return (Object)restClient.Execute(request); + return (Object) await restClient.ExecuteTaskAsync(request); } diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index b5c8bfaeac2..6cb3178e65e 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -9,10 +9,30 @@ using {{modelPackage}}; namespace {{package}} { {{#operations}} + + public interface I{{classname}} { + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}}{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + + /// + /// {{summary}} {{notes}} + /// + {{#allParams}}/// {{description}}{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} + {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}); + {{/operation}} + } + /// /// Represents a collection of functions to interact with the API endpoints /// - public class {{classname}} { + public class {{classname}} : I{{classname}} { + /// /// Initializes a new instance of the class. /// @@ -62,8 +82,7 @@ namespace {{package}} { /// /// {{summary}} {{notes}} /// -{{#allParams}} /// {{description}} -{{/allParams}} + {{#allParams}}/// {{description}}{{/allParams}} /// {{#returnType}}{{{returnType}}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -108,38 +127,40 @@ namespace {{package}} { /// /// {{summary}} {{notes}} /// -{{#allParams}} /// {{description}} -{{/allParams}} + {{#allParams}}/// {{description}}{{/allParams}} /// {{#returnType}}{{{returnType}}}{{/returnType}} public async {{#returnType}}Task<{{{returnType}}}>{{/returnType}}{{^returnType}}Task{{/returnType}} {{nickname}}Async ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#allParams}}{{#required}} - // verify the required parameter '{{paramName}}' is set - if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} - // add default header, if any - foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) - { - _request.AddHeader(defaultHeader.Key, defaultHeader.Value); - } - - _request.AddUrlSegment("format", "json"); // set format to json by default - {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + var path = "{{path}}"; + path = path.Replace("{format}", "json"); + {{#pathParams}}path = path.Replace("{" + "{{baseName}}" + "}", apiClient.ParameterToString({{{paramName}}})); {{/pathParams}} - {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + var formParams = new Dictionary(); + var fileParams = new Dictionary(); + String postBody = null; + + {{#queryParams}} if ({{paramName}} != null) queryParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // query parameter {{/queryParams}} - {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter + {{#headerParams}} if ({{paramName}} != null) headerParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}fileParams.Add("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}formParams.Add("{{baseName}}", apiClient.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter + {{#bodyParam}}postBody = apiClient.Serialize({{paramName}}); // http body (model) parameter {{/bodyParam}} + // authentication setting, if any + String[] authSettings = new String[] { {{#authMethods}}"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}} }; + // make the HTTP request - IRestResponse response = await restClient.ExecuteTaskAsync(_request); + IRestResponse response = (IRestResponse) await apiClient.CallApiAsync(path, Method.{{httpMethod}}, queryParams, postBody, headerParams, formParams, fileParams, authSettings); if (((int)response.StatusCode) >= 400) { throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); } From 5a75eba42b243c889c6ed145c31737c94c8130ad Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 5 Jun 2015 18:30:58 +0800 Subject: [PATCH 37/41] regenerated perl sample --- .../perl/lib/WWW/SwaggerClient/{APIClient.pm => ApiClient.pm} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename samples/client/petstore/perl/lib/WWW/SwaggerClient/{APIClient.pm => ApiClient.pm} (100%) diff --git a/samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm b/samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm similarity index 100% rename from samples/client/petstore/perl/lib/WWW/SwaggerClient/APIClient.pm rename to samples/client/petstore/perl/lib/WWW/SwaggerClient/ApiClient.pm From e737964f6611f15ec65cd1516ef4682b7c1d4240 Mon Sep 17 00:00:00 2001 From: Fredrik Gustafsson Date: Fri, 5 Jun 2015 13:51:52 +0200 Subject: [PATCH 38/41] minor refactoring --- .../src/main/resources/csharp/apiException.mustache | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache index aee6302d025..38a340be249 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -11,6 +11,10 @@ namespace {{invokerPackage}} { /// The error code (HTTP status code). public int ErrorCode { get; set; } + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). public dynamic ErrorContent { get; private set; } /// @@ -29,8 +33,8 @@ namespace {{invokerPackage}} { } public ApiException(int errorCode, string message, dynamic errorContent = null) : base(message) { - this.errorCode = errorCode; - this.errorContent = errorContent; + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; } } From fffc5d7c351a2a270534d70f2eea602013ed72a7 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 5 Jun 2015 20:00:32 +0800 Subject: [PATCH 39/41] Move authentications into ApiClient --- .../main/resources/Java/ApiClient.mustache | 87 ++++++++++++++++++- .../resources/Java/Configuration.mustache | 68 --------------- .../java/io/swagger/client/ApiClient.java | 86 +++++++++++++++++- .../java/io/swagger/client/Configuration.java | 72 --------------- .../java/io/swagger/client/ApiClientTest.java | 75 ++++++++++++++++ .../io/swagger/client/ConfigurationTest.java | 50 ----------- .../io/swagger/petstore/test/PetApiTest.java | 9 +- .../swagger/petstore/test/StoreApiTest.java | 11 +-- .../io/swagger/petstore/test/UserApiTest.java | 11 +-- 9 files changed, 255 insertions(+), 214 deletions(-) create mode 100644 samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java diff --git a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache index 9a6f4215481..910728c4dd5 100644 --- a/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/ApiClient.mustache @@ -17,6 +17,7 @@ import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Collection; +import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; @@ -34,6 +35,9 @@ import java.text.SimpleDateFormat; import java.text.ParseException; import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +import {{invokerPackage}}.auth.OAuth; public class ApiClient { private Map hostMap = new HashMap(); @@ -41,6 +45,8 @@ public class ApiClient { private boolean debugging = false; private String basePath = "{{basePath}}"; + private Map authentications; + private DateFormat dateFormat; public ApiClient() { @@ -53,6 +59,14 @@ public class ApiClient { // Set default User-Agent. setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap();{{#authMethods}}{{#isBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } public String getBasePath() { @@ -64,6 +78,75 @@ public class ApiClient { return this; } + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ @@ -340,8 +423,8 @@ public class ApiClient { */ private void updateParamsForAuth(String[] authNames, Map queryParams, Map headerParams) { for (String authName : authNames) { - Authentication auth = Configuration.getAuthentication(authName); - if (auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); } } diff --git a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache index a09e34b755c..e936b423a91 100644 --- a/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/Java/Configuration.mustache @@ -1,13 +1,5 @@ package {{invokerPackage}}; -import java.util.Map; -import java.util.HashMap; - -import {{invokerPackage}}.auth.Authentication; -import {{invokerPackage}}.auth.HttpBasicAuth; -import {{invokerPackage}}.auth.ApiKeyAuth; -import {{invokerPackage}}.auth.OAuth; - public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); @@ -26,64 +18,4 @@ public class Configuration { public static void setDefaultApiClient(ApiClient apiClient) { defaultApiClient = apiClient; } - - private static final Map AUTH; - - static { - // setup authentications - AUTH = new HashMap(); - {{#authMethods}} - {{#isBasic}}AUTH.put("{{name}}", new HttpBasicAuth());{{/isBasic}} - {{#isApiKey}}AUTH.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{^isKeyInHeader}}"query"{{/isKeyInHeader}}, "{{keyParamName}}"));{{/isApiKey}} - {{#isOAuth}}AUTH.put("{{name}}", new OAuth());{{/isOAuth}} - {{/authMethods}} - } - - public static Authentication getAuthentication(String authName) { - return AUTH.get(authName); - } - - /** Set username for the first HTTP basic authentication. */ - public static void setUsername(String username) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** Set password for the first HTTP basic authentication. */ - public static void setPassword(String password) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** Set API key value for the first API key authentication. */ - public static void setApiKey(String apiKey) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** Set API key prefix for the first API key authentication. */ - public static void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java index e6e2a308456..61d296537e6 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/ApiClient.java @@ -17,6 +17,7 @@ import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Collection; +import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.HashMap; @@ -34,6 +35,9 @@ import java.text.SimpleDateFormat; import java.text.ParseException; import io.swagger.client.auth.Authentication; +import io.swagger.client.auth.HttpBasicAuth; +import io.swagger.client.auth.ApiKeyAuth; +import io.swagger.client.auth.OAuth; public class ApiClient { private Map hostMap = new HashMap(); @@ -41,6 +45,8 @@ public class ApiClient { private boolean debugging = false; private String basePath = "http://petstore.swagger.io/v2"; + private Map authentications; + private DateFormat dateFormat; public ApiClient() { @@ -53,6 +59,13 @@ public class ApiClient { // Set default User-Agent. setUserAgent("Java-Swagger"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); } public String getBasePath() { @@ -64,6 +77,75 @@ public class ApiClient { return this; } + /** + * Get authentications (key: authentication name, value: authentication). + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + /** * Set the User-Agent header's value (by adding to the default header map). */ @@ -340,8 +422,8 @@ public class ApiClient { */ private void updateParamsForAuth(String[] authNames, Map queryParams, Map headerParams) { for (String authName : authNames) { - Authentication auth = Configuration.getAuthentication(authName); - if (auth == null) throw new RuntimeException("Authentication has not been setup for " + authName); + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); auth.applyToParams(queryParams, headerParams); } } diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java index 88192cbd3bf..04899a110f6 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/Configuration.java @@ -1,13 +1,5 @@ package io.swagger.client; -import java.util.Map; -import java.util.HashMap; - -import io.swagger.client.auth.Authentication; -import io.swagger.client.auth.HttpBasicAuth; -import io.swagger.client.auth.ApiKeyAuth; -import io.swagger.client.auth.OAuth; - public class Configuration { private static ApiClient defaultApiClient = new ApiClient(); @@ -26,68 +18,4 @@ public class Configuration { public static void setDefaultApiClient(ApiClient apiClient) { defaultApiClient = apiClient; } - - private static final Map AUTH; - - static { - // setup authentications - AUTH = new HashMap(); - - - AUTH.put("api_key", new ApiKeyAuth("header", "api_key")); - - - - - AUTH.put("petstore_auth", new OAuth()); - - } - - public static Authentication getAuthentication(String authName) { - return AUTH.get(authName); - } - - /** Set username for the first HTTP basic authentication. */ - public static void setUsername(String username) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setUsername(username); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** Set password for the first HTTP basic authentication. */ - public static void setPassword(String password) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof HttpBasicAuth) { - ((HttpBasicAuth) auth).setPassword(password); - return; - } - } - throw new RuntimeException("No HTTP basic authentication configured!"); - } - - /** Set API key value for the first API key authentication. */ - public static void setApiKey(String apiKey) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKey(apiKey); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } - - /** Set API key prefix for the first API key authentication. */ - public static void setApiKeyPrefix(String apiKeyPrefix) { - for (Authentication auth : AUTH.values()) { - if (auth instanceof ApiKeyAuth) { - ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); - return; - } - } - throw new RuntimeException("No API key authentication configured!"); - } } diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java new file mode 100644 index 00000000000..82f39e90583 --- /dev/null +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/ApiClientTest.java @@ -0,0 +1,75 @@ +package io.swagger.client; + +import io.swagger.client.auth.*; + +import java.util.Map; + +import static org.junit.Assert.*; +import org.junit.*; + +public class ApiClientTest { + ApiClient apiClient = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + @Test + public void testSetUsername() { + try { + apiClient.setUsername("my-username"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetPassword() { + try { + apiClient.setPassword("my-password"); + fail("there should be no HTTP basic authentications"); + } catch (RuntimeException e) { + } + } + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = (ApiKeyAuth) apiClient.getAuthentications().get("api_key"); + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java index 3838dcb21bb..9801be416fb 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/client/ConfigurationTest.java @@ -1,59 +1,9 @@ package io.swagger.client; -import io.swagger.client.auth.*; - import static org.junit.Assert.*; import org.junit.*; public class ConfigurationTest { - @Test - public void testGetAuthentication() { - Authentication auth = Configuration.getAuthentication("api_key"); - assertNotNull(auth); - assertTrue(auth instanceof ApiKeyAuth); - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; - assertEquals("header", apiKeyAuth.getLocation()); - assertEquals("api_key", apiKeyAuth.getParamName()); - - auth = Configuration.getAuthentication("petstore_auth"); - assertTrue(auth instanceof OAuth); - - assertNull(Configuration.getAuthentication("unknown")); - } - - @Test - public void testSetUsername() { - try { - Configuration.setUsername("my-username"); - fail("should throw RuntimeException"); - } catch (RuntimeException e) { - } - } - - @Test - public void testSetPassword() { - try { - Configuration.setPassword("my-password"); - fail("should throw RuntimeException"); - } catch (RuntimeException e) { - } - } - - @Test - public void testSetApiKeyAndPrefix() { - ApiKeyAuth auth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); - auth.setApiKey(null); - auth.setApiKeyPrefix(null); - - Configuration.setApiKey("my-api-key"); - Configuration.setApiKeyPrefix("Token"); - assertEquals("my-api-key", auth.getApiKey()); - assertEquals("Token", auth.getApiKeyPrefix()); - - auth.setApiKey(null); - auth.setApiKeyPrefix(null); - } - @Test public void testDefaultApiClient() { ApiClient apiClient = Configuration.getDefaultApiClient(); diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java index b1316b7a8b4..854af7121da 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -16,15 +16,12 @@ import org.junit.*; public class PetApiTest { PetApi api = null; - @BeforeClass - public static void initAuth() { - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - @Before public void setup() { api = new PetApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } @Test diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java index c5e2a9b8719..1499c4eaf86 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -15,15 +15,12 @@ import org.junit.*; public class StoreApiTest { StoreApi api = null; - @BeforeClass - public static void initAuth() { - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - @Before public void setup() { api = new StoreApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } @Test @@ -73,4 +70,4 @@ public class StoreApiTest { return order; } -} \ No newline at end of file +} diff --git a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java index 8fcb621b85e..e3bccd0dcdb 100644 --- a/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ b/samples/client/petstore/java/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -15,15 +15,12 @@ import org.junit.*; public class UserApiTest { UserApi api = null; - @BeforeClass - public static void initAuth() { - ApiKeyAuth apiKeyAuth = (ApiKeyAuth) Configuration.getAuthentication("api_key"); - apiKeyAuth.setApiKey("special-key"); - } - @Before public void setup() { api = new UserApi(); + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); } @Test @@ -89,4 +86,4 @@ public class UserApiTest { return user; } -} \ No newline at end of file +} From d0f9345c5a75d08b0407b2f6da9be8ea385b2eb8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Fri, 5 Jun 2015 13:16:30 +0800 Subject: [PATCH 40/41] fix php map, add test case for get inventory --- .../src/main/resources/php/APIClient.mustache | 7 +++---- .../php/SwaggerClient-php/lib/APIClient.php | 7 +++---- .../php/SwaggerClient-php/tests/PetApiTest.php | 16 +++++++++++++++- 3 files changed, 21 insertions(+), 9 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index f2106dc6e43..476d3b625c2 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -376,17 +376,16 @@ class ApiClient { { if (null === $data) { $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] $inner = substr($class, 4, -1); - $values = array(); + $deserialized = array(); if(strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $values[] = array($key => self::deserialize($value, $subClass)); + $deserialized[$key] = self::deserialize($value, $subClass); } } - $deserialized = $values; } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { $subClass = substr($class, 6, -1); $values = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 5415ff66972..229709562ef 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -381,17 +381,16 @@ class ApiClient { { if (null === $data) { $deserialized = null; - } elseif (substr($class, 0, 4) == 'map[') { + } elseif (substr($class, 0, 4) == 'map[') { # for associative array e.g. map[string,int] $inner = substr($class, 4, -1); - $values = array(); + $deserialized = array(); if(strrpos($inner, ",") !== false) { $subClass_array = explode(',', $inner, 2); $subClass = $subClass_array[1]; foreach ($data as $key => $value) { - $values[] = array($key => self::deserialize($value, $subClass)); + $deserialized[$key] = self::deserialize($value, $subClass); } } - $deserialized = $values; } elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) { $subClass = substr($class, 6, -1); $values = array(); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index d02b8e74558..390cf332b23 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -181,7 +181,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($response->name, 'PHP Unit Test'); } - // test + // test upload file public function testUploadFile() { // initialize the API client @@ -194,6 +194,20 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame($add_response, NULL); } + // test get inventory + public function testGetInventory() + { + // initialize the API client + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + $store_api = new SwaggerClient\StoreAPI($api_client); + // get inventory + $get_response = $store_api->getInventory(); + + $this->assertInternalType("int", $get_response['sold']); + $this->assertInternalType("int", $get_response['pending']); + + } + } ?> From ddbef8b25daaf5db6d43a6b3ba95372fd22ba415 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 5 Jun 2015 11:40:30 -0700 Subject: [PATCH 41/41] implemented processOpts to avoid clobbering by superclass --- .../codegen/languages/JaxRSServerCodegen.java | 31 ++++++++++++------- 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java index 0bc8097d671..4631a804fc7 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -27,7 +27,7 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf } public JaxRSServerCodegen() { - super(); + super.processOpts(); sourceFolder = "src/gen/java"; @@ -37,7 +37,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf apiTemplateFiles.put("apiService.mustache", ".java"); apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); - templateDir = "JavaJaxRS"; apiPackage = System.getProperty( "swagger.codegen.jaxrs.apipackage", "io.swagger.api") ; modelPackage = System.getProperty( "swagger.codegen.jaxrs.modelpackage", "io.swagger.model" ); @@ -48,6 +47,24 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf additionalProperties.put("artifactVersion", artifactVersion); additionalProperties.put("title", title); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float") + ); + } + + + @Override + public void processOpts() { + super.processOpts(); + supportingFiles.clear(); supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); @@ -62,16 +79,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf supportingFiles.add(new SupportingFile("web.mustache", ("src/main/webapp/WEB-INF"), "web.xml")); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "String", - "boolean", - "Boolean", - "Double", - "Integer", - "Long", - "Float") - ); } @Override