From 4d05b5d81f07cde411c4426a0584c63f28e7db24 Mon Sep 17 00:00:00 2001 From: George Sibble Date: Tue, 16 Jul 2013 14:20:49 -0700 Subject: [PATCH 01/20] Only check in lists and dictionaries The "in" operator also works on strings which can cause problems with this line if the attribute and the object are named the same thing. Signed-off-by: George Sibble --- src/main/resources/python/swagger.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/python/swagger.mustache b/src/main/resources/python/swagger.mustache index c635d85b90d..b5761bbfb56 100644 --- a/src/main/resources/python/swagger.mustache +++ b/src/main/resources/python/swagger.mustache @@ -159,7 +159,7 @@ class ApiClient: instance = objClass() for attr, attrType in instance.swaggerTypes.iteritems(): - if attr in obj: + if attr in obj and type(obj) in [list, dict]: value = obj[attr] if attrType in ['str', 'int', 'long', 'float', 'bool']: attrType = eval(attrType) From 0628c63b15a44b430992834756df76b8bc547a23 Mon Sep 17 00:00:00 2001 From: George Sibble Date: Tue, 16 Jul 2013 14:32:17 -0700 Subject: [PATCH 02/20] Check for None Type Signed-off-by: George Sibble --- src/main/resources/python/swagger.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/resources/python/swagger.mustache b/src/main/resources/python/swagger.mustache index b5761bbfb56..6cec36e4fed 100644 --- a/src/main/resources/python/swagger.mustache +++ b/src/main/resources/python/swagger.mustache @@ -159,7 +159,7 @@ class ApiClient: instance = objClass() for attr, attrType in instance.swaggerTypes.iteritems(): - if attr in obj and type(obj) in [list, dict]: + if obj is not None and attr in obj and type(obj) in [list, dict]: value = obj[attr] if attrType in ['str', 'int', 'long', 'float', 'bool']: attrType = eval(attrType) From 7bde2ffd6edb98d7b4f867d0452b1f55137f4367 Mon Sep 17 00:00:00 2001 From: Mark Crowther Date: Thu, 3 Oct 2013 15:59:40 +0100 Subject: [PATCH 03/20] Fix Java Generator to always generate valid Java variable names --- src/main/resources/Java/api.mustache | 6 +++--- .../com/wordnik/swagger/codegen/BasicJavaGenerator.scala | 7 ++++++- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/main/resources/Java/api.mustache b/src/main/resources/Java/api.mustache index 2d647d5c5d2..de2248f8930 100644 --- a/src/main/resources/Java/api.mustache +++ b/src/main/resources/Java/api.mustache @@ -41,10 +41,10 @@ public class {{classname}} { {{/requiredParamCount}} {{#queryParams}}if(!"null".equals(String.valueOf({{paramName}}))) - queryParams.put("{{paramName}}", String.valueOf({{paramName}})); + queryParams.put("{{baseName}}", String.valueOf({{paramName}})); {{/queryParams}} - {{#headerParams}}headerParams.put("{{paramName}}", {{paramName}}); + {{#headerParams}}headerParams.put("{{baseName}}", {{paramName}}); {{/headerParams}} String contentType = "application/json"; @@ -68,4 +68,4 @@ public class {{classname}} { } {{/operation}} } -{{/operations}} \ No newline at end of file +{{/operations}} diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala index b11ce15b58d..f624d6781a8 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicJavaGenerator.scala @@ -93,6 +93,11 @@ class BasicJavaGenerator extends BasicGenerator { // file suffix override def fileSuffix = ".java" + override def toVarName(name: String): String = { + val paramName = name.replaceAll("[^a-zA-Z0-9_]","") + super.toVarName(paramName) + } + // response classes override def processResponseClass(responseClass: String): Option[String] = { responseClass match { @@ -209,4 +214,4 @@ class BasicJavaGenerator extends BasicGenerator { ("JsonUtil.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "JsonUtil.java"), ("apiException.mustache", destinationDir + java.io.File.separator + invokerPackage.get.replace(".", java.io.File.separator) + java.io.File.separator, "ApiException.java"), ("pom.mustache", "generated-code/java", "pom.xml")) -} \ No newline at end of file +} From ee19dfadf1f549ffefbd3fb5b0dc6b28950de8e1 Mon Sep 17 00:00:00 2001 From: Gregg Carrier Date: Wed, 16 Oct 2013 22:11:15 -0400 Subject: [PATCH 04/20] more descriptive exception message than MatchError --- .../scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala b/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala index d2aff8ee7b1..8b63333f07d 100644 --- a/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala +++ b/src/main/scala/com/wordnik/swagger/model/SwaggerModelSerializer.scala @@ -87,6 +87,7 @@ object SwaggerSerializers { new ResourceListingSerializer + new ApiListingSerializer } + case _ => throw new IllegalArgumentException("%s is not a valid Swagger version".format(version)) } } From d56c5e3b44d1d59e33532530fa8ce97dca790412 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:42:57 -0700 Subject: [PATCH 05/20] regenerated client --- samples/client/wordnik-api/java/pom.xml | 32 +--- .../com/wordnik/client/api/AccountApi.java | 24 ++- .../java/com/wordnik/client/api/WordApi.java | 94 +++++++--- .../com/wordnik/client/api/WordListApi.java | 26 ++- .../com/wordnik/client/api/WordListsApi.java | 4 +- .../java/com/wordnik/client/api/WordsApi.java | 22 ++- .../com/wordnik/client/common/ApiInvoker.java | 44 +++-- .../com/wordnik/client/model/Definition.java | 8 +- .../com/wordnik/client/model/Example.java | 2 +- .../client/model/ScrabbleScoreResult.java | 21 +++ .../wordnik/client/model/WordOfTheDay.java | 2 +- samples/client/wordnik-api/scala/pom.xml | 22 ++- .../com/wordnik/client/api/AccountApi.scala | 59 +++++-- .../com/wordnik/client/api/WordApi.scala | 161 +++++++++++++----- .../com/wordnik/client/api/WordListApi.scala | 79 ++++++--- .../com/wordnik/client/api/WordListsApi.scala | 17 +- .../com/wordnik/client/api/WordsApi.scala | 50 ++++-- .../wordnik/client/common/ApiInvoker.scala | 66 ++++--- .../com/wordnik/client/model/Definition.scala | 8 +- .../com/wordnik/client/model/Example.scala | 2 +- .../client/model/ScrabbleScoreResult.scala | 5 + .../wordnik/client/model/WordOfTheDay.scala | 2 +- .../src/test/scala/WordListApiTest.scala | 20 ++- 23 files changed, 540 insertions(+), 230 deletions(-) create mode 100644 samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java create mode 100644 samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala diff --git a/samples/client/wordnik-api/java/pom.xml b/samples/client/wordnik-api/java/pom.xml index 18912577dbf..ebdec7d08e0 100644 --- a/samples/client/wordnik-api/java/pom.xml +++ b/samples/client/wordnik-api/java/pom.xml @@ -14,11 +14,7 @@ 2.2.0 - - org.sonatype.oss - oss-parent - 5 - + @@ -37,30 +33,6 @@ pertest - - org.apache.maven.plugins - maven-javadoc-plugin - - - attach-javadocs - - jar - - - - - - org.apache.maven.plugins - maven-source-plugin - - - attach-sources - - jar - - - - maven-dependency-plugin @@ -135,6 +107,7 @@ net.alchim31.maven scala-maven-plugin + ${scala-maven-plugin-version} @@ -235,6 +208,7 @@ 1.0.0 4.8.1 1.6.1 + 3.1.5 diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/AccountApi.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/AccountApi.java index 9dba32f04bf..51448d9cfd1 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/AccountApi.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/AccountApi.java @@ -2,9 +2,9 @@ package com.wordnik.client.api; import com.wordnik.client.common.ApiException; import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.ApiTokenStatus; -import com.wordnik.client.model.WordList; import com.wordnik.client.model.User; +import com.wordnik.client.model.WordList; +import com.wordnik.client.model.ApiTokenStatus; import com.wordnik.client.model.AuthenticationToken; import java.util.*; @@ -38,8 +38,10 @@ public class AccountApi { } if(!"null".equals(String.valueOf(password))) queryParams.put("password", String.valueOf(password)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (AuthenticationToken) ApiInvoker.deserialize(response, "", AuthenticationToken.class); } @@ -67,8 +69,10 @@ public class AccountApi { if(username == null || body == null ) { throw new ApiException(400, "missing required params"); } + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); if(response != null){ return (AuthenticationToken) ApiInvoker.deserialize(response, "", AuthenticationToken.class); } @@ -101,8 +105,10 @@ public class AccountApi { if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", WordList.class); } @@ -127,8 +133,10 @@ public class AccountApi { Map headerParams = new HashMap(); headerParams.put("api_key", api_key); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (ApiTokenStatus) ApiInvoker.deserialize(response, "", ApiTokenStatus.class); } @@ -157,8 +165,10 @@ public class AccountApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (User) ApiInvoker.deserialize(response, "", User.class); } diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordApi.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordApi.java index a130de970b7..6d11ad99c7b 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordApi.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordApi.java @@ -2,16 +2,17 @@ package com.wordnik.client.api; import com.wordnik.client.common.ApiException; import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.Definition; -import com.wordnik.client.model.TextPron; -import com.wordnik.client.model.Example; -import com.wordnik.client.model.Syllable; -import com.wordnik.client.model.AudioFile; -import com.wordnik.client.model.ExampleSearchResults; -import com.wordnik.client.model.WordObject; -import com.wordnik.client.model.Bigram; -import com.wordnik.client.model.Related; import com.wordnik.client.model.FrequencySummary; +import com.wordnik.client.model.Bigram; +import com.wordnik.client.model.WordObject; +import com.wordnik.client.model.ExampleSearchResults; +import com.wordnik.client.model.Example; +import com.wordnik.client.model.ScrabbleScoreResult; +import com.wordnik.client.model.TextPron; +import com.wordnik.client.model.Syllable; +import com.wordnik.client.model.Related; +import com.wordnik.client.model.Definition; +import com.wordnik.client.model.AudioFile; import java.util.*; public class WordApi { @@ -50,8 +51,10 @@ public class WordApi { queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (ExampleSearchResults) ApiInvoker.deserialize(response, "", ExampleSearchResults.class); } @@ -83,8 +86,10 @@ public class WordApi { queryParams.put("useCanonical", String.valueOf(useCanonical)); if(!"null".equals(String.valueOf(includeSuggestions))) queryParams.put("includeSuggestions", String.valueOf(includeSuggestions)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); } @@ -124,8 +129,10 @@ public class WordApi { queryParams.put("useCanonical", String.valueOf(useCanonical)); if(!"null".equals(String.valueOf(includeTags))) queryParams.put("includeTags", String.valueOf(includeTags)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", Definition.class); } @@ -155,8 +162,10 @@ public class WordApi { } if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (Example) ApiInvoker.deserialize(response, "", Example.class); } @@ -190,8 +199,10 @@ public class WordApi { queryParams.put("relationshipTypes", String.valueOf(relationshipTypes)); if(!"null".equals(String.valueOf(limitPerRelationshipType))) queryParams.put("limitPerRelationshipType", String.valueOf(limitPerRelationshipType)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", Related.class); } @@ -227,8 +238,10 @@ public class WordApi { queryParams.put("typeFormat", String.valueOf(typeFormat)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", TextPron.class); } @@ -262,8 +275,10 @@ public class WordApi { queryParams.put("sourceDictionary", String.valueOf(sourceDictionary)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", Syllable.class); } @@ -297,8 +312,10 @@ public class WordApi { queryParams.put("startYear", String.valueOf(startYear)); if(!"null".equals(String.valueOf(endYear))) queryParams.put("endYear", String.valueOf(endYear)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (FrequencySummary) ApiInvoker.deserialize(response, "", FrequencySummary.class); } @@ -332,8 +349,10 @@ public class WordApi { queryParams.put("wlmi", String.valueOf(wlmi)); if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", Bigram.class); } @@ -363,8 +382,10 @@ public class WordApi { } if(!"null".equals(String.valueOf(useCanonical))) queryParams.put("useCanonical", String.valueOf(useCanonical)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", String.class); } @@ -396,8 +417,10 @@ public class WordApi { queryParams.put("useCanonical", String.valueOf(useCanonical)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", AudioFile.class); } @@ -413,5 +436,36 @@ public class WordApi { } } } + public ScrabbleScoreResult getScrabbleScore (String word) throws ApiException { + // create path and map variables + String path = "/word.{format}/{word}/scrabbleScore".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}", apiInvoker.escapeString(word.toString())); + + // query params + Map queryParams = new HashMap(); + Map headerParams = new HashMap(); + + // verify required params are set + if(word == null ) { + throw new ApiException(400, "missing required params"); + } + String contentType = "application/json"; + + try { + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); + if(response != null){ + return (ScrabbleScoreResult) ApiInvoker.deserialize(response, "", ScrabbleScoreResult.class); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.getCode() == 404) { + return null; + } + else { + throw ex; + } + } + } } diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListApi.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListApi.java index 78c160ee7da..b75aa46004c 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListApi.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListApi.java @@ -2,9 +2,9 @@ package com.wordnik.client.api; import com.wordnik.client.common.ApiException; import com.wordnik.client.common.ApiInvoker; +import com.wordnik.client.model.WordListWord; import com.wordnik.client.model.WordList; import com.wordnik.client.model.StringValue; -import com.wordnik.client.model.WordListWord; import java.util.*; public class WordListApi { @@ -36,8 +36,10 @@ public class WordListApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, body, headerParams, contentType); if(response != null){ return ; } @@ -66,8 +68,10 @@ public class WordListApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, contentType); if(response != null){ return ; } @@ -96,8 +100,10 @@ public class WordListApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (WordList) ApiInvoker.deserialize(response, "", WordList.class); } @@ -126,8 +132,10 @@ public class WordListApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); if(response != null){ return ; } @@ -164,8 +172,10 @@ public class WordListApi { if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", WordListWord.class); } @@ -194,8 +204,10 @@ public class WordListApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); if(response != null){ return ; } diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListsApi.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListsApi.java index b7544882efd..c8d669e48d3 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListsApi.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordListsApi.java @@ -34,8 +34,10 @@ public class WordListsApi { throw new ApiException(400, "missing required params"); } headerParams.put("auth_token", auth_token); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams, contentType); if(response != null){ return (WordList) ApiInvoker.deserialize(response, "", WordList.class); } diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordsApi.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordsApi.java index 478e07bca37..a543bf2c70a 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordsApi.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/api/WordsApi.java @@ -2,8 +2,8 @@ package com.wordnik.client.api; import com.wordnik.client.common.ApiException; import com.wordnik.client.common.ApiInvoker; -import com.wordnik.client.model.WordObject; import com.wordnik.client.model.DefinitionSearchResults; +import com.wordnik.client.model.WordObject; import com.wordnik.client.model.WordOfTheDay; import com.wordnik.client.model.WordSearchResults; import java.util.*; @@ -58,8 +58,10 @@ public class WordsApi { queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (WordSearchResults) ApiInvoker.deserialize(response, "", WordSearchResults.class); } @@ -85,8 +87,10 @@ public class WordsApi { if(!"null".equals(String.valueOf(date))) queryParams.put("date", String.valueOf(date)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (WordOfTheDay) ApiInvoker.deserialize(response, "", WordOfTheDay.class); } @@ -146,8 +150,10 @@ public class WordsApi { queryParams.put("skip", String.valueOf(skip)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (DefinitionSearchResults) ApiInvoker.deserialize(response, "", DefinitionSearchResults.class); } @@ -195,8 +201,10 @@ public class WordsApi { queryParams.put("sortOrder", String.valueOf(sortOrder)); if(!"null".equals(String.valueOf(limit))) queryParams.put("limit", String.valueOf(limit)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (List) ApiInvoker.deserialize(response, "List", WordObject.class); } @@ -238,8 +246,10 @@ public class WordsApi { queryParams.put("minLength", String.valueOf(minLength)); if(!"null".equals(String.valueOf(maxLength))) queryParams.put("maxLength", String.valueOf(maxLength)); + String contentType = "application/json"; + try { - String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); + String response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, contentType); if(response != null){ return (WordObject) ApiInvoker.deserialize(response, "", WordObject.class); } diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java index d07eb075db6..8344a2ab37f 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/common/ApiInvoker.java @@ -44,9 +44,8 @@ public class ApiInvoker { return response; } else if(String.class.equals(cls)) { - if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) { + if(json != null && json.startsWith("\"") && json.endsWith("\"") && json.length() > 1) return json.substring(1, json.length() - 2); - } else return json; } @@ -61,15 +60,17 @@ public class ApiInvoker { public static String serialize(Object obj) throws ApiException { try { - if (obj != null) return JsonUtil.getJsonMapper().writeValueAsString(obj); - else return null; + if (obj != null) + return JsonUtil.getJsonMapper().writeValueAsString(obj); + else + return null; } catch (Exception e) { throw new ApiException(500, e.getMessage()); } } - public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams) throws ApiException { + public String invokeAPI(String host, String path, String method, Map queryParams, Object body, Map headerParams, String contentType) throws ApiException { Client client = getClient(host); StringBuilder b = new StringBuilder(); @@ -77,14 +78,16 @@ public class ApiInvoker { for(String key : queryParams.keySet()) { String value = queryParams.get(key); if (value != null){ - if(b.toString().length() == 0) b.append("?"); - else b.append("&"); + if(b.toString().length() == 0) + b.append("?"); + else + b.append("&"); b.append(escapeString(key)).append("=").append(escapeString(value)); } } String querystring = b.toString(); - Builder builder = client.resource(host + path + querystring).type("application/json"); + Builder builder = client.resource(host + path + querystring).accept("application/json"); for(String key : headerParams.keySet()) { builder.header(key, headerParams.get(key)); } @@ -100,13 +103,22 @@ public class ApiInvoker { response = (ClientResponse) builder.get(ClientResponse.class); } else if ("POST".equals(method)) { + if(body == null) response = builder.post(ClientResponse.class, serialize(body)); + else + response = builder.type("application/json").post(ClientResponse.class, serialize(body)); } else if ("PUT".equals(method)) { - response = builder.put(ClientResponse.class, serialize(body)); - } + if(body == null) + response = builder.put(ClientResponse.class, serialize(body)); + else + response = builder.type("application/json").put(ClientResponse.class, serialize(body)); + } else if ("DELETE".equals(method)) { + if(body == null) response = builder.delete(ClientResponse.class, serialize(body)); + else + response = builder.type("application/json").delete(ClientResponse.class, serialize(body)); } else { throw new ApiException(500, "unknown method type " + method); @@ -122,12 +134,12 @@ public class ApiInvoker { } private Client getClient(String host) { - if(!hostMap.containsKey(host)) { - Client client = Client.create(); - client.addFilter(new LoggingFilter()); - hostMap.put(host, client); - } - return hostMap.get(host); + if(!hostMap.containsKey(host)) { + Client client = Client.create(); + client.addFilter(new LoggingFilter()); + hostMap.put(host, client); + } + return hostMap.get(host); } } diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Definition.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Definition.java index f4c2d9b4d69..42b728893f2 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Definition.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Definition.java @@ -1,12 +1,12 @@ package com.wordnik.client.model; import java.util.*; -import com.wordnik.client.model.ExampleUsage; -import com.wordnik.client.model.Note; -import com.wordnik.client.model.Citation; -import com.wordnik.client.model.TextPron; import com.wordnik.client.model.Label; +import com.wordnik.client.model.ExampleUsage; +import com.wordnik.client.model.TextPron; +import com.wordnik.client.model.Citation; import com.wordnik.client.model.Related; +import com.wordnik.client.model.Note; public class Definition { private String extendedText = null; private String text = null; diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Example.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Example.java index 58f09de0172..3f0e59b043e 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Example.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/Example.java @@ -1,8 +1,8 @@ package com.wordnik.client.model; import com.wordnik.client.model.Sentence; -import com.wordnik.client.model.ScoredWord; import com.wordnik.client.model.ContentProvider; +import com.wordnik.client.model.ScoredWord; public class Example { private Long id = null; private Long exampleId = null; diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java new file mode 100644 index 00000000000..71086647e59 --- /dev/null +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/ScrabbleScoreResult.java @@ -0,0 +1,21 @@ +package com.wordnik.client.model; + +public class ScrabbleScoreResult { + private Integer value = null; + public Integer getValue() { + return value; + } + public void setValue(Integer value) { + this.value = value; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ScrabbleScoreResult {\n"); + sb.append(" value: ").append(value).append("\n"); + sb.append("}\n"); + return sb.toString(); + } +} + diff --git a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/WordOfTheDay.java b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/WordOfTheDay.java index 70f67fd3f87..9027c6cb0e0 100644 --- a/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/WordOfTheDay.java +++ b/samples/client/wordnik-api/java/src/main/java/com/wordnik/client/model/WordOfTheDay.java @@ -2,8 +2,8 @@ package com.wordnik.client.model; import java.util.Date; import java.util.*; -import com.wordnik.client.model.SimpleDefinition; import com.wordnik.client.model.SimpleExample; +import com.wordnik.client.model.SimpleDefinition; import com.wordnik.client.model.ContentProvider; public class WordOfTheDay { private Long id = null; diff --git a/samples/client/wordnik-api/scala/pom.xml b/samples/client/wordnik-api/scala/pom.xml index 9981cc63fe7..68162889d15 100644 --- a/samples/client/wordnik-api/scala/pom.xml +++ b/samples/client/wordnik-api/scala/pom.xml @@ -5,16 +5,12 @@ swagger-client jar swagger-client - 1.0.0 + 1.0 2.2.0 + - - scala-tools.org - Scala-Tools Maven2 Repository - http://scala-tools.org/repo-releases - maven-mongodb-plugin-repo maven mongodb plugin repository @@ -113,9 +109,9 @@ - org.scala-tools - maven-scala-plugin - 2.15.2 + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} scala-compile-first @@ -160,6 +156,12 @@ ${jersey-version} compile + + com.sun.jersey.contribs + jersey-multipart + ${jersey-version} + compile + org.scala-lang scala-library @@ -194,5 +196,7 @@ 1.6.1 4.8.1 1.6.1 + 3.1.5 + diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala index eb041156311..a5dd0901880 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala @@ -1,11 +1,15 @@ package com.wordnik.client.api -import com.wordnik.client.model.ApiTokenStatus -import com.wordnik.client.model.WordList import com.wordnik.client.model.User +import com.wordnik.client.model.WordList +import com.wordnik.client.model.ApiTokenStatus import com.wordnik.client.model.AuthenticationToken import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException + +import java.io.File +import java.util.Date + import scala.collection.mutable.HashMap class AccountApi { @@ -16,20 +20,24 @@ class AccountApi { def authenticate (username: String, password: String) : Option[AuthenticationToken]= { // create path and map variables - val path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escapeString(username)) + val path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(username, password) - null).size match { + (List(username, password).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } if(String.valueOf(password) != "null") queryParams += "password" -> password.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[AuthenticationToken]).asInstanceOf[AuthenticationToken]) case _ => None @@ -41,19 +49,26 @@ class AccountApi { } def authenticatePost (username: String, body: String) : Option[AuthenticationToken]= { // create path and map variables - val path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escapeString(username)) + val path = "/account.{format}/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(username, body) - null).size match { + (List(username, body).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[AuthenticationToken]).asInstanceOf[AuthenticationToken]) case _ => None @@ -65,12 +80,16 @@ class AccountApi { } def getWordListsForLoggedInUser (auth_token: String, skip: Int= 0, limit: Int= 50) : Option[List[WordList]]= { // create path and map variables - val path = "/account.{format}/wordLists".replaceAll("\\{format\\}","json")// query params + val path = "/account.{format}/wordLists".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(auth_token) - null).size match { + (List(auth_token).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -78,7 +97,7 @@ class AccountApi { if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[WordList]).asInstanceOf[List[WordList]]) case _ => None @@ -90,13 +109,17 @@ class AccountApi { } def getApiTokenStatus (api_key: String) : Option[ApiTokenStatus]= { // create path and map variables - val path = "/account.{format}/apiTokenStatus".replaceAll("\\{format\\}","json")// query params + val path = "/account.{format}/apiTokenStatus".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] headerParams += "api_key" -> api_key try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[ApiTokenStatus]).asInstanceOf[ApiTokenStatus]) case _ => None @@ -108,18 +131,22 @@ class AccountApi { } def getLoggedInUser (auth_token: String) : Option[User]= { // create path and map variables - val path = "/account.{format}/user".replaceAll("\\{format\\}","json")// query params + val path = "/account.{format}/user".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(auth_token) - null).size match { + (List(auth_token).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) case _ => None diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala index 15add3527d7..cab9db7e07a 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala @@ -1,17 +1,22 @@ package com.wordnik.client.api -import com.wordnik.client.model.Definition -import com.wordnik.client.model.TextPron -import com.wordnik.client.model.Example -import com.wordnik.client.model.Syllable -import com.wordnik.client.model.AudioFile -import com.wordnik.client.model.ExampleSearchResults -import com.wordnik.client.model.WordObject -import com.wordnik.client.model.Bigram -import com.wordnik.client.model.Related import com.wordnik.client.model.FrequencySummary +import com.wordnik.client.model.Bigram +import com.wordnik.client.model.WordObject +import com.wordnik.client.model.ExampleSearchResults +import com.wordnik.client.model.Example +import com.wordnik.client.model.ScrabbleScoreResult +import com.wordnik.client.model.TextPron +import com.wordnik.client.model.Syllable +import com.wordnik.client.model.Related +import com.wordnik.client.model.Definition +import com.wordnik.client.model.AudioFile import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException + +import java.io.File +import java.util.Date + import scala.collection.mutable.HashMap class WordApi { @@ -22,14 +27,18 @@ class WordApi { def getExamples (word: String, includeDuplicates: String= "false", useCanonical: String= "false", skip: Int= 0, limit: Int= 5) : Option[ExampleSearchResults]= { // create path and map variables - val path = "/word.{format}/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -38,7 +47,7 @@ class WordApi { if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[ExampleSearchResults]).asInstanceOf[ExampleSearchResults]) case _ => None @@ -50,21 +59,25 @@ class WordApi { } def getWord (word: String, useCanonical: String= "false", includeSuggestions: String= "true") : Option[WordObject]= { // create path and map variables - val path = "/word.{format}/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString if(String.valueOf(includeSuggestions) != "null") queryParams += "includeSuggestions" -> includeSuggestions.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[WordObject]).asInstanceOf[WordObject]) case _ => None @@ -76,14 +89,18 @@ class WordApi { } def getDefinitions (word: String, partOfSpeech: String, sourceDictionaries: String, limit: Int= 200, includeRelated: String= "false", useCanonical: String= "false", includeTags: String= "false") : Option[List[Definition]]= { // create path and map variables - val path = "/word.{format}/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -94,7 +111,7 @@ class WordApi { if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString if(String.valueOf(includeTags) != "null") queryParams += "includeTags" -> includeTags.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[Definition]).asInstanceOf[List[Definition]]) case _ => None @@ -106,20 +123,24 @@ class WordApi { } def getTopExample (word: String, useCanonical: String= "false") : Option[Example]= { // create path and map variables - val path = "/word.{format}/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[Example]).asInstanceOf[Example]) case _ => None @@ -131,14 +152,18 @@ class WordApi { } def getRelatedWords (word: String, relationshipTypes: String, useCanonical: String= "false", limitPerRelationshipType: Int= 10) : Option[List[Related]]= { // create path and map variables - val path = "/word.{format}/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -146,7 +171,7 @@ class WordApi { if(String.valueOf(relationshipTypes) != "null") queryParams += "relationshipTypes" -> relationshipTypes.toString if(String.valueOf(limitPerRelationshipType) != "null") queryParams += "limitPerRelationshipType" -> limitPerRelationshipType.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[Related]).asInstanceOf[List[Related]]) case _ => None @@ -158,14 +183,18 @@ class WordApi { } def getTextPronunciations (word: String, sourceDictionary: String, typeFormat: String, useCanonical: String= "false", limit: Int= 50) : Option[List[TextPron]]= { // create path and map variables - val path = "/word.{format}/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -174,7 +203,7 @@ class WordApi { if(String.valueOf(typeFormat) != "null") queryParams += "typeFormat" -> typeFormat.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[TextPron]).asInstanceOf[List[TextPron]]) case _ => None @@ -186,14 +215,18 @@ class WordApi { } def getHyphenation (word: String, sourceDictionary: String, useCanonical: String= "false", limit: Int= 50) : Option[List[Syllable]]= { // create path and map variables - val path = "/word.{format}/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -201,7 +234,7 @@ class WordApi { if(String.valueOf(sourceDictionary) != "null") queryParams += "sourceDictionary" -> sourceDictionary.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[Syllable]).asInstanceOf[List[Syllable]]) case _ => None @@ -213,14 +246,18 @@ class WordApi { } def getWordFrequency (word: String, useCanonical: String= "false", startYear: Int= 1800, endYear: Int= 2012) : Option[FrequencySummary]= { // create path and map variables - val path = "/word.{format}/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -228,7 +265,7 @@ class WordApi { if(String.valueOf(startYear) != "null") queryParams += "startYear" -> startYear.toString if(String.valueOf(endYear) != "null") queryParams += "endYear" -> endYear.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[FrequencySummary]).asInstanceOf[FrequencySummary]) case _ => None @@ -240,14 +277,18 @@ class WordApi { } def getPhrases (word: String, limit: Int= 5, wlmi: Int= 0, useCanonical: String= "false") : Option[List[Bigram]]= { // create path and map variables - val path = "/word.{format}/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -255,7 +296,7 @@ class WordApi { if(String.valueOf(wlmi) != "null") queryParams += "wlmi" -> wlmi.toString if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[Bigram]).asInstanceOf[List[Bigram]]) case _ => None @@ -267,20 +308,24 @@ class WordApi { } def getEtymologies (word: String, useCanonical: String) : Option[List[String]]= { // create path and map variables - val path = "/word.{format}/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[String]).asInstanceOf[List[String]]) case _ => None @@ -292,21 +337,25 @@ class WordApi { } def getAudio (word: String, useCanonical: String= "false", limit: Int= 50) : Option[List[AudioFile]]= { // create path and map variables - val path = "/word.{format}/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escapeString(word)) + val path = "/word.{format}/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(word) - null).size match { + (List(word).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[AudioFile]).asInstanceOf[List[AudioFile]]) case _ => None @@ -316,5 +365,33 @@ class WordApi { case ex: ApiException => throw ex } } + def getScrabbleScore (word: String) : Option[ScrabbleScoreResult]= { + // create path and map variables + val path = "/word.{format}/{word}/scrabbleScore".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + val contentType = { + "application/json"} + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + // verify required params are set + (List(word).filter(_ != null)).size match { + case 1 => // all required values set + case _ => throw new Exception("missing required params") + } + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[ScrabbleScoreResult]).asInstanceOf[ScrabbleScoreResult]) + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } } diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala index 5ab720ae1aa..bc4124f6c2a 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala @@ -1,10 +1,14 @@ package com.wordnik.client.api +import com.wordnik.client.model.WordListWord import com.wordnik.client.model.WordList import com.wordnik.client.model.StringValue -import com.wordnik.client.model.WordListWord import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException + +import java.io.File +import java.util.Date + import scala.collection.mutable.HashMap class WordListApi { @@ -15,20 +19,27 @@ class WordListApi { def updateWordList (permalink: String, body: WordList, auth_token: String) = { // create path and map variables - val path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escapeString(permalink)) + val path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(permalink, auth_token) - null).size match { + (List(permalink, auth_token).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => case _ => None } @@ -39,20 +50,24 @@ class WordListApi { } def deleteWordList (permalink: String, auth_token: String) = { // create path and map variables - val path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escapeString(permalink)) + val path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(permalink, auth_token) - null).size match { + (List(permalink, auth_token).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => case _ => None } @@ -63,20 +78,24 @@ class WordListApi { } def getWordListByPermalink (permalink: String, auth_token: String) : Option[WordList]= { // create path and map variables - val path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escapeString(permalink)) + val path = "/wordList.{format}/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(permalink, auth_token) - null).size match { + (List(permalink, auth_token).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[WordList]).asInstanceOf[WordList]) case _ => None @@ -86,22 +105,29 @@ class WordListApi { case ex: ApiException => throw ex } } - def addWordsToWordList (permalink: String, body: Array[StringValue], auth_token: String) = { + def addWordsToWordList (permalink: String, body: List[StringValue], auth_token: String) = { // create path and map variables - val path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escapeString(permalink)) + val path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(permalink, auth_token) - null).size match { + (List(permalink, auth_token).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => case _ => None } @@ -112,14 +138,18 @@ class WordListApi { } def getWordListWords (permalink: String, auth_token: String, sortBy: String= "createDate", sortOrder: String= "desc", skip: Int= 0, limit: Int= 100) : Option[List[WordListWord]]= { // create path and map variables - val path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escapeString(permalink)) + val path = "/wordList.{format}/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(permalink, auth_token) - null).size match { + (List(permalink, auth_token).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } @@ -129,7 +159,7 @@ class WordListApi { if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[WordListWord]).asInstanceOf[List[WordListWord]]) case _ => None @@ -139,22 +169,29 @@ class WordListApi { case ex: ApiException => throw ex } } - def deleteWordsFromWordList (permalink: String, body: Array[StringValue], auth_token: String) = { + def deleteWordsFromWordList (permalink: String, body: List[StringValue], auth_token: String) = { // create path and map variables - val path = "/wordList.{format}/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escapeString(permalink)) + val path = "/wordList.{format}/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + } // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(permalink, auth_token) - null).size match { + (List(permalink, auth_token).filter(_ != null)).size match { case 2 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => case _ => None } diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListsApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListsApi.scala index 8a3236c59f4..cd854997b61 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListsApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListsApi.scala @@ -3,6 +3,10 @@ package com.wordnik.client.api import com.wordnik.client.model.WordList import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException + +import java.io.File +import java.util.Date + import scala.collection.mutable.HashMap class WordListsApi { @@ -13,18 +17,25 @@ class WordListsApi { def createWordList (body: WordList, auth_token: String) : Option[WordList]= { // create path and map variables - val path = "/wordLists.{format}".replaceAll("\\{format\\}","json")// query params + val path = "/wordLists.{format}".replaceAll("\\{format\\}","json") + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + } + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(auth_token) - null).size match { + (List(auth_token).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } headerParams += "auth_token" -> auth_token try { - apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[WordList]).asInstanceOf[WordList]) case _ => None diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala index 3e748fbee2f..a5b96d4f3f2 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala @@ -1,11 +1,15 @@ package com.wordnik.client.api -import com.wordnik.client.model.WordObject import com.wordnik.client.model.DefinitionSearchResults +import com.wordnik.client.model.WordObject import com.wordnik.client.model.WordOfTheDay import com.wordnik.client.model.WordSearchResults import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException + +import java.io.File +import java.util.Date + import scala.collection.mutable.HashMap class WordsApi { @@ -16,14 +20,18 @@ class WordsApi { def searchWords (query: String, includePartOfSpeech: String, excludePartOfSpeech: String, caseSensitive: String= "true", minCorpusCount: Int= 5, maxCorpusCount: Int= -1, minDictionaryCount: Int= 1, maxDictionaryCount: Int= -1, minLength: Int= 1, maxLength: Int= -1, skip: Int= 0, limit: Int= 10) : Option[WordSearchResults]= { // create path and map variables - val path = "/words.{format}/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}",apiInvoker.escapeString(query)) + val path = "/words.{format}/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}",apiInvoker.escape(query)) + + + val contentType = { + "application/json"} // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(query) - null).size match { + (List(query).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -39,7 +47,7 @@ class WordsApi { if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[WordSearchResults]).asInstanceOf[WordSearchResults]) case _ => None @@ -51,13 +59,17 @@ class WordsApi { } def getWordOfTheDay (date: String) : Option[WordOfTheDay]= { // create path and map variables - val path = "/words.{format}/wordOfTheDay".replaceAll("\\{format\\}","json")// query params + val path = "/words.{format}/wordOfTheDay".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] if(String.valueOf(date) != "null") queryParams += "date" -> date.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[WordOfTheDay]).asInstanceOf[WordOfTheDay]) case _ => None @@ -69,12 +81,16 @@ class WordsApi { } def reverseDictionary (query: String, findSenseForWord: String, includeSourceDictionaries: String, excludeSourceDictionaries: String, includePartOfSpeech: String, excludePartOfSpeech: String, expandTerms: String, sortBy: String, sortOrder: String, minCorpusCount: Int= 5, maxCorpusCount: Int= -1, minLength: Int= 1, maxLength: Int= -1, includeTags: String= "false", skip: String= "0", limit: Int= 10) : Option[DefinitionSearchResults]= { // create path and map variables - val path = "/words.{format}/reverseDictionary".replaceAll("\\{format\\}","json")// query params + val path = "/words.{format}/reverseDictionary".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] // verify required params are set - (Set(query) - null).size match { + (List(query).filter(_ != null)).size match { case 1 => // all required values set case _ => throw new Exception("missing required params") } @@ -95,7 +111,7 @@ class WordsApi { if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[DefinitionSearchResults]).asInstanceOf[DefinitionSearchResults]) case _ => None @@ -107,7 +123,11 @@ class WordsApi { } def getRandomWords (includePartOfSpeech: String, excludePartOfSpeech: String, sortBy: String, sortOrder: String, hasDictionaryDef: String= "true", minCorpusCount: Int= 0, maxCorpusCount: Int= -1, minDictionaryCount: Int= 1, maxDictionaryCount: Int= -1, minLength: Int= 5, maxLength: Int= -1, limit: Int= 10) : Option[List[WordObject]]= { // create path and map variables - val path = "/words.{format}/randomWords".replaceAll("\\{format\\}","json")// query params + val path = "/words.{format}/randomWords".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] @@ -124,7 +144,7 @@ class WordsApi { if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "List", classOf[WordObject]).asInstanceOf[List[WordObject]]) case _ => None @@ -136,7 +156,11 @@ class WordsApi { } def getRandomWord (includePartOfSpeech: String, excludePartOfSpeech: String, hasDictionaryDef: String= "true", minCorpusCount: Int= 0, maxCorpusCount: Int= -1, minDictionaryCount: Int= 1, maxDictionaryCount: Int= -1, minLength: Int= 5, maxLength: Int= -1) : Option[WordObject]= { // create path and map variables - val path = "/words.{format}/randomWord".replaceAll("\\{format\\}","json")// query params + val path = "/words.{format}/randomWord".replaceAll("\\{format\\}","json") + val contentType = { + "application/json"} + + // query params val queryParams = new HashMap[String, String] val headerParams = new HashMap[String, String] @@ -150,7 +174,7 @@ class WordsApi { if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString try { - apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap) match { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { case s: String => Some(ApiInvoker.deserialize(s, "", classOf[WordObject]).asInstanceOf[WordObject]) case _ => None diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala index 1da17e02c94..794070ae89c 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/common/ApiInvoker.scala @@ -6,6 +6,10 @@ import com.sun.jersey.api.client.config.ClientConfig import com.sun.jersey.api.client.config.DefaultClientConfig import com.sun.jersey.api.client.filter.LoggingFilter +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File import java.net.URLEncoder import javax.ws.rs.core.MediaType @@ -36,12 +40,16 @@ object ApiInvoker { val defaultHeaders: HashMap[String, String] = HashMap() val hostMap: HashMap[String, Client] = HashMap() - def escapeString(value: String): String = { + def escape(value: String): String = { URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") } + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + def deserialize(json: String, containerType: String, cls: Class[_]) = { - if (cls == classOf[String] && containerType == null) { + if (cls == classOf[String]) { json match { case s: String => { if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) @@ -50,8 +58,13 @@ object ApiInvoker { case _ => null } } else { - containerType match { - case "List" => { + containerType.toLowerCase match { + case "array" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case "list" => { val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] response.asScala.toList @@ -75,12 +88,11 @@ object ApiInvoker { } else null } - def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String]) = { + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { val client = getClient(host) - val querystring = queryParams.filter(k => k._2 != null).map(k => (escapeString(k._1) + "=" + escapeString(k._2))).mkString("?", "&", "") - val builder = client.resource(host + path + querystring).`type`("application/json") - + val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) headerParams.map(p => builder.header(p._1, p._2)) defaultHeaders.map(p => { headerParams.contains(p._1) match { @@ -94,22 +106,43 @@ object ApiInvoker { builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] } case "POST" => { - builder.post(classOf[ClientResponse], serialize(body)) + if(body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName()) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } + else { + if(body == null) builder.post(classOf[ClientResponse], serialize(body)) + else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } } case "PUT" => { - builder.put(classOf[ClientResponse], serialize(body)) + if(body == null) builder.put(classOf[ClientResponse], null) + else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) } case "DELETE" => { builder.delete(classOf[ClientResponse]) } case _ => null } - response.getClientResponseStatus() match { - case ClientResponse.Status.OK => response.getEntity(classOf[String]) + response.getClientResponseStatus().getStatusCode() match { + case 204 => "" + case code: Int if (Range(200, 299).contains(code)) => { + response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "" + } + } case _ => { + val entity = response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "no data" + } throw new ApiException( response.getClientResponseStatus().getStatusCode(), - response.getEntity(classOf[String])) + entity) } } } @@ -127,11 +160,6 @@ object ApiInvoker { } } -class ApiException extends Exception { - var code = 0 +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) - def this(code: Int, msg: String) = { - this() - } -} diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala index 67d29195bf3..9f2996d793c 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala @@ -1,11 +1,11 @@ package com.wordnik.client.model -import com.wordnik.client.model.ExampleUsage -import com.wordnik.client.model.Note -import com.wordnik.client.model.Citation -import com.wordnik.client.model.TextPron import com.wordnik.client.model.Label +import com.wordnik.client.model.ExampleUsage +import com.wordnik.client.model.TextPron +import com.wordnik.client.model.Citation import com.wordnik.client.model.Related +import com.wordnik.client.model.Note case class Definition ( extendedText: String, text: String, diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala index 3d3e45996a2..349ec7e70a5 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala @@ -1,8 +1,8 @@ package com.wordnik.client.model import com.wordnik.client.model.Sentence -import com.wordnik.client.model.ScoredWord import com.wordnik.client.model.ContentProvider +import com.wordnik.client.model.ScoredWord case class Example ( id: Long, exampleId: Long, diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala new file mode 100644 index 00000000000..2e275f2fe7b --- /dev/null +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/ScrabbleScoreResult.scala @@ -0,0 +1,5 @@ +package com.wordnik.client.model + +case class ScrabbleScoreResult ( + value: Int) + diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala index 3c64a66571b..dccf9403f2d 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala @@ -1,8 +1,8 @@ package com.wordnik.client.model import java.util.Date -import com.wordnik.client.model.SimpleDefinition import com.wordnik.client.model.SimpleExample +import com.wordnik.client.model.SimpleDefinition import com.wordnik.client.model.ContentProvider case class WordOfTheDay ( id: Long, diff --git a/samples/client/wordnik-api/scala/src/test/scala/WordListApiTest.scala b/samples/client/wordnik-api/scala/src/test/scala/WordListApiTest.scala index f609862ffa3..75d9ff7511b 100644 --- a/samples/client/wordnik-api/scala/src/test/scala/WordListApiTest.scala +++ b/samples/client/wordnik-api/scala/src/test/scala/WordListApiTest.scala @@ -63,12 +63,13 @@ class WordListApiTest extends FlatSpec with ShouldMatchers with BaseApiTest { } it should "add words to a list" in { - val wordsToAdd = new ListBuffer[StringValue] - wordsToAdd += StringValue("delicious") - wordsToAdd += StringValue("tasty") - wordsToAdd += StringValue("scrumptious") + val wordsToAdd = List( + StringValue("delicious"), + StringValue("tasty"), + StringValue("scrumptious") + ) - api.addWordsToWordList(sampleList.permalink, wordsToAdd.toArray, auth.token) + api.addWordsToWordList(sampleList.permalink, wordsToAdd, auth.token) } it should "get word list words" in { @@ -81,11 +82,12 @@ class WordListApiTest extends FlatSpec with ShouldMatchers with BaseApiTest { } it should "remove words from a list" in { - val wordsToRemove = new ListBuffer[StringValue] - wordsToRemove += StringValue("delicious") - wordsToRemove += StringValue("tasty") + val wordsToRemove = List( + StringValue("delicious"), + StringValue("tasty") + ) - api.deleteWordsFromWordList(sampleList.permalink, wordsToRemove.toArray, auth.token) + api.deleteWordsFromWordList(sampleList.permalink, wordsToRemove, auth.token) api.getWordListWords(sampleList.permalink, auth.token).get.size should be(1) } From c4990b773d325add9b68bca5431a98f32f22aae3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:43:26 -0700 Subject: [PATCH 06/20] regenerated client --- .../petstore/objc/ObjcPetstoreCodegen.scala | 25 +- .../contents.xcworkspacedata | 1 + .../xcshareddata/PetstoreClient.xccheckout | 41 + .../UserInterfaceState.xcuserstate | Bin 0 -> 14324 bytes .../PetstoreClient.xcodeproj/project.pbxproj | 600 ++++--- .../xcshareddata/PetstoreClient.xccheckout | 41 + .../UserInterfaceState.xcuserstate | Bin 40923 -> 8581 bytes .../xcdebugger/Breakpoints.xcbkptlist | 5 - .../xcdebugger/Breakpoints_v2.xcbkptlist | 101 -- .../xcschemes/PetstoreClient.xcscheme | 28 +- .../xcschemes/xcschememanagement.plist | 9 +- .../PetstoreClient/AppDelegate.h | 15 + .../PetstoreClient/AppDelegate.m | 46 + .../Base.lproj/Main_iPad.storyboard | 26 + .../Base.lproj/Main_iPhone.storyboard | 26 + .../AppIcon.appiconset/Contents.json | 53 + .../LaunchImage.launchimage/Contents.json | 51 + .../PetstoreClient/PetstoreClient-Info.plist | 49 + .../PetstoreClient/PetstoreClient-Prefix.pch | 16 +- .../PetstoreClient/PetstoreClient.1 | 79 - .../PetstoreClient/ViewController.h | 13 + .../PetstoreClient/ViewController.m | 36 + .../PetstoreClient/en.lproj/InfoPlist.strings | 2 + .../objc/PetstoreClient/PetstoreClient/main.m | 18 +- .../PetstoreClientTests-Info.plist | 22 + .../PetstoreClientTests/PetstoreClientTests.m | 34 + .../en.lproj/InfoPlist.strings | 2 + samples/client/petstore/objc/Podfile | 4 + samples/client/petstore/objc/Podfile.lock | 10 + .../AFNetworking/AFNetworking/AFHTTPClient.h | 641 ++++++++ .../AFNetworking/AFNetworking/AFHTTPClient.m | 1396 ++++++++++++++++ .../AFNetworking/AFHTTPRequestOperation.h | 133 ++ .../AFNetworking/AFHTTPRequestOperation.m | 327 ++++ .../AFNetworking/AFImageRequestOperation.h | 113 ++ .../AFNetworking/AFImageRequestOperation.m | 321 ++++ .../AFNetworking/AFJSONRequestOperation.h | 71 + .../AFNetworking/AFJSONRequestOperation.m | 150 ++ .../AFNetworkActivityIndicatorManager.h | 75 + .../AFNetworkActivityIndicatorManager.m | 157 ++ .../AFNetworking/AFNetworking/AFNetworking.h | 43 + .../AFPropertyListRequestOperation.h | 68 + .../AFPropertyListRequestOperation.m | 143 ++ .../AFNetworking/AFURLConnectionOperation.h | 370 +++++ .../AFNetworking/AFURLConnectionOperation.m | 848 ++++++++++ .../AFNetworking/AFXMLRequestOperation.h | 89 ++ .../AFNetworking/AFXMLRequestOperation.m | 167 ++ .../AFNetworking/UIImageView+AFNetworking.h | 78 + .../AFNetworking/UIImageView+AFNetworking.m | 191 +++ .../petstore/objc/Pods/AFNetworking/LICENSE | 19 + .../petstore/objc/Pods/AFNetworking/README.md | 208 +++ .../BuildHeaders/AFNetworking/AFHTTPClient.h | 1 + .../AFNetworking/AFHTTPRequestOperation.h | 1 + .../AFNetworking/AFImageRequestOperation.h | 1 + .../AFNetworking/AFJSONRequestOperation.h | 1 + .../AFNetworkActivityIndicatorManager.h | 1 + .../BuildHeaders/AFNetworking/AFNetworking.h | 1 + .../AFPropertyListRequestOperation.h | 1 + .../AFNetworking/AFURLConnectionOperation.h | 1 + .../AFNetworking/AFXMLRequestOperation.h | 1 + .../AFNetworking/UIImageView+AFNetworking.h | 1 + .../Pods/Headers/AFNetworking/AFHTTPClient.h | 1 + .../AFNetworking/AFHTTPRequestOperation.h | 1 + .../AFNetworking/AFImageRequestOperation.h | 1 + .../AFNetworking/AFJSONRequestOperation.h | 1 + .../AFNetworkActivityIndicatorManager.h | 1 + .../Pods/Headers/AFNetworking/AFNetworking.h | 1 + .../AFPropertyListRequestOperation.h | 1 + .../AFNetworking/AFURLConnectionOperation.h | 1 + .../AFNetworking/AFXMLRequestOperation.h | 1 + .../AFNetworking/UIImageView+AFNetworking.h | 1 + .../client/petstore/objc/Pods/Manifest.lock | 10 + .../Pods/Pods-AFNetworking-Private.xcconfig | 5 + .../objc/Pods/Pods-AFNetworking-dummy.m | 5 + .../objc/Pods/Pods-AFNetworking-prefix.pch | 19 + .../objc/Pods/Pods-AFNetworking.xcconfig | 1 + .../objc/Pods/Pods-acknowledgements.markdown | 26 + .../objc/Pods/Pods-acknowledgements.plist | 56 + .../client/petstore/objc/Pods/Pods-dummy.m | 5 + .../petstore/objc/Pods/Pods-environment.h | 14 + .../petstore/objc/Pods/Pods-resources.sh | 47 + .../client/petstore/objc/Pods/Pods.xcconfig | 4 + .../objc/Pods/Pods.xcodeproj/project.pbxproj | 1419 +++++++++++++++++ .../xcschemes/Pods-AFNetworking.xcscheme | 59 + .../tony.xcuserdatad/xcschemes/Pods.xcscheme} | 28 +- .../xcschemes/xcschememanagement.plist | 52 + .../petstore/objc/client/NIKApiInvoker.h | 40 - .../petstore/objc/client/NIKApiInvoker.m | 336 ---- .../petstore/objc/client/NIKSwaggerObject.h | 6 - .../petstore/objc/client/NIKSwaggerObject.m | 10 - .../client/petstore/objc/client/RVBCategory.h | 16 - .../client/petstore/objc/client/RVBOrder.h | 23 - samples/client/petstore/objc/client/RVBPet.h | 26 - .../client/petstore/objc/client/RVBPetApi.h | 71 - .../client/petstore/objc/client/RVBPetApi.m | 617 ------- .../client/petstore/objc/client/RVBStoreApi.m | 312 ---- samples/client/petstore/objc/client/RVBTag.h | 16 - samples/client/petstore/objc/client/RVBUser.h | 28 - .../client/petstore/objc/client/RVBUserApi.m | 842 ---------- .../petstore/objc/client/SWGApiClient.h | 64 + .../petstore/objc/client/SWGApiClient.m | 419 +++++ .../client/petstore/objc/client/SWGCategory.h | 18 + .../client/{RVBCategory.m => SWGCategory.m} | 18 +- .../objc/client/{NIKDate.h => SWGDate.h} | 4 +- .../objc/client/{NIKDate.m => SWGDate.m} | 4 +- .../objc/client/{NIKFile.h => SWGFile.h} | 8 +- .../objc/client/{NIKFile.m => SWGFile.m} | 4 +- .../client/petstore/objc/client/SWGObject.h | 6 + .../client/petstore/objc/client/SWGObject.m | 17 + .../client/petstore/objc/client/SWGOrder.h | 28 + .../objc/client/{RVBOrder.m => SWGOrder.m} | 39 +- samples/client/petstore/objc/client/SWGPet.h | 32 + .../objc/client/{RVBPet.m => SWGPet.m} | 89 +- .../client/petstore/objc/client/SWGPetApi.h | 102 ++ .../client/petstore/objc/client/SWGPetApi.m | 564 +++++++ .../client/{RVBStoreApi.h => SWGStoreApi.h} | 25 +- .../client/petstore/objc/client/SWGStoreApi.m | 205 +++ samples/client/petstore/objc/client/SWGTag.h | 18 + .../objc/client/{RVBTag.m => SWGTag.m} | 18 +- samples/client/petstore/objc/client/SWGUser.h | 36 + .../objc/client/{RVBUser.m => SWGUser.m} | 28 +- .../client/{RVBUserApi.h => SWGUserApi.h} | 37 +- .../client/petstore/objc/client/SWGUserApi.m | 504 ++++++ 122 files changed, 10391 insertions(+), 2970 deletions(-) create mode 100644 samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata create mode 100644 samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout create mode 100644 samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace/xcshareddata/PetstoreClient.xccheckout delete mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist delete mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPad.storyboard create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPhone.storyboard create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/LaunchImage.launchimage/Contents.json create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Info.plist delete mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient.1 create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClient/en.lproj/InfoPlist.strings create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests-Info.plist create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/en.lproj/InfoPlist.strings create mode 100644 samples/client/petstore/objc/Podfile create mode 100644 samples/client/petstore/objc/Podfile.lock create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/LICENSE create mode 100644 samples/client/petstore/objc/Pods/AFNetworking/README.md create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h create mode 120000 samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h create mode 100644 samples/client/petstore/objc/Pods/Manifest.lock create mode 100644 samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig create mode 100644 samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m create mode 100644 samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch create mode 100644 samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig create mode 100644 samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown create mode 100644 samples/client/petstore/objc/Pods/Pods-acknowledgements.plist create mode 100644 samples/client/petstore/objc/Pods/Pods-dummy.m create mode 100644 samples/client/petstore/objc/Pods/Pods-environment.h create mode 100755 samples/client/petstore/objc/Pods/Pods-resources.sh create mode 100644 samples/client/petstore/objc/Pods/Pods.xcconfig create mode 100644 samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj create mode 100644 samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme rename samples/client/petstore/objc/{PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClientTests.xcscheme => Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme} (73%) create mode 100644 samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist delete mode 100644 samples/client/petstore/objc/client/NIKApiInvoker.h delete mode 100644 samples/client/petstore/objc/client/NIKApiInvoker.m delete mode 100644 samples/client/petstore/objc/client/NIKSwaggerObject.h delete mode 100644 samples/client/petstore/objc/client/NIKSwaggerObject.m delete mode 100644 samples/client/petstore/objc/client/RVBCategory.h delete mode 100644 samples/client/petstore/objc/client/RVBOrder.h delete mode 100644 samples/client/petstore/objc/client/RVBPet.h delete mode 100644 samples/client/petstore/objc/client/RVBPetApi.h delete mode 100644 samples/client/petstore/objc/client/RVBPetApi.m delete mode 100644 samples/client/petstore/objc/client/RVBStoreApi.m delete mode 100644 samples/client/petstore/objc/client/RVBTag.h delete mode 100644 samples/client/petstore/objc/client/RVBUser.h delete mode 100644 samples/client/petstore/objc/client/RVBUserApi.m create mode 100644 samples/client/petstore/objc/client/SWGApiClient.h create mode 100644 samples/client/petstore/objc/client/SWGApiClient.m create mode 100644 samples/client/petstore/objc/client/SWGCategory.h rename samples/client/petstore/objc/client/{RVBCategory.m => SWGCategory.m} (64%) rename samples/client/petstore/objc/client/{NIKDate.h => SWGDate.h} (72%) rename samples/client/petstore/objc/client/{NIKDate.m => SWGDate.m} (95%) rename samples/client/petstore/objc/client/{NIKFile.h => SWGFile.h} (75%) rename samples/client/petstore/objc/client/{NIKFile.m => SWGFile.m} (90%) create mode 100644 samples/client/petstore/objc/client/SWGObject.h create mode 100644 samples/client/petstore/objc/client/SWGObject.m create mode 100644 samples/client/petstore/objc/client/SWGOrder.h rename samples/client/petstore/objc/client/{RVBOrder.m => SWGOrder.m} (57%) create mode 100644 samples/client/petstore/objc/client/SWGPet.h rename samples/client/petstore/objc/client/{RVBPet.m => SWGPet.m} (62%) create mode 100644 samples/client/petstore/objc/client/SWGPetApi.h create mode 100644 samples/client/petstore/objc/client/SWGPetApi.m rename samples/client/petstore/objc/client/{RVBStoreApi.h => SWGStoreApi.h} (60%) create mode 100644 samples/client/petstore/objc/client/SWGStoreApi.m create mode 100644 samples/client/petstore/objc/client/SWGTag.h rename samples/client/petstore/objc/client/{RVBTag.m => SWGTag.m} (65%) create mode 100644 samples/client/petstore/objc/client/SWGUser.h rename samples/client/petstore/objc/client/{RVBUser.m => SWGUser.m} (66%) rename samples/client/petstore/objc/client/{RVBUserApi.h => SWGUserApi.h} (62%) create mode 100644 samples/client/petstore/objc/client/SWGUserApi.m diff --git a/samples/client/petstore/objc/ObjcPetstoreCodegen.scala b/samples/client/petstore/objc/ObjcPetstoreCodegen.scala index d76b7cd0258..5c554e9099c 100644 --- a/samples/client/petstore/objc/ObjcPetstoreCodegen.scala +++ b/samples/client/petstore/objc/ObjcPetstoreCodegen.scala @@ -20,20 +20,25 @@ object ObjcPetstoreCodegen extends BasicObjcGenerator { def main(args: Array[String]) = generateClient(args) // where to write generated code - override def destinationDir = "samples/client/petstore/objc/client" + val outputFolder = "samples/client/petstore/objc/" + override def destinationDir = outputFolder + java.io.File.separator + "client" // to avoid recompiling ... - override def templateDir = "src/main/resources/objc" + override def templateDir = "objc" + + additionalParams ++= Map("projectName" -> "PetstoreClient") // supporting classes override def supportingFiles = List( - ("NIKSwaggerObject.h", destinationDir, "NIKSwaggerObject.h"), - ("NIKSwaggerObject.m", destinationDir, "NIKSwaggerObject.m"), - ("NIKApiInvoker.h", destinationDir, "NIKApiInvoker.h"), - ("NIKApiInvoker.m", destinationDir, "NIKApiInvoker.m"), - ("NIKFile.h", destinationDir, "NIKFile.h"), - ("NIKFile.m", destinationDir, "NIKFile.m"), - ("NIKDate.h", destinationDir, "NIKDate.h"), - ("NIKDate.m", destinationDir, "NIKDate.m")) + ("SWGObject.h", destinationDir, "SWGObject.h"), + ("SWGObject.m", destinationDir, "SWGObject.m"), + ("SWGApiClient.h", destinationDir, "SWGApiClient.h"), + ("SWGApiClient.m", destinationDir, "SWGApiClient.m"), + ("SWGFile.h", destinationDir, "SWGFile.h"), + ("SWGFile.m", destinationDir, "SWGFile.m"), + ("SWGDate.h", destinationDir, "SWGDate.h"), + ("SWGDate.m", destinationDir, "SWGDate.m"), + ("Podfile.mustache", outputFolder, "Podfile") + ) } diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata b/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata new file mode 100644 index 00000000000..834f64caf7e --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient.xcworkspace/contents.xcworkspacedata @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout new file mode 100644 index 00000000000..66f3c15bca7 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcshareddata/PetstoreClient.xccheckout @@ -0,0 +1,41 @@ + + + + + IDESourceControlProjectFavoriteDictionaryKey + + IDESourceControlProjectIdentifier + 81EB09FA-DD8C-4FE1-82D3-1FB6FF0D9C43 + IDESourceControlProjectName + PetstoreClient + IDESourceControlProjectOriginsDictionary + + 92840518-904D-4771-AA3D-9AF52CA48B71 + ssh://github.com/wordnik/swagger-codegen.git + + IDESourceControlProjectPath + samples/client/petstore/objc/PetstoreClient.xcworkspace + IDESourceControlProjectRelativeInstallPathDictionary + + 92840518-904D-4771-AA3D-9AF52CA48B71 + ../../../../.. + + IDESourceControlProjectURL + ssh://github.com/wordnik/swagger-codegen.git + IDESourceControlProjectVersion + 110 + IDESourceControlProjectWCCIdentifier + 92840518-904D-4771-AA3D-9AF52CA48B71 + IDESourceControlProjectWCConfigurations + + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + 92840518-904D-4771-AA3D-9AF52CA48B71 + IDESourceControlWCCName + swagger-codegen + + + + diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate new file mode 100644 index 0000000000000000000000000000000000000000..742c5c4def3185ea558fd8de6745c5f7f6f60685 GIT binary patch literal 14324 zcmc&ad3;k<)^~a7nl@XLCT-KEv`N#_r27UUbcM=R+ER96XhR!mo0_CRS>y&qR0a`5 zL;;}%WN{Z%#0~cy1r(4)L>P1s1wj#n(eJ#xq-_9a=8tc_ul@bn_uf7C+;h)8`#n?I zn(Z!kX66?NBZ4U6kO&2Fom|)0jKDr;RM311gXg%71Hlrudljs?=7(I(#L@%LN&>QF-^a1(= zeUA2{1L!FF8hwxcfli|z&{>Qz!4z{?goAJ}4#A;ViB&intFZ>h;8+}owOEG@I2~u; zY@CPlaX;K27vpj~1P{Z*@d!K~PrwuLBs>}4hNt0X+=5&2?RW;BiRa=4_-?!q--GYP zOYt)NAX0l$b}!f)VR_)Yv4{s4c9zr_3T0elR9gU{d}@lW_H zK1T?lgd-vnM1n~O2_<1fN@OIOsELLokQ8DhnIwx8k$$9vl#-!j7^x#;$XGItSV%o- zA+5wg+Q{u>A-RX#OYS3!$lu6faz9x@9w1A}aTbf<{s~RnTavrg2nDlV~zc zqnR|H-b4q{Vmgvm(NVOT*3eoynogj%(k5!Bw^1i`Q8%4Q@1XPOLV6Fqm)=Jg(Ff>q zx`A${Tj*2tY5F|fMqi>k=&STK`X+sg?xvs7&*>3*lzvT5(;w&=dWl}9ztbyRFc-pw za$%f`i{{i^JeR=fI3t(JrEz_^bS|GO;0n1SZV-11Hk-5MHS_RnWp^A>}*qRURk-R zxG+24l$TdtnweKoQdp9oW06KxmX(ijIH$SVto61sM}2#Xt<~*cScMXhaWjfWYNSCi zC>F&bEsAF%7Q}*C2n%IlES!lqBOOXaeNYn6p+N>@U=b{mNm(_}6wIc;uVpg7ioLbL zF{8q1ZLwLTiSS{hv%%)HHFU3DYn@W+XmvXs&CQ_J7U|8sNedXX6cra1=9CqcnF_K> zGflbKrTM0ktfE3wMQ&bpad~c0S$<)*MXKpuwX(GW`01*5+H9@E9SuN0dT-k11B=g!^hJ^LJ#*NHU1N6B7PfC^C&>Nj3E_Euoz zSmDv;0_iArI;|aD0MLKzh?KsFZ3;+U4jvjnDNiL4Jx+JYKU6R@fZew$GXY6S&I zW<|iNO!%#5bJ-p6Y#HC|#a{~|2#W(X!m?gztN}6_tj-3WtvuDj5GZGz;NOJzn)WFz zAiLvxO_VBNMwxA@wY}M0W}DL9C@@Rs`&7kGcez1~t8Hygn+qPSZt$0&Trw|sqs`fy z?flyQ?>we2&}=jZ%>@&52bzZ%@>ryDr^DeESjBH;gjboO8*Q!jc9%dHuST|+Zec{- z=Crq1ogLQ=u{?&Do)zv#ccQysfd%Mpv=A1#1Ko!fp}(QUW5JI%H#lvrb!}Go>z+{0 z<85`oPuXndQZGzrEit^T@RcJL@!%|r~GxPet4(RSgUE_PL zlg9c^s2MZ3%H}R^vzuE48?g~RZjr{pf<4Ru?Dp11FTGV(yR!>zLjC^@jIiDo)WuA! zZ(V&e&radnQ}8W=^_>i>xkj5Z$y8Q>A?{U5L6#}4$eMXD&PtMwn0|B$=TPM!@n8WK49DtgT#HC}sk zJ!}n>xi0iNkM2K)50w2~ApQ42AUO{$X89np1q=zI@GkEH7$}R+1$>A;vPe^asBYN_ zu!n)l*@ZslY5GsWg>8R|c3Y%L|G^4f=rbPse*)_FMSIXbWb8zHS-(#71?$f&7O7sa z4g%qpzcN~W1P9R}9>G`arcQL24Pchq;h>lP(PQWYlCMYKpyTLUb~78u2CYXY!7`s> z#bAwZP;?3yR+Wr+cFNr5VLN;;aH3#a3mYX zhO-fD~vjLVSd5fkh<9re`P}O z1;G}M#|aZh)O1TkM;DGq{d;*3oQV4f9)wL`b%Me7$^cFQ^No!-6{oQ=Y%Cks%Y4I` z_6@MD-WQw$Ms@tZHmZK}Y3TMSL+x&}APs)znQOeqPzv^PAHE5N;{j+M9*DN_>BAJO z%QgZ2J8jM2F5zPaJXH#4D}Ztg^>z87)<1dn&Itk-p%%KV?D0m z`5|n$5`-S#!mLaJVasfRi4e~g76Lo-3JT`V4fRXLNL-7I8*mjKg{yH5YhX4ul{Id_ zqj4P`gU7Na*2-qF*~~I_m~E;rAXI`a>JC)81D)}L#o$Azan<(5CNHpm84GUUm$?;N z@f2Lo?Cdr+jWut8ETsxJLWouk=AeZS%q-H_I?#50ZxFHDX7E9ftJ*rF&f4r1ro3*prNr0wD znfZ99u9l~ExV5p>?rv|ebu&9@5IcwXA3x6f@ZtcR_v0mO2Aj!hdw8BSs9oxvBS_40 z{LtiXdGV$t>+y0vG4Z2(7(c@Ab0wS83Hb%&6R=MR8(ofO8yGs!YyL?6z>ndz$hdAD zv-m%B;SK!k^=w`z-pJU$;?fqLOIz_1%){>L;nLIixqux#kGHY;>`vGbh?$^HNrUF^ z2;jmF{7S%_SMh6X0lS;GUlN$rJ8DiEWM|&Fy(2R}@o(dIyN~!ib}zFC$N3>o=tuZt zb{|{ZL+Eb2Ct%UNcpqED{>Eynk_LII0_Z!44_^a%6hQB1wMl~p>lfGuUq*n=DJcldkwbeb(^+u+jo@|k7 z|6+<@zx|B*8D9pUiO=H;_!s;uzKDOrm)JvW1$&sSWRI{%*{V(WcYFn31&vO^e-gx2 zvo)*>^tzfo%bpWz4nBWT4PIL~CqFqt8pant%4fDg@?~rA>Xz`CFHXP|hK^3ctVfYnQEQz4q}M&_fj z$Czg4L7|{9Cui-picNgfZM14M0Rojg2G9nc3xs;0fI4a_OG;VFowiYrFg+%upc0hs-C3@4+IaXkQyBvk67ubvI ziJkXP>?N;v0uJzE1R_>Ht<=%NC-8hs<~>}{B7O*5)yUT7j!MXkVU%Z-H~Ve{X^$!^ z8C=^0Nqoad=csmDyN$Q0QsUpPlgxqo25}KLX(!Xk3^J2+kXd9ldztNIudr9yYwUIQ z2HVBn+=7zG9b_J1@P9tJ6aFp$^4?-^vv=YDd+dGq`vHGkJhA0Yr^DGT!9H!_YcBzs zD1#5BQ0B9?xoi#IlLbq`&-Ux0H*348-hc^S zytbS?;sb}$Em@7{tYbo6K-Tv9-sOGvAI3(q$?p`%X7-WKDUc`dob}{M@)UWReav>V zJ>8ChJV&|^mYm>S2!w*) zuuKm&dvKNq=X-FS2af^KuI5EMsstE0t<7O?b-TP}V8|K43B>s7Y`qdPSB1j~Q8Wlt zv=9@3P73Aa5?d2wnGWYfp^jWr-(=$};ZeeCb$csBjiABa>XSv9In3&E^IG3*gQa?M zVqsbdMDh*ZiBLR+A_N#o@Na%^C9DS|s09rO%n*Fk6}PojKn=}R**e_bYVW2M2nu-j zg=Kz5pC=c2n{|Qwg8pE~*|%)sdh#2&L@u)v>}L;-;F*;Y;NJrmHxF|(`pL9N3j|2- z-<&F;=HoN0*QPZAFn((OpcFzG@+Uq@3(M(uQAFjibm77_)@LV5(Jsqu$Q z{$ukO&-~t)>S;>gBtN#k)O6#4EShuUfdX2@4-~TVowOhOCGg+|dN+8%BE4hkf2DjF z7!PFxzM8$F!q+7;{M##`Ly&PJEv03&oL11m>{oV?{l+e_%NuDWy@d{?!{~7KJGGPJvVDj<9;&i@!FR?!7iizX7Np zb*ygE7-PTHHq(Q)jm&*jmH zkO$F8bTa#=2cvF(N3FD>x9g!cI+gvw{^VUxVh=9@^5mXuH))V9zyZ=}w6!-jyqC7I zMIMa#Wa)0B*XMO_prjpcA*!0d-ukXLygr_`L%D-a_h61mzMvgY^@iFvokeHUfpqRT zmp4X%P|bsbJXpjocyKshZu)BAy-4e40Hb$8bV@yRz6S?;a7Y)ui!SisP!A4cmN7m_ zs1w+EO{m^YoDZsp@7@@N{*5m7XIXx$dad%Vr}xt(eCbw5#{LTI#p^ws49vtbxQV*7UaFhqDJXrlWT|*zEYw0@LNxM8a#)GvUtn=U` z4^HvmzJV&giC1|KhMLl}|BlZ4?h)Y1peL$m>TOk@6ey5cq<8&yCeJE3X9b9|3MlA5M?0faNTPQr0Ye2E~Q1f`2T~hK!%#Y08X{fG`H0U z9P29rjnV(7f)#Ljy95d}|A)6>e!YF0e!y3NuC2|}59vpIZQg@pJva^m-x_A&&DOq8 zrzhP%jxXtEXXO_8YY%h}-G4(Y2k1coOS}gs^kDhwpyq=Q$MRSTvU9qT9HS?1h~)3| zlz=4BgZuO#IXLQ}AI}S}&|A_@cj`KUX#-NjgJfG zq&LJT>VKvq`v>=yxIDR>DUZr{QA3X>wpQGdj6A5B7Cp@I@w}x^#`B@Xt%+ zlEK$-eK;_(*&dwJ#pyYN2j_Zl9v_nM`EwaWAoVtXYzG%y-QT?TOKzy3!QHe)y18Mx z8*XR;)?{yMasfwOt=U=IeCR05`f!tDig>*(|Z>GpEBp>S>**UVpl zHNXw(NEw+p#otki3FSmV{crluI!T`j4v|P>V&jtaeY0{4d_8)hVd3J4NNBn8u|w#{ zf*Mh=8+tCLw7YFC=z|k8I8HTGFHSaoVev$fF$@4OL68f5TBuSgaln zDGLL1**Sjty0X*YJug4-(ln3%SXcygw_Z$X5ZKk#FYSikp_(zGW~i+LsvN$C-aP|u zuH}1=7=~6}8FV8iArrLj7C;}{P-xzr01a9WXxMc@v+g|TCAuG4bXTLtpl4=1+6dh) zTcAOA2YM4)bN8Tw&>V0Qor1>Ps~E!twGtX{6X3Qs0~g>jJQ!Evp>RDp7Fum@g$CO; z+>YT640qw}&_4UBz+i%f|Ikqv@Pl9X;9I;=IM>QKCUsW|`Mdk|@Tm>;2R`#}ehqPQ z9S}2vlDoNfu8f<(&Gf4JFb^IM+U~(4Jb2{e+$=nXo5Rh83(_$jT*YR2@F)*lp3Z__ z(EmRFT2Y1S>AwL2n!vpCeIkJtE5MTQKsD|TzNhiuK=POPUdW_DAp(c?atlEd@8Ry{ z<(_W|;$w?LA+ZY~^{N(Fwut+iz#Ur`w}{V9q_vI)YlqJ2)@Aq0%+pm3m!1Zh=C2z} zy=(a1oQzwF;W{w_luf9&au4A-Tj?suLLR1tlu+!g6Fov#LK5OlMWpOJI}HURC>wdR z6FCD5d7apC>$wf1y}cG*$hsmk+W$ov>iL4 z&G-Sj4BCrVKrZwsT@6XkI{F+m7{355#xK)XpvCwNXfl4A?xh!@UAP7sfj4lwxWn9U zA|#?BktkRs6~&5@Md_j}Q9sdO(Rk5B(PYuBqA8*V(Ns~B=r&QaXr9O;x>K}3v`}=f zXpv~KXo+a4=s{7ZXuD{a=v)vD$_^?IstsxhniaG-Xi3o0pa+8<3VJx`k)TyUYl7AW zJs-3^=*6HNK|6z94SGFjSI}EQ?*zRUv?u6v(4}BWa7=J!a7}Py@T}lP!Rvx|27eiR zAo#1`!@);`F9!b^5)>j2$qOkCDGezP85~j>GBjj($dr)wkh?-24%rs+LdZ)YFNeGm z@>2fDhdq_m4?QKYC{u3`-bL*)`X4?oe|1H=ZD@Ex+rvc=!(#lp_@Xt zhwcjfDD;!i-Jzd{^$#lx8y{u~YY)34Y)jbFVPA!v5BnwTV%Vjy-@|EmPJu|U%X#@P<%*yMEte*8}YZ|li~~FU&X(PFN?2; z|0(`60!PpYX+&H^LB!CA#)t(GOCz3&*ctJ5#JdsiM|>FZal{u9`y&oU9Evy+@pZ)I zNL{2kvM$mR*&Nvt>5iNmd0*s`$PJN?M{bVX8u?`8(~&Plz8<+N@~y~sBHxSrEOJle zzQ`kyUq^lu`H#pSB7cm$DhZW@OClr^Nui`%GF&oFGC?v)Vv#gSS|u(?hh)BFrDUyS zv*ZcMQ<7&S?@8X5d?7h1IVL$SIU)JG9e`%StLOMix zi*%TDv~-MgoOFV8lGGxdD}7Y@nsmSPnDiUzx6-rH^U`0Wzez7kugD}awM;8ZkR{5J zWSO!&S%IubcC&1dtVC8OtCrbht+E-iyJYvu7ReUNmdTdOR>)S$x@1qtw#(j@eIz>| zJ0v?IJ0?3WJ0bf`&dEjcAbE&fDOby5^M7~u1pnRqLQTb~5WAbO^FU#MR@0EWkKOjFOKO+BH{+;}c{3rQ2 z`FZ)D3QiHE2vI~RBnp{Ap@>pw6={kLMV2B*QK;yrxJhxdVz8oCF-c)jSQYgOo1#_G zrf@3Uis_1(idBl8irtEz6j!3cqQp^=QPL=RR8*8IN*$FFl^WGI$`q9ml@*l}l^0bI zRS`8d$`SQo)bmlFMqO1ZlsaXSQm-^B)0FATo0UVABa~Ij8s%u^80A!DqtdOMq3lr3 zQQo0s%EiiM%H_%x%2moW%C*W)<>Sh2${os`%2$&?4OIa^--)dkhB zs^3(Xqobm8qlZQhj~*Z0677h-J=zuB9z7$vBYJl9+~|4H%c7S@uZUh5{b=;+=*Obh zMR!GSh<-f!&FIggPexx-2dfj*IqH$>2K8+9UFrquh3W^?Yt$RmTh-gt+tn|s-%#&T zzoq_I{fTI>?t8mbX#f;FL%))N5>-MvYxFL&G$SHOn;1H7hi$G;1_#HJzI6n%81tV~jBaVg|+( z$CSpD#|)0Cj2Rj;JZ5CfsFbS?^_Qib@_ifzCxKr9#tx=n%P1l;W_1ZSA zOWUrUshy>rqg|=psNJmHs(niPjP^P0>)JQ9Z)@MvexUtGdq8_gdqjIodt7@$dro^n z`>Xbn_IK^o_|W+9_=tE(`~&f8;y1@{jej!!>G)^kpO1en{*CxIx9)!3!@5UxYjkUM&+2ySUeoQ;y`_6sw_A5u_l@p^?v(Ba z-A}robr*D35=o*gv2S8-Vr}At#My~U6CX=lo478qEAg4cR}>`g*-h->7fXyY$obGxf9dbMy=J zOZ2Pt8}*y?Tl7!ppVGgme_8*k{&oE>{agBv^rd;?=zr3m)1TL0(f?t<25Jx) zf(=qbj3LF4X~;I@8uAT=hGIjRVX&dnFw8K*Fvf7J!ETstm}l@9?ldegEHpe|c+jxI zu+p%~u*UGX;aS7WhW8Ag8TJ_V8NM_eFnnV;VK`;@-f-G*#_($jNs*+;QDp$e3^JZyaJAX{cP~*sb8laPd$-(CiQIUA8Fxf@-$_dIxRM>Pntf>nASJVl$M`1Agv;8 zMEcX|&!z87{~-Od^!@24($A$|NWYkVIsIz-pC)3GnB=A?Q?x0@6laPz=}hIO+f2(% zubbXCeQr8vI&L~?`qA`@>9SdDjx_f%_cfa#HP1HpH&>Z!%ys5*<_YFWW{cTst~XCL b+s)I=bItS3_Xr^&A;N!dV?Yp%%=i5dTlCa$ literal 0 HcmV?d00001 diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index 07d67a5b92b..65087ed0f36 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -7,233 +7,245 @@ objects = { /* Begin PBXBuildFile section */ - EA07F4BE16134F27006A2112 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA07F4BD16134F27006A2112 /* Foundation.framework */; }; - EA07F4C116134F27006A2112 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = EA07F4C016134F27006A2112 /* main.m */; }; - EA07F4C516134F27006A2112 /* PetstoreClient.1 in CopyFiles */ = {isa = PBXBuildFile; fileRef = EA07F4C416134F27006A2112 /* PetstoreClient.1 */; }; - EA07F5311613580E006A2112 /* SenTestingKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA07F5301613580E006A2112 /* SenTestingKit.framework */; }; - EA07F53316135819006A2112 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA07F53216135819006A2112 /* Cocoa.framework */; }; - EA4F4D3816F1A90A00F24B35 /* NIKFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EA4F4D3716F1A90A00F24B35 /* NIKFile.m */; }; - EAE9042217BF2F7900486EFE /* NIKApiInvoker.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040617BF2F3A00486EFE /* NIKApiInvoker.h */; }; - EAE9042317BF2F7900486EFE /* NIKApiInvoker.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040717BF2F3A00486EFE /* NIKApiInvoker.m */; }; - EAE9042417BF2F7900486EFE /* NIKDate.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040817BF2F3A00486EFE /* NIKDate.h */; }; - EAE9042517BF2F7900486EFE /* NIKDate.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040917BF2F3A00486EFE /* NIKDate.m */; }; - EAE9042617BF2F7900486EFE /* NIKSwaggerObject.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040A17BF2F3A00486EFE /* NIKSwaggerObject.h */; }; - EAE9042717BF2F7900486EFE /* NIKSwaggerObject.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040B17BF2F3A00486EFE /* NIKSwaggerObject.m */; }; - EAE9042817BF2F7900486EFE /* RVBCategory.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F617BF2CB200486EFE /* RVBCategory.h */; }; - EAE9042917BF2F7900486EFE /* RVBCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F717BF2CB200486EFE /* RVBCategory.m */; }; - EAE9042A17BF2F7900486EFE /* RVBOrder.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F817BF2CB200486EFE /* RVBOrder.h */; }; - EAE9042B17BF2F7900486EFE /* RVBOrder.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903F917BF2CB200486EFE /* RVBOrder.m */; }; - EAE9042C17BF2F7900486EFE /* RVBPet.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FA17BF2CB200486EFE /* RVBPet.h */; }; - EAE9042D17BF2F7900486EFE /* RVBPet.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FB17BF2CB200486EFE /* RVBPet.m */; }; - EAE9042E17BF2F7900486EFE /* RVBPetApi.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FC17BF2CB200486EFE /* RVBPetApi.h */; }; - EAE9042F17BF2F7900486EFE /* RVBPetApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FD17BF2CB200486EFE /* RVBPetApi.m */; }; - EAE9043017BF2F7900486EFE /* RVBStoreApi.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FE17BF2CB200486EFE /* RVBStoreApi.h */; }; - EAE9043117BF2F7900486EFE /* RVBStoreApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE903FF17BF2CB200486EFE /* RVBStoreApi.m */; }; - EAE9043217BF2F7900486EFE /* RVBTag.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040017BF2CB200486EFE /* RVBTag.h */; }; - EAE9043317BF2F7900486EFE /* RVBTag.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040117BF2CB200486EFE /* RVBTag.m */; }; - EAE9043417BF2F7900486EFE /* RVBUser.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040217BF2CB200486EFE /* RVBUser.h */; }; - EAE9043517BF2F7900486EFE /* RVBUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040317BF2CB200486EFE /* RVBUser.m */; }; - EAE9043617BF2F7900486EFE /* RVBUserApi.h in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040417BF2CB200486EFE /* RVBUserApi.h */; }; - EAE9043717BF2F7900486EFE /* RVBUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAE9040517BF2CB200486EFE /* RVBUserApi.m */; }; - EAE9043817BF318800486EFE /* NIKFile.h in Sources */ = {isa = PBXBuildFile; fileRef = EA4F4D3616F1A90A00F24B35 /* NIKFile.h */; }; - EAE9043917BF318800486EFE /* NIKFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EA4F4D3716F1A90A00F24B35 /* NIKFile.m */; }; - EAE9043A17BF31C800486EFE /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA81837816137FD500341A6E /* PetApiTest.m */; }; - EAE9043B17BF31C800486EFE /* PetApiTest.h in Sources */ = {isa = PBXBuildFile; fileRef = EA81837916137FD500341A6E /* PetApiTest.h */; }; - EAE9043C17BF31C800486EFE /* UserApiTest.h in Sources */ = {isa = PBXBuildFile; fileRef = EA5A034216141443003B3E41 /* UserApiTest.h */; }; - EAE9043D17BF31C800486EFE /* UserApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA5A034316141443003B3E41 /* UserApiTest.m */; }; + BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; + EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; + EA66999C1811D2FA00A70D03 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */; }; + EA66999E1811D2FA00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; }; + EA6699A41811D2FA00A70D03 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = EA6699A21811D2FA00A70D03 /* InfoPlist.strings */; }; + EA6699A61811D2FA00A70D03 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699A51811D2FA00A70D03 /* main.m */; }; + EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699A91811D2FA00A70D03 /* AppDelegate.m */; }; + EA6699AD1811D2FA00A70D03 /* Main_iPhone.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = EA6699AB1811D2FA00A70D03 /* Main_iPhone.storyboard */; }; + EA6699B01811D2FA00A70D03 /* Main_iPad.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = EA6699AE1811D2FA00A70D03 /* Main_iPad.storyboard */; }; + EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699B21811D2FA00A70D03 /* ViewController.m */; }; + EA6699B51811D2FA00A70D03 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = EA6699B41811D2FA00A70D03 /* Images.xcassets */; }; + EA6699BC1811D2FB00A70D03 /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699BB1811D2FB00A70D03 /* XCTest.framework */; }; + EA6699BD1811D2FB00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; + EA6699BE1811D2FB00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; }; + EA6699C61811D2FB00A70D03 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = EA6699C41811D2FB00A70D03 /* InfoPlist.strings */; }; + EA6699C81811D2FB00A70D03 /* PetstoreClientTests.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */; }; + EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */; }; + EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */; }; + EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D11811D3AE00F06E69 /* SWGDate.m */; }; + EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D31811D3AE00F06E69 /* SWGFile.m */; }; + EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D51811D3AE00F06E69 /* SWGObject.m */; }; + EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D71811D3AE00F06E69 /* SWGOrder.m */; }; + EAEA85EA1811D3AE00F06E69 /* SWGPet.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D91811D3AE00F06E69 /* SWGPet.m */; }; + EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */; }; + EAEA85EC1811D3AE00F06E69 /* SWGStoreApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85DD1811D3AE00F06E69 /* SWGStoreApi.m */; }; + EAEA85ED1811D3AE00F06E69 /* SWGTag.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85DF1811D3AE00F06E69 /* SWGTag.m */; }; + EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E11811D3AE00F06E69 /* SWGUser.m */; }; + EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */; }; + EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = EAEA85F01811D8F100F06E69 /* libPods.a */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ - EA07F52E161357A5006A2112 /* PBXContainerItemProxy */ = { + EA6699BF1811D2FB00A70D03 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; - containerPortal = EA07F4B016134F27006A2112 /* Project object */; + containerPortal = EA66998E1811D2FA00A70D03 /* Project object */; proxyType = 1; - remoteGlobalIDString = EA07F4B816134F27006A2112; + remoteGlobalIDString = EA6699951811D2FA00A70D03; remoteInfo = PetstoreClient; }; /* End PBXContainerItemProxy section */ -/* Begin PBXCopyFilesBuildPhase section */ - EA07F4B716134F27006A2112 /* CopyFiles */ = { - isa = PBXCopyFilesBuildPhase; - buildActionMask = 2147483647; - dstPath = /usr/share/man/man1/; - dstSubfolderSpec = 0; - files = ( - EA07F4C516134F27006A2112 /* PetstoreClient.1 in CopyFiles */, - ); - runOnlyForDeploymentPostprocessing = 1; - }; -/* End PBXCopyFilesBuildPhase section */ - /* Begin PBXFileReference section */ - EA07F4B916134F27006A2112 /* PetstoreClient */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = PetstoreClient; sourceTree = BUILT_PRODUCTS_DIR; }; - EA07F4BD16134F27006A2112 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; - EA07F4C016134F27006A2112 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; - EA07F4C316134F27006A2112 /* PetstoreClient-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-Prefix.pch"; sourceTree = ""; }; - EA07F4C416134F27006A2112 /* PetstoreClient.1 */ = {isa = PBXFileReference; lastKnownFileType = text.man; path = PetstoreClient.1; sourceTree = ""; }; - EA07F4F21613521A006A2112 /* PetstoreClientTests.octest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PetstoreClientTests.octest; sourceTree = BUILT_PRODUCTS_DIR; }; - EA07F5301613580E006A2112 /* SenTestingKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SenTestingKit.framework; path = Library/Frameworks/SenTestingKit.framework; sourceTree = DEVELOPER_DIR; }; - EA07F53216135819006A2112 /* Cocoa.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Cocoa.framework; path = System/Library/Frameworks/Cocoa.framework; sourceTree = SDKROOT; }; - EA4F4D3616F1A90A00F24B35 /* NIKFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = NIKFile.h; path = ../client/NIKFile.h; sourceTree = ""; }; - EA4F4D3716F1A90A00F24B35 /* NIKFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = NIKFile.m; path = ../client/NIKFile.m; sourceTree = ""; }; - EA5A034216141443003B3E41 /* UserApiTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = UserApiTest.h; path = ../tests/UserApiTest.h; sourceTree = ""; }; - EA5A034316141443003B3E41 /* UserApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = UserApiTest.m; path = ../tests/UserApiTest.m; sourceTree = ""; }; - EA81837816137FD500341A6E /* PetApiTest.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = PetApiTest.m; path = ../tests/PetApiTest.m; sourceTree = ""; }; - EA81837916137FD500341A6E /* PetApiTest.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = PetApiTest.h; path = ../tests/PetApiTest.h; sourceTree = ""; }; - EAE903F617BF2CB200486EFE /* RVBCategory.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBCategory.h; path = ../client/RVBCategory.h; sourceTree = ""; }; - EAE903F717BF2CB200486EFE /* RVBCategory.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBCategory.m; path = ../client/RVBCategory.m; sourceTree = ""; }; - EAE903F817BF2CB200486EFE /* RVBOrder.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBOrder.h; path = ../client/RVBOrder.h; sourceTree = ""; }; - EAE903F917BF2CB200486EFE /* RVBOrder.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBOrder.m; path = ../client/RVBOrder.m; sourceTree = ""; }; - EAE903FA17BF2CB200486EFE /* RVBPet.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBPet.h; path = ../client/RVBPet.h; sourceTree = ""; }; - EAE903FB17BF2CB200486EFE /* RVBPet.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBPet.m; path = ../client/RVBPet.m; sourceTree = ""; }; - EAE903FC17BF2CB200486EFE /* RVBPetApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBPetApi.h; path = ../client/RVBPetApi.h; sourceTree = ""; }; - EAE903FD17BF2CB200486EFE /* RVBPetApi.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBPetApi.m; path = ../client/RVBPetApi.m; sourceTree = ""; }; - EAE903FE17BF2CB200486EFE /* RVBStoreApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBStoreApi.h; path = ../client/RVBStoreApi.h; sourceTree = ""; }; - EAE903FF17BF2CB200486EFE /* RVBStoreApi.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBStoreApi.m; path = ../client/RVBStoreApi.m; sourceTree = ""; }; - EAE9040017BF2CB200486EFE /* RVBTag.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBTag.h; path = ../client/RVBTag.h; sourceTree = ""; }; - EAE9040117BF2CB200486EFE /* RVBTag.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBTag.m; path = ../client/RVBTag.m; sourceTree = ""; }; - EAE9040217BF2CB200486EFE /* RVBUser.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBUser.h; path = ../client/RVBUser.h; sourceTree = ""; }; - EAE9040317BF2CB200486EFE /* RVBUser.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBUser.m; path = ../client/RVBUser.m; sourceTree = ""; }; - EAE9040417BF2CB200486EFE /* RVBUserApi.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = RVBUserApi.h; path = ../client/RVBUserApi.h; sourceTree = ""; }; - EAE9040517BF2CB200486EFE /* RVBUserApi.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = RVBUserApi.m; path = ../client/RVBUserApi.m; sourceTree = ""; }; - EAE9040617BF2F3A00486EFE /* NIKApiInvoker.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NIKApiInvoker.h; path = ../client/NIKApiInvoker.h; sourceTree = ""; }; - EAE9040717BF2F3A00486EFE /* NIKApiInvoker.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = NIKApiInvoker.m; path = ../client/NIKApiInvoker.m; sourceTree = ""; }; - EAE9040817BF2F3A00486EFE /* NIKDate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NIKDate.h; path = ../client/NIKDate.h; sourceTree = ""; }; - EAE9040917BF2F3A00486EFE /* NIKDate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = NIKDate.m; path = ../client/NIKDate.m; sourceTree = ""; }; - EAE9040A17BF2F3A00486EFE /* NIKSwaggerObject.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; name = NIKSwaggerObject.h; path = ../client/NIKSwaggerObject.h; sourceTree = ""; }; - EAE9040B17BF2F3A00486EFE /* NIKSwaggerObject.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; name = NIKSwaggerObject.m; path = ../client/NIKSwaggerObject.m; sourceTree = ""; }; + 73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; + EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.xcconfig; path = ../Pods/Pods.xcconfig; sourceTree = ""; }; + EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; + EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; + EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = CoreGraphics.framework; path = System/Library/Frameworks/CoreGraphics.framework; sourceTree = SDKROOT; }; + EA66999D1811D2FA00A70D03 /* UIKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = UIKit.framework; path = System/Library/Frameworks/UIKit.framework; sourceTree = SDKROOT; }; + EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClient-Info.plist"; sourceTree = ""; }; + EA6699A31811D2FA00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + EA6699A51811D2FA00A70D03 /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; + EA6699A71811D2FA00A70D03 /* PetstoreClient-Prefix.pch */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "PetstoreClient-Prefix.pch"; sourceTree = ""; }; + EA6699A81811D2FA00A70D03 /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; + EA6699A91811D2FA00A70D03 /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; + EA6699AC1811D2FA00A70D03 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main_iPhone.storyboard; sourceTree = ""; }; + EA6699AF1811D2FA00A70D03 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main_iPad.storyboard; sourceTree = ""; }; + EA6699B11811D2FA00A70D03 /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; + EA6699B21811D2FA00A70D03 /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; + EA6699B41811D2FA00A70D03 /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Images.xcassets; sourceTree = ""; }; + EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = PetstoreClientTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; + EA6699BB1811D2FB00A70D03 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; + EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClientTests-Info.plist"; sourceTree = ""; }; + EA6699C51811D2FB00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PetstoreClientTests.m; sourceTree = ""; }; + EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGApiClient.h; sourceTree = ""; }; + EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClient.m; sourceTree = ""; }; + EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGCategory.h; sourceTree = ""; }; + EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGCategory.m; sourceTree = ""; }; + EAEA85D01811D3AE00F06E69 /* SWGDate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGDate.h; sourceTree = ""; }; + EAEA85D11811D3AE00F06E69 /* SWGDate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGDate.m; sourceTree = ""; }; + EAEA85D21811D3AE00F06E69 /* SWGFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGFile.h; sourceTree = ""; }; + EAEA85D31811D3AE00F06E69 /* SWGFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGFile.m; sourceTree = ""; }; + EAEA85D41811D3AE00F06E69 /* SWGObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGObject.h; sourceTree = ""; }; + EAEA85D51811D3AE00F06E69 /* SWGObject.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGObject.m; sourceTree = ""; }; + EAEA85D61811D3AE00F06E69 /* SWGOrder.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGOrder.h; sourceTree = ""; }; + EAEA85D71811D3AE00F06E69 /* SWGOrder.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGOrder.m; sourceTree = ""; }; + EAEA85D81811D3AE00F06E69 /* SWGPet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGPet.h; sourceTree = ""; }; + EAEA85D91811D3AE00F06E69 /* SWGPet.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGPet.m; sourceTree = ""; }; + EAEA85DA1811D3AE00F06E69 /* SWGPetApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGPetApi.h; sourceTree = ""; }; + EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGPetApi.m; sourceTree = ""; }; + EAEA85DC1811D3AE00F06E69 /* SWGStoreApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGStoreApi.h; sourceTree = ""; }; + EAEA85DD1811D3AE00F06E69 /* SWGStoreApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGStoreApi.m; sourceTree = ""; }; + EAEA85DE1811D3AE00F06E69 /* SWGTag.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGTag.h; sourceTree = ""; }; + EAEA85DF1811D3AE00F06E69 /* SWGTag.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGTag.m; sourceTree = ""; }; + EAEA85E01811D3AE00F06E69 /* SWGUser.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUser.h; sourceTree = ""; }; + EAEA85E11811D3AE00F06E69 /* SWGUser.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUser.m; sourceTree = ""; }; + EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGUserApi.h; sourceTree = ""; }; + EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGUserApi.m; sourceTree = ""; }; + EAEA85F01811D8F100F06E69 /* libPods.a */ = {isa = PBXFileReference; lastKnownFileType = file; name = libPods.a; path = "../Pods/build/Debug-iphoneos/libPods.a"; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ - EA07F4B616134F27006A2112 /* Frameworks */ = { + EA6699931811D2FA00A70D03 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - EA07F4BE16134F27006A2112 /* Foundation.framework in Frameworks */, + EA66999C1811D2FA00A70D03 /* CoreGraphics.framework in Frameworks */, + EA66999E1811D2FA00A70D03 /* UIKit.framework in Frameworks */, + EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */, + BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; - EA07F4EE1613521A006A2112 /* Frameworks */ = { + EA6699B71811D2FB00A70D03 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - EA07F53316135819006A2112 /* Cocoa.framework in Frameworks */, - EA07F5311613580E006A2112 /* SenTestingKit.framework in Frameworks */, + EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */, + EA6699BC1811D2FB00A70D03 /* XCTest.framework in Frameworks */, + EA6699BE1811D2FB00A70D03 /* UIKit.framework in Frameworks */, + EA6699BD1811D2FB00A70D03 /* Foundation.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - EA07F4AE16134F27006A2112 = { + EA66998D1811D2FA00A70D03 = { isa = PBXGroup; children = ( - EA81837C1613809300341A6E /* Tests */, - EA07F52D1613569E006A2112 /* Generated Client */, - EA07F4BF16134F27006A2112 /* PetstoreClient */, - EA07F4BC16134F27006A2112 /* Frameworks */, - EA07F4BA16134F27006A2112 /* Products */, + EAEA85CB1811D3AE00F06E69 /* client */, + EA66999F1811D2FA00A70D03 /* PetstoreClient */, + EA6699C11811D2FB00A70D03 /* PetstoreClientTests */, + EA6699981811D2FA00A70D03 /* Frameworks */, + EA6699971811D2FA00A70D03 /* Products */, + EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */, ); sourceTree = ""; }; - EA07F4BA16134F27006A2112 /* Products */ = { + EA6699971811D2FA00A70D03 /* Products */ = { isa = PBXGroup; children = ( - EA07F4B916134F27006A2112 /* PetstoreClient */, - EA07F4F21613521A006A2112 /* PetstoreClientTests.octest */, + EA6699961811D2FA00A70D03 /* PetstoreClient.app */, + EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */, ); name = Products; sourceTree = ""; }; - EA07F4BC16134F27006A2112 /* Frameworks */ = { + EA6699981811D2FA00A70D03 /* Frameworks */ = { isa = PBXGroup; children = ( - EA07F53216135819006A2112 /* Cocoa.framework */, - EA07F5301613580E006A2112 /* SenTestingKit.framework */, - EA07F4BD16134F27006A2112 /* Foundation.framework */, - EA07F4F71613521A006A2112 /* Other Frameworks */, + EAEA85F01811D8F100F06E69 /* libPods.a */, + EA6699991811D2FA00A70D03 /* Foundation.framework */, + EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */, + EA66999D1811D2FA00A70D03 /* UIKit.framework */, + EA6699BB1811D2FB00A70D03 /* XCTest.framework */, + 73DA4F1067C343C3962F1542 /* libPods.a */, ); name = Frameworks; sourceTree = ""; }; - EA07F4BF16134F27006A2112 /* PetstoreClient */ = { + EA66999F1811D2FA00A70D03 /* PetstoreClient */ = { isa = PBXGroup; children = ( - EA07F4C016134F27006A2112 /* main.m */, - EA07F4C416134F27006A2112 /* PetstoreClient.1 */, - EA07F4C216134F27006A2112 /* Supporting Files */, + EA6699A81811D2FA00A70D03 /* AppDelegate.h */, + EA6699A91811D2FA00A70D03 /* AppDelegate.m */, + EA6699AB1811D2FA00A70D03 /* Main_iPhone.storyboard */, + EA6699AE1811D2FA00A70D03 /* Main_iPad.storyboard */, + EA6699B11811D2FA00A70D03 /* ViewController.h */, + EA6699B21811D2FA00A70D03 /* ViewController.m */, + EA6699B41811D2FA00A70D03 /* Images.xcassets */, + EA6699A01811D2FA00A70D03 /* Supporting Files */, ); path = PetstoreClient; sourceTree = ""; }; - EA07F4C216134F27006A2112 /* Supporting Files */ = { + EA6699A01811D2FA00A70D03 /* Supporting Files */ = { isa = PBXGroup; children = ( - EA07F4C316134F27006A2112 /* PetstoreClient-Prefix.pch */, + EA6699A11811D2FA00A70D03 /* PetstoreClient-Info.plist */, + EA6699A21811D2FA00A70D03 /* InfoPlist.strings */, + EA6699A51811D2FA00A70D03 /* main.m */, + EA6699A71811D2FA00A70D03 /* PetstoreClient-Prefix.pch */, ); name = "Supporting Files"; sourceTree = ""; }; - EA07F4F71613521A006A2112 /* Other Frameworks */ = { + EA6699C11811D2FB00A70D03 /* PetstoreClientTests */ = { isa = PBXGroup; children = ( + EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */, + EA6699C21811D2FB00A70D03 /* Supporting Files */, ); - name = "Other Frameworks"; + path = PetstoreClientTests; sourceTree = ""; }; - EA07F52D1613569E006A2112 /* Generated Client */ = { + EA6699C21811D2FB00A70D03 /* Supporting Files */ = { isa = PBXGroup; children = ( - EAE9040617BF2F3A00486EFE /* NIKApiInvoker.h */, - EAE9040717BF2F3A00486EFE /* NIKApiInvoker.m */, - EAE9040817BF2F3A00486EFE /* NIKDate.h */, - EAE9040917BF2F3A00486EFE /* NIKDate.m */, - EA4F4D3616F1A90A00F24B35 /* NIKFile.h */, - EA4F4D3716F1A90A00F24B35 /* NIKFile.m */, - EAE9040A17BF2F3A00486EFE /* NIKSwaggerObject.h */, - EAE9040B17BF2F3A00486EFE /* NIKSwaggerObject.m */, - EAE903F617BF2CB200486EFE /* RVBCategory.h */, - EAE903F717BF2CB200486EFE /* RVBCategory.m */, - EAE903F817BF2CB200486EFE /* RVBOrder.h */, - EAE903F917BF2CB200486EFE /* RVBOrder.m */, - EAE903FA17BF2CB200486EFE /* RVBPet.h */, - EAE903FB17BF2CB200486EFE /* RVBPet.m */, - EAE903FC17BF2CB200486EFE /* RVBPetApi.h */, - EAE903FD17BF2CB200486EFE /* RVBPetApi.m */, - EAE903FE17BF2CB200486EFE /* RVBStoreApi.h */, - EAE903FF17BF2CB200486EFE /* RVBStoreApi.m */, - EAE9040017BF2CB200486EFE /* RVBTag.h */, - EAE9040117BF2CB200486EFE /* RVBTag.m */, - EAE9040217BF2CB200486EFE /* RVBUser.h */, - EAE9040317BF2CB200486EFE /* RVBUser.m */, - EAE9040417BF2CB200486EFE /* RVBUserApi.h */, - EAE9040517BF2CB200486EFE /* RVBUserApi.m */, + EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */, + EA6699C41811D2FB00A70D03 /* InfoPlist.strings */, ); - name = "Generated Client"; + name = "Supporting Files"; sourceTree = ""; }; - EA81837C1613809300341A6E /* Tests */ = { + EAEA85CB1811D3AE00F06E69 /* client */ = { isa = PBXGroup; children = ( - EA81837816137FD500341A6E /* PetApiTest.m */, - EA81837916137FD500341A6E /* PetApiTest.h */, - EA5A034216141443003B3E41 /* UserApiTest.h */, - EA5A034316141443003B3E41 /* UserApiTest.m */, + EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */, + EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */, + EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */, + EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */, + EAEA85D01811D3AE00F06E69 /* SWGDate.h */, + EAEA85D11811D3AE00F06E69 /* SWGDate.m */, + EAEA85D21811D3AE00F06E69 /* SWGFile.h */, + EAEA85D31811D3AE00F06E69 /* SWGFile.m */, + EAEA85D41811D3AE00F06E69 /* SWGObject.h */, + EAEA85D51811D3AE00F06E69 /* SWGObject.m */, + EAEA85D61811D3AE00F06E69 /* SWGOrder.h */, + EAEA85D71811D3AE00F06E69 /* SWGOrder.m */, + EAEA85D81811D3AE00F06E69 /* SWGPet.h */, + EAEA85D91811D3AE00F06E69 /* SWGPet.m */, + EAEA85DA1811D3AE00F06E69 /* SWGPetApi.h */, + EAEA85DB1811D3AE00F06E69 /* SWGPetApi.m */, + EAEA85DC1811D3AE00F06E69 /* SWGStoreApi.h */, + EAEA85DD1811D3AE00F06E69 /* SWGStoreApi.m */, + EAEA85DE1811D3AE00F06E69 /* SWGTag.h */, + EAEA85DF1811D3AE00F06E69 /* SWGTag.m */, + EAEA85E01811D3AE00F06E69 /* SWGUser.h */, + EAEA85E11811D3AE00F06E69 /* SWGUser.m */, + EAEA85E21811D3AE00F06E69 /* SWGUserApi.h */, + EAEA85E31811D3AE00F06E69 /* SWGUserApi.m */, ); - name = Tests; + name = client; + path = ../client; sourceTree = ""; }; /* End PBXGroup section */ /* Begin PBXNativeTarget section */ - EA07F4B816134F27006A2112 /* PetstoreClient */ = { + EA6699951811D2FA00A70D03 /* PetstoreClient */ = { isa = PBXNativeTarget; - buildConfigurationList = EA07F4C816134F27006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; + buildConfigurationList = EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClient" */; buildPhases = ( - EA07F4B516134F27006A2112 /* Sources */, - EA07F4B616134F27006A2112 /* Frameworks */, - EA07F4B716134F27006A2112 /* CopyFiles */, + 04DAA264FD78471BBAD25173 /* Check Pods Manifest.lock */, + EA6699921811D2FA00A70D03 /* Sources */, + EA6699931811D2FA00A70D03 /* Frameworks */, + EA6699941811D2FA00A70D03 /* Resources */, + 3692D11BB04F489DAA7C0B6A /* Copy Pods Resources */, ); buildRules = ( ); @@ -241,152 +253,213 @@ ); name = PetstoreClient; productName = PetstoreClient; - productReference = EA07F4B916134F27006A2112 /* PetstoreClient */; - productType = "com.apple.product-type.tool"; + productReference = EA6699961811D2FA00A70D03 /* PetstoreClient.app */; + productType = "com.apple.product-type.application"; }; - EA07F4F11613521A006A2112 /* PetstoreClientTests */ = { + EA6699B91811D2FB00A70D03 /* PetstoreClientTests */ = { isa = PBXNativeTarget; - buildConfigurationList = EA07F5051613521A006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */; + buildConfigurationList = EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */; buildPhases = ( - EA07F4ED1613521A006A2112 /* Sources */, - EA07F4EE1613521A006A2112 /* Frameworks */, - EA07F4EF1613521A006A2112 /* Resources */, - EA07F4F01613521A006A2112 /* ShellScript */, + EA6699B61811D2FB00A70D03 /* Sources */, + EA6699B71811D2FB00A70D03 /* Frameworks */, + EA6699B81811D2FB00A70D03 /* Resources */, ); buildRules = ( ); dependencies = ( - EA07F52F161357A5006A2112 /* PBXTargetDependency */, + EA6699C01811D2FB00A70D03 /* PBXTargetDependency */, ); name = PetstoreClientTests; productName = PetstoreClientTests; - productReference = EA07F4F21613521A006A2112 /* PetstoreClientTests.octest */; - productType = "com.apple.product-type.bundle"; + productReference = EA6699BA1811D2FB00A70D03 /* PetstoreClientTests.xctest */; + productType = "com.apple.product-type.bundle.unit-test"; }; /* End PBXNativeTarget section */ /* Begin PBXProject section */ - EA07F4B016134F27006A2112 /* Project object */ = { + EA66998E1811D2FA00A70D03 /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 0450; - ORGANIZATIONNAME = "Tony Tam"; + LastUpgradeCheck = 0500; + ORGANIZATIONNAME = Reverb; + TargetAttributes = { + EA6699B91811D2FB00A70D03 = { + TestTargetID = EA6699951811D2FA00A70D03; + }; + }; }; - buildConfigurationList = EA07F4B316134F27006A2112 /* Build configuration list for PBXProject "PetstoreClient" */; + buildConfigurationList = EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "PetstoreClient" */; compatibilityVersion = "Xcode 3.2"; developmentRegion = English; hasScannedForEncodings = 0; knownRegions = ( en, + Base, ); - mainGroup = EA07F4AE16134F27006A2112; - productRefGroup = EA07F4BA16134F27006A2112 /* Products */; + mainGroup = EA66998D1811D2FA00A70D03; + productRefGroup = EA6699971811D2FA00A70D03 /* Products */; projectDirPath = ""; projectRoot = ""; targets = ( - EA07F4B816134F27006A2112 /* PetstoreClient */, - EA07F4F11613521A006A2112 /* PetstoreClientTests */, + EA6699951811D2FA00A70D03 /* PetstoreClient */, + EA6699B91811D2FB00A70D03 /* PetstoreClientTests */, ); }; /* End PBXProject section */ /* Begin PBXResourcesBuildPhase section */ - EA07F4EF1613521A006A2112 /* Resources */ = { + EA6699941811D2FA00A70D03 /* Resources */ = { isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( + EA6699B01811D2FA00A70D03 /* Main_iPad.storyboard in Resources */, + EA6699B51811D2FA00A70D03 /* Images.xcassets in Resources */, + EA6699AD1811D2FA00A70D03 /* Main_iPhone.storyboard in Resources */, + EA6699A41811D2FA00A70D03 /* InfoPlist.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + EA6699B81811D2FB00A70D03 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + EA6699C61811D2FB00A70D03 /* InfoPlist.strings in Resources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - EA07F4F01613521A006A2112 /* ShellScript */ = { + 04DAA264FD78471BBAD25173 /* Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); + name = "Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; shellPath = /bin/sh; - shellScript = "# Run the unit tests in this test bundle.\n\"${SYSTEM_DEVELOPER_DIR}/Tools/RunUnitTests\"\n"; + shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n"; + showEnvVarsInLog = 0; + }; + 3692D11BB04F489DAA7C0B6A /* Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Copy Pods Resources"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/../Pods/Pods-resources.sh\"\n"; + showEnvVarsInLog = 0; }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ - EA07F4B516134F27006A2112 /* Sources */ = { + EA6699921811D2FA00A70D03 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - EA07F4C116134F27006A2112 /* main.m in Sources */, - EA4F4D3816F1A90A00F24B35 /* NIKFile.m in Sources */, + EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */, + EAEA85ED1811D3AE00F06E69 /* SWGTag.m in Sources */, + EA6699B31811D2FA00A70D03 /* ViewController.m in Sources */, + EA6699AA1811D2FA00A70D03 /* AppDelegate.m in Sources */, + EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */, + EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */, + EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */, + EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */, + EA6699A61811D2FA00A70D03 /* main.m in Sources */, + EAEA85EA1811D3AE00F06E69 /* SWGPet.m in Sources */, + EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */, + EAEA85EC1811D3AE00F06E69 /* SWGStoreApi.m in Sources */, + EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */, + EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */, + EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; - EA07F4ED1613521A006A2112 /* Sources */ = { + EA6699B61811D2FB00A70D03 /* Sources */ = { isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - EAE9043A17BF31C800486EFE /* PetApiTest.m in Sources */, - EAE9043B17BF31C800486EFE /* PetApiTest.h in Sources */, - EAE9043C17BF31C800486EFE /* UserApiTest.h in Sources */, - EAE9043D17BF31C800486EFE /* UserApiTest.m in Sources */, - EAE9043817BF318800486EFE /* NIKFile.h in Sources */, - EAE9043917BF318800486EFE /* NIKFile.m in Sources */, - EAE9042217BF2F7900486EFE /* NIKApiInvoker.h in Sources */, - EAE9042317BF2F7900486EFE /* NIKApiInvoker.m in Sources */, - EAE9042417BF2F7900486EFE /* NIKDate.h in Sources */, - EAE9042517BF2F7900486EFE /* NIKDate.m in Sources */, - EAE9042617BF2F7900486EFE /* NIKSwaggerObject.h in Sources */, - EAE9042717BF2F7900486EFE /* NIKSwaggerObject.m in Sources */, - EAE9042817BF2F7900486EFE /* RVBCategory.h in Sources */, - EAE9042917BF2F7900486EFE /* RVBCategory.m in Sources */, - EAE9042A17BF2F7900486EFE /* RVBOrder.h in Sources */, - EAE9042B17BF2F7900486EFE /* RVBOrder.m in Sources */, - EAE9042C17BF2F7900486EFE /* RVBPet.h in Sources */, - EAE9042D17BF2F7900486EFE /* RVBPet.m in Sources */, - EAE9042E17BF2F7900486EFE /* RVBPetApi.h in Sources */, - EAE9042F17BF2F7900486EFE /* RVBPetApi.m in Sources */, - EAE9043017BF2F7900486EFE /* RVBStoreApi.h in Sources */, - EAE9043117BF2F7900486EFE /* RVBStoreApi.m in Sources */, - EAE9043217BF2F7900486EFE /* RVBTag.h in Sources */, - EAE9043317BF2F7900486EFE /* RVBTag.m in Sources */, - EAE9043417BF2F7900486EFE /* RVBUser.h in Sources */, - EAE9043517BF2F7900486EFE /* RVBUser.m in Sources */, - EAE9043617BF2F7900486EFE /* RVBUserApi.h in Sources */, - EAE9043717BF2F7900486EFE /* RVBUserApi.m in Sources */, + EA6699C81811D2FB00A70D03 /* PetstoreClientTests.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXSourcesBuildPhase section */ /* Begin PBXTargetDependency section */ - EA07F52F161357A5006A2112 /* PBXTargetDependency */ = { + EA6699C01811D2FB00A70D03 /* PBXTargetDependency */ = { isa = PBXTargetDependency; - target = EA07F4B816134F27006A2112 /* PetstoreClient */; - targetProxy = EA07F52E161357A5006A2112 /* PBXContainerItemProxy */; + target = EA6699951811D2FA00A70D03 /* PetstoreClient */; + targetProxy = EA6699BF1811D2FB00A70D03 /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ +/* Begin PBXVariantGroup section */ + EA6699A21811D2FA00A70D03 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + EA6699A31811D2FA00A70D03 /* en */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; + EA6699AB1811D2FA00A70D03 /* Main_iPhone.storyboard */ = { + isa = PBXVariantGroup; + children = ( + EA6699AC1811D2FA00A70D03 /* Base */, + ); + name = Main_iPhone.storyboard; + sourceTree = ""; + }; + EA6699AE1811D2FA00A70D03 /* Main_iPad.storyboard */ = { + isa = PBXVariantGroup; + children = ( + EA6699AF1811D2FA00A70D03 /* Base */, + ); + name = Main_iPad.storyboard; + sourceTree = ""; + }; + EA6699C41811D2FB00A70D03 /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + EA6699C51811D2FB00A70D03 /* en */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + /* Begin XCBuildConfiguration section */ - EA07F4C616134F27006A2112 /* Debug */ = { + EA6699C91811D2FB00A70D03 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; - FRAMEWORK_SEARCH_PATHS = "\"$(SDKROOT)/Developer/Library/Frameworks $(DEVELOPER_LIBRARY_DIR)/Frameworks\""; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; GCC_OPTIMIZATION_LEVEL = 0; GCC_PREPROCESSOR_DEFINITIONS = ( "DEBUG=1", @@ -394,122 +467,153 @@ ); GCC_SYMBOLS_PRIVATE_EXTERN = NO; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.8; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; ONLY_ACTIVE_ARCH = YES; - SDKROOT = macosx; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; }; name = Debug; }; - EA07F4C716134F27006A2112 /* Release */ = { + EA6699CA1811D2FB00A70D03 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { ALWAYS_SEARCH_USER_PATHS = NO; - ARCHS = "$(ARCHS_STANDARD_64_BIT)"; + ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)"; CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = YES; - DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; - FRAMEWORK_SEARCH_PATHS = "\"$(SDKROOT)/Developer/Library/Frameworks $(DEVELOPER_LIBRARY_DIR)/Frameworks\""; + ENABLE_NS_ASSERTIONS = NO; GCC_C_LANGUAGE_STANDARD = gnu99; - GCC_ENABLE_OBJC_EXCEPTIONS = YES; GCC_WARN_64_TO_32_BIT_CONVERSION = YES; - GCC_WARN_ABOUT_RETURN_TYPE = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; GCC_WARN_UNINITIALIZED_AUTOS = YES; + GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; - MACOSX_DEPLOYMENT_TARGET = 10.8; - SDKROOT = macosx; + IPHONEOS_DEPLOYMENT_TARGET = 7.0; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; }; name = Release; }; - EA07F4C916134F27006A2112 /* Debug */ = { + EA6699CC1811D2FB00A70D03 /* Debug */ = { isa = XCBuildConfiguration; + baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */; buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch"; + INFOPLIST_FILE = "PetstoreClient/PetstoreClient-Info.plist"; PRODUCT_NAME = "$(TARGET_NAME)"; + WRAPPER_EXTENSION = app; }; name = Debug; }; - EA07F4CA16134F27006A2112 /* Release */ = { + EA6699CD1811D2FB00A70D03 /* Release */ = { isa = XCBuildConfiguration; + baseConfigurationReference = EA5799F266AC4D21AD004BC4 /* Pods.xcconfig */; buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME = LaunchImage; GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch"; + INFOPLIST_FILE = "PetstoreClient/PetstoreClient-Info.plist"; PRODUCT_NAME = "$(TARGET_NAME)"; + WRAPPER_EXTENSION = app; }; name = Release; }; - EA07F5061613521A006A2112 /* Debug */ = { + EA6699CF1811D2FB00A70D03 /* Debug */ = { isa = XCBuildConfiguration; buildSettings = { - COMBINE_HIDPI_IMAGES = YES; + ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)"; + BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/PetstoreClient.app/PetstoreClient"; FRAMEWORK_SEARCH_PATHS = ( - "$(DEVELOPER_LIBRARY_DIR)/Frameworks", - "$(DEVELOPER_LIBRARY_DIR)/Frameworks", "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + "$(DEVELOPER_FRAMEWORKS_DIR)", ); GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "../tests/PetstoreClientTests-Prefix.pch"; - INFOPLIST_FILE = "../tests/PetstoreClientTests-Info.plist"; + GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch"; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + INFOPLIST_FILE = "PetstoreClientTests/PetstoreClientTests-Info.plist"; PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = octest; + TEST_HOST = "$(BUNDLE_LOADER)"; + WRAPPER_EXTENSION = xctest; }; name = Debug; }; - EA07F5071613521A006A2112 /* Release */ = { + EA6699D01811D2FB00A70D03 /* Release */ = { isa = XCBuildConfiguration; buildSettings = { - COMBINE_HIDPI_IMAGES = YES; + ARCHS = "$(ARCHS_STANDARD_INCLUDING_64_BIT)"; + BUNDLE_LOADER = "$(BUILT_PRODUCTS_DIR)/PetstoreClient.app/PetstoreClient"; FRAMEWORK_SEARCH_PATHS = ( - "$(DEVELOPER_LIBRARY_DIR)/Frameworks", - "$(DEVELOPER_LIBRARY_DIR)/Frameworks", "$(SDKROOT)/Developer/Library/Frameworks", + "$(inherited)", + "$(DEVELOPER_FRAMEWORKS_DIR)", ); GCC_PRECOMPILE_PREFIX_HEADER = YES; - GCC_PREFIX_HEADER = "../tests/PetstoreClientTests-Prefix.pch"; - INFOPLIST_FILE = "../tests/PetstoreClientTests-Info.plist"; + GCC_PREFIX_HEADER = "PetstoreClient/PetstoreClient-Prefix.pch"; + INFOPLIST_FILE = "PetstoreClientTests/PetstoreClientTests-Info.plist"; PRODUCT_NAME = "$(TARGET_NAME)"; - WRAPPER_EXTENSION = octest; + TEST_HOST = "$(BUNDLE_LOADER)"; + WRAPPER_EXTENSION = xctest; }; name = Release; }; /* End XCBuildConfiguration section */ /* Begin XCConfigurationList section */ - EA07F4B316134F27006A2112 /* Build configuration list for PBXProject "PetstoreClient" */ = { + EA6699911811D2FA00A70D03 /* Build configuration list for PBXProject "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - EA07F4C616134F27006A2112 /* Debug */, - EA07F4C716134F27006A2112 /* Release */, + EA6699C91811D2FB00A70D03 /* Debug */, + EA6699CA1811D2FB00A70D03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - EA07F4C816134F27006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { + EA6699CB1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClient" */ = { isa = XCConfigurationList; buildConfigurations = ( - EA07F4C916134F27006A2112 /* Debug */, - EA07F4CA16134F27006A2112 /* Release */, + EA6699CC1811D2FB00A70D03 /* Debug */, + EA6699CD1811D2FB00A70D03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; - EA07F5051613521A006A2112 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */ = { + EA6699CE1811D2FB00A70D03 /* Build configuration list for PBXNativeTarget "PetstoreClientTests" */ = { isa = XCConfigurationList; buildConfigurations = ( - EA07F5061613521A006A2112 /* Debug */, - EA07F5071613521A006A2112 /* Release */, + EA6699CF1811D2FB00A70D03 /* Debug */, + EA6699D01811D2FB00A70D03 /* Release */, ); defaultConfigurationIsVisible = 0; defaultConfigurationName = Release; }; /* End XCConfigurationList section */ }; - rootObject = EA07F4B016134F27006A2112 /* Project object */; + rootObject = EA66998E1811D2FA00A70D03 /* Project object */; } diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace/xcshareddata/PetstoreClient.xccheckout b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace/xcshareddata/PetstoreClient.xccheckout new file mode 100644 index 00000000000..bbe327e168b --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace/xcshareddata/PetstoreClient.xccheckout @@ -0,0 +1,41 @@ + + + + + IDESourceControlProjectFavoriteDictionaryKey + + IDESourceControlProjectIdentifier + 7A33CEA3-5D3F-4B6D-8F47-84701AB3E283 + IDESourceControlProjectName + PetstoreClient + IDESourceControlProjectOriginsDictionary + + 92840518-904D-4771-AA3D-9AF52CA48B71 + ssh://github.com/wordnik/swagger-codegen.git + + IDESourceControlProjectPath + samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace + IDESourceControlProjectRelativeInstallPathDictionary + + 92840518-904D-4771-AA3D-9AF52CA48B71 + ../../../../../../.. + + IDESourceControlProjectURL + ssh://github.com/wordnik/swagger-codegen.git + IDESourceControlProjectVersion + 110 + IDESourceControlProjectWCCIdentifier + 92840518-904D-4771-AA3D-9AF52CA48B71 + IDESourceControlProjectWCConfigurations + + + IDESourceControlRepositoryExtensionIdentifierKey + public.vcs.git + IDESourceControlWCCIdentifierKey + 92840518-904D-4771-AA3D-9AF52CA48B71 + IDESourceControlWCCName + swagger-codegen + + + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate index eb26dbf4ea27f0836a132d0e1e63daac57e4b965..53cb85903b2a9f27e8040ecbdc00b27c053dc8f2 100644 GIT binary patch literal 8581 zcmcgRd3+Pq*5}?PP1`idWG0zp8jwN@6zm2qOL1#UTdhDTbg>kqr0viK+N5M@sR*7Y zB5sHxB8Vbw0YOnjL~&&ic!AX+es?lW+9>aR{=PrH=GSCq?%D3S zXP?@ZCYR5jnRyrpP>2EzXd#+@L(f(vx5{3h%j2#}_SDXj>-@ec$xd%wql-N*PxgCS zcp$f~-NL;OI*0)QEMSEpFcdC@R7it#$bd{32E*YRD28ic9E^tvPy!R76ehuBC<7PF zg4xgn&EN(Pw7?wj!VPdM+ynQ*{jdrigbr8->)~yI~)^4u6Ap;SijF z58)#?2_M4`@FQG+pWtWs7yJVMhF?h>(UW*$AVy*#R+2ylkR*~!29iN!2pL9(lPofl zV@y$plhDCX!MziBytmGK18U2GU4eq?x#hhXh~|X(#i^0&)krliWp?kh{r) zWHot+JWSS*M@T2xNH&ot$+P4+vV-g*yI~>OLk^JF$Q$Gkd5@eV{~)Kx7vxLw6*)(K zB)?IhF*KH%DNhAzp~-Y09YhDy6gq?srI~aX9YsgeT$)Go={2;3meVRaoz~MP+DzTF zmA28j6zN~+&2%AMOdqCe=p%G3?Vz2si>{;V=?1!)K0&w9opcx7OJAc0>AUn0eV=|n zPtXtPNAwf=DLqZUtVnhTnwkzlEX08x;=u&`btPr#v*mVQHT&&8^2+48Ca2HW2?j7C z#i&l;z>FGv87peIGHX1n;0{DSP&*+e#DYAZ(h!@(W!}9*;(^b6Xy-f&df|r%o#Ck z{`}A(WWg1XvI(+b1dN1HFdA}T3|t16qX{`QBaZ@F(2643Ho=ul{kf0_`7oAU6+#i( znfeoOIX;L_v8xxc1*@krX_y@2owagP4ac#&vPMr^iL=$!;PiXE*RuzO^)7am=aro` zT$&<$$U-7iT;X>$x%}-4SQ!gc{z{kJrV~l4^FG4{PNu}?SeTw-o zv?5oNT1zaWh*5?FR?YqZdbsk3a0pnJlC(T*jv1=W~aCP z4@)>40SDrUqc9I{WDMrR0=S7WX@#3%A>0Css#un4s`tw7$`&X4_D`)-=(_#o?JZ1! ziS^wvC@+}JoXmeBw>Z_~RZcdzUB+oRW^)7wac~3{!)=V;?QjR&33tH~xEq!-YYfG- z@t(RM&h#F)R&9wvG&^1Hp2vzWyX)n-6K95Sd)6==Q*am##e~+#hGncy|D1NEaE8={NQ75Nu%LJ_;LQ6SPeY9aF{R@l*V+W|=u-a|>o*CPEFjU?%g_F&P<6 zOy^CF9-lv>!pAH&!|!poXVlBB8Hz_LMN5XS&Dp?gHBHeZv$YH#qtYb%GU|fvo6*wk z%^57?)n!EL<#)F|uAZT8vV98aKlt_Pq$Rm_27BtDlsl|AJyCbD1YGJ5dba71&wB4Q4`x4J#s$ zMtW{1>{4XOuQ;j$Uc=E?UBeAjLq~Vy z{!bAtMBoj0OCj(k=5)Z@I0mcBCorcCtsaK=fbU{4;3yo!%kXl%q6?0*u>C$>$wKuU zr5+j*!HxxHzg)&rp1UDR&H-Q#w$*us3u8VM^mFz&){?T0=|T=FcMmJVZQxaZ*)9+M5<5X3qptLN{{U>W=2_PaGl?2NzDdYneS#yNe3g@ygtn?H; z;b>}Tjk$RZXRGrxr#oAigR0J!-tESr4gW?oz^@}f2%#hji}6|WS81J&}45&{D75>hc79Ww}yNO>j22 zUH*Vlv-a;%Pz1vsw4_`)7nHxCN0Y%MWm-vD*tXj{$zWI;l4K}Ji;yIpWZ-pJg%zbq zxwoeDqLNKUOfM;$5b!I>IG7l^NVbw1R3@XyXckPv06pBg$S8#$D=q%0PgO;iF`prq zx5Ip>`Km$ZLK`R|#gNiTt|r&u z40LvqYsomQ#X796RPCu!J;00dzgUhXlSx?(*Ehl-es3{dq?}YJd;0HS7tbys!LK7# zkg|3yR`;q|$W$^-saZ%3&c=pdi7`u6l2cJqEjD%+3`B;N==wvIaPc&)Cgk63wuT!O z++%vgPRjxZQ7)8}vF=k>S>d+(d4HlywBj zU&zg5A^I_Zt=P7XEF!m(#pE`ei#OqIcso{CjhAP3w;xuPz{1`UE}g5@G^5nkQzp9_ z8iT;0^H@rjD{Sr|_mXAgK5WMua30>cjy1GJdIgKWUR{I^K-m=cK|C!6tRT+|bZwveYI{C^vH1{dNjSP@ocQtmtq z#(|Kco+mFwpu9|8!CP@LR`lqU;j~2Hyh`>da_+@DI#@f(+D{fSStsH1G|4Qz`DL$i zCLsm~$?K|TgdV&}-VVpxcW?<-tExDx?C1zNig)9^Jv%y1K8O(S1o;q`;yp|}W)rGi zC*`_kM2PoK@@WLlY4RB^!~2vRWnx&po2I1PX}cnD&ya7zM{pMJ4+;03BHVfMJ+8o& zJ;Gfe|B7IgPX5ip?E_eml)G?cZ?cq7mPUJ}h;$mwAXh1np2P^qIBH-Kkm_kXuEvKt zsgauSVO$f`aVY17TXEJ~scz4{1}ah;wNr^EPzOGO zYq0}6u?yF2pnd5jv>znV{;X+UkB{SK=0#5`?Xo&@DxBNGI%By$m@k!nQ)%(L=OvR_ zwWVr5vZs?%t_-M#9RHx7LDU?E>!)Z3N2%3c(JLm}9#0FoHJxd5K zhhDB6+!&Uz9>Y3zLC3I*$FRCIA|ehSk;5WlR#rG7(y_EKEK3nSffXT&#dKVlvqGyn zv@nrQ3S&&hEj<_&v@*ii=oC6NWX^ONZtXT_T0^8RI)gfCEk2FgaYxvssZ1Mt8!C0t zS-1_KQ52+1mBQzsOdOJOTXG|8*F(J#$Uf@FXYn~!2r*RESyj9{F#@lh-WY*5pDw`X z@r4l6@XRQJX${x>|Js5EqZGYGX$kCX1{!J!=xuZv8$Qw7=^gY=dKXLwiRosjFaQ`M4M3+MmT|pn9E9okhi;`Fd`YQ{d@8D59j(=yqqXwnELpQ6umX;zm((x6$C%D|MFk{9l;=Vg2 zgsk>ax=AtTjd-AgK8CL;VdMW?w5U^b`Xqgdkz`$#yMu1UgFPPd41Hcn|9@;-=!^8F zVB7LK{*ARQOosnd$VU-(u0= zZKZy_D4!74VR}pn9Y^R0RO()Z|bJd8&aEHm?*0@fI@9;$oT#ahRbJ662oBATrG_rH=DyY2Urp3@s7!0N7m$0r)9qGAs6fVGJ^9zW@Q@h@`i4uk->gD;W0&xKZhu>Aw2eX)5}_;hB?V#p>8aN>=)a zG?%-saY(rJ^W_UcSxFE%b^qxUgz6}douWw};hnQb6@ z8I(%XX%-#9UI^u|@YqIgq4zUiT}4;3*FKN1S3X_rbDjs@RIy>e!ap_Ski?n_>^go{9Y?_S@L+V!x05HIBqZ#cAV=aiim|h--*ziCYo3 zI&OE|n{n^N9f~^|_g>uJ^;B=t^LmTkrkC^%eWE^1pRFIMAFUsw&(n|97wWIp7wZH1 zCHnRHC-qzP+w|M@d-U(<59yESkLi!=-`Ahef299fe^!4^e_sEC{(}Bz{V)1om5_-*ko#lI52D}GP>-uO4--->@H{!sjp_+tiY7-pDZxZSYAu*$I7 zu*R^~&}n$qu+y;Du-|aNaL{nf@PXk&!%4#@hSP@64PP35GR7M-jXB1A<3wY*(P^A% zY&6a?dW>_7K4ZYxYP`vKoACkT8snqJmyLUk$Bn0qpBPUYKR5nt(wL%6F{U_Eyvb@B zU>a;1V!G6nX&P?IHjOl0VJa|9F*TaznC>;LH0?0GX?oxEf$4PHrD}kb9du&V9gr z$erYVG;7QTv&n2W3udeN5_6(?fH~Pb$edyxW-d0Do2Q#+oBifi^IY={<{Qn6%!|#p zo9{F)F)uYgVLoU+!$79=F+&_KW{ac59Pu*o8gZOBK`a#~i{+wItQG4- zS@enlu}!=|yir^rE*9?=?-7@Y%f%I9m$*@UOx!GP6}O4o#plF>;vw;*_=$L0{9OE6 zJS(0P&)cX?Z?oI_+WOi0+XmTEY(s6SwySK{*ml@<+xFV_+YZ={*gms;Vf)JVwe76! zob9~r2ipbP&vt{|WH;LdyVY*9OLm97uf3nWzkRg5!tSx(YQN9E-oDHJcl)>YUnL?% zNzqb_6ekr(lcaK~Qko)7m9Cd&Nj@ncwMp&LJn0tcR_QkB4(TrGZmCP!ENzjtO53Ep z(thcHbWr-6bVNEOot8eAzLd^N=cMz}4+;7NdqUrYehK{(1|_5<3{6N)$W5qnXdQ75 znn2V4}#_xR52?v>p`j$TB1mxF5@93XNu8w!G;)Z>6ti3m!u8+SClX^QD4iW)VE z(U?S2G@9OvEk;d@rdU#q(P&KjzrE!SPBB0Iet${+|Ic3(?{;V2ym{}O1Ot>Ido! z^)q#z`h)rtQAmb3F(`c$9z=(O{H@(vcZupiGpFhN1#gh>Fl?REnxl zHL5|is18j;lh9-|1x-ioXeL^K1Vqq6v<<#hB207PprmXI0y&hWSoMvScmo4fQ>j6 zoA7Wv0*}O_a1kDj$KYaIipy{to`$F6cHDtGaTlI}XX06SHlBm$;stmSz8>F#Z^d`u zrT78-AYO%60pT*DN5AcV0C*Fm3<2`sU{s`~GALIS_6MPtdfsf&D@K5+O zK7)V8XYqObJFTQSnx|E?2kk@q(t&gk9Y#md8akOyp|!M*&ZG0`0=keMMh~Y)&?D(l z^jLa4J%OG~H`72>s@^kekn^m_UUdIPue1fGOL)i%;U^P=1Jxm<~e2?^CI&y^Ct5a^ER`G z*~@&y>|;J=_A{R{N0_6`G3E^OGjo}A)w2fH$fmMpb_6?;9mN*0quDWRF7iDQqh{o$X=?yO3SPUc+9? z-pnpx?`7{}?`ON&mFyPwS@t>hdG-Z%E4z(-k=@SjU|(h5WZz{!WcRQiv-{ak+0WT8 z*e}`d*&o=G?2qgz_Gk7y`>V_*v&$yRu98iWwaKQ*I%Qq5*|IsZt7Qvhi)7cxZjjw5 zyH$3Z><-zTvU_Cr${v(0ldX_-%N~)fkv%4RT((j6r0f~lX4&(y7i8OIJ7llQUX#5g zdt3It>;u_u*&f-)vi-78Wrt*+%f65ulO30REBj9NqwJLIXW3cVud?6dlpM)fxlGQ< zdAX-tE%%lC$%Ev<@=$r0JW3udkC!LNHS%P+UT%=5$QZ{7(79^5yas^7Zm3$Wjbfj8KeJR4B$PCMcQ|cEv{ooH zII1|NIIcLYIHUMkaaM6o@r&ZT;#Z|ysZc7FeoB93fHF`St&CB|D&v#}rBRuxv?z0x zdCFpCiE^y6R9UCAD(jUtWrMO&*`%DNoUUwFUaef96qH1HtMWGGV&wzM2bIf|4=Ep2 zKBjzJxnB8%a)WZC@=4`3<%`Pg%6F9SD&JG?R~}FvR31|vSDsLwQU1(fj^-GS<-9m= z&W8)*!np`e!zFVmoR%|j8C)i3;c~e`u814Wjp53;ncQ4%9w%^wyOz6-yNSD*Tg)xt z?&6km_i^`g4{;B3E4fwNT5cV;o_m7Z#687r;hyETa@)9b9n)-$_WZWSuBrCcPG`&hR2UV%mI|N(sURwt8c2mugQ!q} z6=Z^3PzXwa6L>+jmI|jLs7NXb5DB7UsVKoi7$B&Hp@5WJ7zqED*NLq(w>GuSENr(; zwOiE@@SwQ8$=+^na)ub8oQ*(_bqd}(y5(K$g9no3{1np>Sx7%Asw>1F*NqvD!sP#5p-r799%RZtB zNYOm8+1_qdhe2^mV<)&c{iEBrv2kr}Ee*Ez5girH9nB3b&{&`g5$Hy)+bjRMbG1p~ zI{o~l@VPpp5k9AzO!MdOa&X>2rLLfYfQX*Es5B~_GE*5<64P6OiW8)d_70E@OMAO* zb~hBroG_-W*x{8qnK*z5qt$d!Cwdv0)?P; z)No+mNNN;SM2!Y^7E>icFfcGgctGeTXs|GpAd^relvhK4peIGP278NDt%h%9liOyF zvCU|nWb15euZ0H%P0jGh(r&j|)f%z;P8oA!WO-+EOLOOJu~-?no1GQS_L&ku7cdEg z8@t><YJW>d2e`Mk)=ml2jw0Lawyw^a z5__j*TJt!2M`!X>rIUnp)MSx_R;r$|Q4Lfh)kN8;iPR)vkPs?_3E@J75Gh0n(L&5R zAmCN-uLOQtsWxgFH5~{T3;&AXXM%8zaIJ8gP!4?*(aX0tbWNIM?;(@Fi);=NEd%75 zZ0$`VHO0abo>kI+k`Vh=NRGJltgNeHszbJYphmuZqOGf?)6s%N!tkC)C1Rb9PLSCya69x-Of@USP1gLq3kPH;8 z5LH`(TXR6CPJ0>1Uh5>s$NXj(r){mac3`_z?dM+B-U9O#d((x_huPbv+B@54OT+G7 zaoF7_qzIl)q#mSJQSoc2Wz<8|!_;zW1=UTh6tsd)&K=ZHh=X#lIOa|^&=l?r0e(oM0N#w~ zv`-!5(40X|CEd@vfzEdYvw*+i6s=c>RXg96mllDxn%33O(%jf%N2`jFa5 z?V@&5d#Dl^k51%^+8Q0hp{|#7lE#1%Q$bF9AB#G_waGrKc%rjz?>k|%kS~-7c>>Tn zWkMqi%VZdoZY-0)CA$=3S!a7!V`o>pT@u2NsnnI!e(C^qP$&?F3nN7va0u{TM;)%} z(@vo<%uQ!WJ^zCG(y9)D7JFq2z{3b}AY5W=ZttePqB8%7GE#%bsKdetVOY7S6Fa0w z-@v0$!mv6}mK~tw?RhQDpheU`%aefNkJKsZC+c){Q;#B^}7h}vddf5!8y%he?;%gA%5Y#$XnI1E(sdd+?gzC4`&aO z%N)Zt56H3`A&N(sI*l0Wl;|)v*gEXh@PE6#1%S@53zRTU7~|*=k|Ra=m@?o^H&RlW z(nskHk5oX3F=eB>Iz^?_JAPIoUK~LV`9uRiNg_{SyxewLW9sKG_3-CSAvXGEaFrX@GFJ+e=6Fwsx@8;GQ;5gW&`k(BG|y1G;E9B+6$|smldV zHF9E|gL1*1B8xD21vqTro`K=$p$=FbP_iPuoP~#>5n|!t!c{BKNMVYjFpLKmokT+e zqa5ZPXbc+Ljfzo;&>~D1oO1$HhAJrUZZr;+3sZ&GZZsZE5ZZ)kf~6L~^eQG%qgIR) zJ2%=kskOPYtI1yL)~To*vV#);I5D%L1~7{E~C3Hsg256w8X8a*P!d&VBUak6s{H)2$o*ijLH!XyVbc3EfG7iSRj|d zlhdUR&@Xvj^?fosbz7xXP?z6y$PHq zxiA;K67B(|xmdXWBlISE3mSMEy@TF`MqWW5Kt%XM>iY>0_-<)xx3^YIv%&Aq>P8W6 zYo|C~VXQli;H4}@bsPApJvtv+x<|NASklKuLAzj>?-pGY;cnq}$)k`)r|2J`{pbKX zDBL03Dcse^KLDq5n49f(d_iA=)n0m$)poPll67|LEBY3C`vFAEPgCCu_X3Ld3E(w} z`r${>0=x#qk!Gjp4EousjsqUKTpG8DnmaSP(OJ<#UT$$|xc`FATh&pQ(Ly)+RfK*y zMV-R_JNi=;c2O~6N_bExcXSfdAlR6}tguX2?hzpgSShR$Rtt{^YlOAJI^of^ zI0nb!I2?}?a3UUzlZ3~FXM|nCZsBX;jBuVHUvZoca`PBmlj-EL*;5A6Q<3M{DZDbw1TTRXwHgDY`ja3;>eLvXh6xUgP$Lf9Z|6rL0|t$}%ZEY5|0`C#3nz^)Gzo`Qc* zgN=unl_WkA!CWK|O|eV7i(6Y}OQE5DN)3m&kqu^cP(lol6wI0i(|LQ7!@f%KuYM}! zi2*%(hXgnnsyWL{6~h)_%3CEjzJCBtH^aeWAarye06n1@5r0wf!9)hUZLu9m%uCQ% z5bu(n!GOnM8x{XJF2@ykJf46naTTt{HMkbnVJof|HVa#XXNBj4=YR&ls^~z8KLdsLg%2fHMU3pYq|QZWaHm@! zAZh7@SxZ9~%-Eg%_Uc=_$DvB-`^*JGl;Vr)i-E_Bn{#+r#nXDiAmYTyRi?}?a?ugC zoGHezU=Z|u?be(Wl@T3MSM|~2fGX>pEqbb=I&!^mRV-^1Bc3H~9nE6%l0WMzHDXe$ zIKKivUecAW7roVcxL(>e(=oXdC(t6}FD{t}&Df@O*qes6w{=Z}Vq)yqRZJw8!^gz) zC?3zpS3@9CBD(O3@Y*hTCSZaWR>E|m!!eZf zspt*(Mwm6bieAW`mG~xnv#7W)T?8yUL_04Ki%JJ)#0d6o2llt&#rSG`J52svB|C&S zh1Z0)oc*{J$M~JeH1^2vhm~KQe;Df-#IIV4mbiNd2L;-ozPT~y>(LOWZ?q| z&=YtAlyxw@%--3JH&U5>zVE`1!d(1&yh+$86@MB(BSw^*(>iCpm3TAWBGUZgSAC%U z4_ezvzUT3)5Gchj;H`KYei3iSJMc^RW&Db;N7yTTB!>LFI(`Gc z3F`N4{0@A3546Ll!Xe=>Xon-harkyZRKjBHyr8|ktzDYSKn$axRh+ani6Pyda8fA* z^`Harz$N2iybVNLeCATUj_{IL%`x0_XG<=cW184Ah@?>^P6;mnCl-Zg;)((^1`gYW z*nnL2ZQeD+dS}M^G<{Ndn$a2D#|QAi<-%tYZ$8C`fY&_}ZeZq0{3-s-F)N2Jl7>Fg zQye@m{3RN@0)HiZF7&)RE`C2De9`Nme2aeouLFOFzZbp~zUsy&@sGk$;h114ZEh;< z1e@do@r6FI8%J?EnFbA6in)$!TM-#=&?Cdl|tnxYYng>Qs!h3|y#SJ4a=MayWp z@B?t|l<IX`f&;J%Cojc%?ms zlPhR1;Ya5zL7InK+=}|q{?haY6yJqhF{Qi06?8Bi;sQBHI4xLuI!}kw5pMG%I+~8B z;#bl!bSxbw{4AUm&aI>qMB69);;?i*(hE`P#wmGiQ^jDr7?X7%Cz%mZ5Je+A0;UY` zwiBe=F)e8YarVv69X4(<(5tDqeQcM#%Pv|MHFjd7r!&C6p$)W=PNhwB8l6s?gnw^0-cL|F+of(b4%%Q;QrHP1hFgVa)M+)8uuaMBzz@ZPsKk%S5e348oHLQqpbwVg%JcP z2vQQn5yZn=$4?Xdo(ON9e^rhT1BCLD2_@}qO%U$wsOsxksE66XErV5orf?~wdI=O- z>FHE_HvpgJ0O%optdbfLhn~8)bF#fXyce<)^_lb>vED4PuqTwiuwGf$v}q8E0x1j! zs=DH0v_LO(k!=w{UcF?yj=rInY$6J-=mC8TeVeP&VuE~nE8Rig={}I|rXPlx4}A}P zFMS_w5vNjvD>wGttU8nf?_0 zjEfJO2@31w!*lfW5+59DpWa5lxSXH}hee`y&@VwuSoACCm)#5z{VM(9O8PbWb@~m0 zq6ms6Cs}l=&uRV5Tqr@;Ih^9cl61=5d!*0 z`V>LQ1f_`9Oq@Hq6I0wZk zrIO^@C&Pkt8zheSN?9YNU9Aw{2hHkO+^LZsmN^EBRjn=m>RmpU-si&P zugOsXG9_SM3lP*F;=$adJn;n7|oi^o)TqGN}aR6I4J@Awk1dF=W zc9O-}Lkm*?4jz-s_S8RJMw#XKYLZ(?}3-x`v>s z1XhPYy5rqswnz4)tcoJYxJm91Q=DcvQk(|&Q`9Owb6A{`$uR1B7AhcFt)J3PPrxa& z&X@tHg8qt^wA(=;b#;uhwNJA5v9_C)= zKIVQ0TsuMFj87t{nV_o(f}XaBeUw7shKtB9xq1#~EU>_$O)E4O6zEJkL#ke9(P~W= zy-ufx@PzcLPMdMKK5z!znN7@7 z?m#v(TihQ!&%7W#m>_2D=(R>E)sfi_i%HB5f?5U7Jl^u@o z3{0H~nobZ*dfEsA&;7c~)?$CBhE0jGZ2obbv3ktCPEx+Zd?1>QcbWH?_X%nz2*ye0 zO6EgmC$o#7E`nwd1WVBsl7^^|hUBFMvCqg3xCBf4_iP<*J##>$>_LKNxzgE~L(FGR z)+vxp zN;~x36{+bf(xm+>-oMb({UP4h2*B)1oQu26Ku{kly1#SM@i*oVQHlRf(4rO0p9Ed= z7fPHJmo{03WeEbkd!tKw3gfgxp==yGE4(s92pf_Ab+Cx;1yP9WxSpSQ_ z!F(R90we;s6g@a@m+YNGj@dyV$80D;xAxHxYy=z0MlmoGT|y898E$jvg@4(*0e#?e zo&4a3BYU{Q#$FAGGI+25z`2yhB$Lu*$mbK@hmoz&0>eJ+3Zjj=1=z!bT2{o5d@a=0fHWU1Px;I zq%}Qum;hFE87$tx4?z!$64n=C7;)3=?VYnl;|7)vmhomw%VI&!kr3W9r zyJG>2Ef-$3s#9UY1jetZsA6<@qhtx&!;Q(ha7}m-B(!$fCfVoB8)A738U6olw-1obJH8qM)>FMDZA_h`$@^)5Nm> z89klDtDWs|^D)>N>|Ai&*_rGtb~ZbQptS_8Bj{0r9$UrEW9PG1vtU#nC+I1HUM1)Q zQG)+pcHPDA_MyJ;u!>zSJVel@KI+}ct5xiJ@Z;Il>?7R` z?&3=Xy-d(6A`AaN_v4+p8|+K$%kIPBHTHF|4E#ypt>MvG2QA*~#v5f3TPR zNO~Z-?GRsVn1UKi$?iPg5dY-4x@be;gG*`b}w!k(7pBHrZ=5k z|B5{UwwXQ39%GLa^cF#H6ZFnX_G^5S{g$A2g`)($_rL0@OLY55q}yqN-tV=;XW4TS ziT_7;nf*)7AfKiEHIlnlwRjFvGnRwk3lWeS;6#>se@O6DOOAoG-|WnMCG znUBm@<|p%)1;_$rL9$@kKv{@vkStUdCJUEE$RcG?vS?Y1ELIjLi`w;9$Z~(zU1P>&55W!&tM-UuEa16n51Sb$Y zm|zXTDFo}F-?9{$R;H8bWd@m1mMSyJ(q!o}vn)fFDa(=#k!8z<%5r2DS*|QkmM<%i z70QOmhRa6CM#@IXie#f@V`Rm$64_W;sjN&kPF60fkd2p3kX6d6WYw}7S*@&2W+m7_ za2mlG1P>uNpWtBx7ZY4ca3#UD1lJSXNbnSbTM3>{a3{et37$jne1Zjn7ZH3t!8a0o zE5WxDyp-U334V~^RRpgg_%VVv5WI=tX9#|d;2i|NLhu^|zfJJ_1b;;Eeu6(C_%nh( zC-_T(j}!b2frb3OaYk8_6gJysRkvRDEcibeSUuY-N-J_5+clFX@9qtD%9YS1-%zas2uv=qPLq^T`vJY zY*jD(d;9s90p}EPE1A2L-6A3Oxm7*wvJw05Mzpx&>LNL~T|(natGeYMLIVipPKmoE z6pmWe_RB`$iqnRoyo6Aoq{c; zm#-`S7X;0X#cxVDz`mHvcOU*EL6f%B_LvMYo5!6N?@4&TCfUDtXRn*;7LAu1HFil@ z{9#qU^8cuqK}JTY9S$G4kiPpIJ;Shb`trSl|ANn8lYqDvv-uMV4SXeNT#;#ph8=kf zj(oAcJGkA{$q@++=1QEDD?+1J%zzBeNr4**M+Cqi8v`W&so*C{XNY)B_dDS=tQ;IWVQM z;U;qO0TLSi|DeeAEMLubvx#ya36a1n5xM`89v6p- zcWzsM@)0Rv5qc$JdPQp6sVH44(rM7$#$ud=M);MW@gGUYUuqWMm|wKrC(qz@~INAbb`%&fDOLE^!0w}d@{2>-36voKD%EqbL4X+Fqs5r^#P;% z@T2VqYvvkLO*+V#G-`VhS}4CBAjucWuaRFXzmDK+f}txp1Y1_gZ;;<8LCYmLuLl}r zd|Yt2+COzz+h(7d{N=Z$NyJDs^>*Pd`F;Ho<9_)A68Z%M7xp1W^1;b39hAW6O$HZD zyX9*{O01NxlCPFOLhx{cM-V)c;8CmOYvr)rSPtuMMFfu)L5&d;2L3flwC-5?RY9qv z3wnL3ZhqBVoz{?^6mBrOdh?7Nwq{*|uP?~AN`xsPc&v*sKwrziPw#a|ZkpNbg7k{~ zO%c+o^4H|A%VCwVj9?h*}#YEoKm#9b(nZu!OLFL({1*w7jo=0ssLehd_s(kZcJ$BOI{*}vf(1wl zq`(SV!4TX;u$|zE1W#I}kSXL;lmgbvCllN(Lb~c-mE6#;fBE6e0ErkzyR)gbL5g6BEG-02?L(I7aRW?A{4PAsQyN@B2E!6fodao zS}&;9by;mztAoO()KnLw6onBWU1S3ksS1+>rJdjo7nCjA2ha9;W~l>;KCKs@AqqHW ztsf|PihK!57r`_7K+(;+?}ptDC`N-z{1l@UC1S7o8;^>yic$&EEP`jdAZ_;LxKra6 zN(9oUx>TN`Qc>40LRLk+1ZFP5^ITxIY)|U;(?m&N3~=IbkA+lBQozoSOVD|$qE!NQ zHNgv9pfLn7CUfktnqnp+ySF zXS)Q6ZdBX^1L78fuOawa5z=+ypx^B4TmRy?PzNNPQ9pmeTsYjiuUOupfD_UBLF`_6 z52VJDAw)y&l! zb)sU|>dm0#jk;7o%GfIlPbgr!#3efVwBi{6yoKP~2wp4#UeeRiiCvi+rH&fR&{4CS z;ZST-K=#)q#@{Q7R{`Yf1m8jMog&D)93Xv)-ygoS)B#ej6G6f`)O~69u43mULGDuQ zmKb|CfkRWA^xN!Hu`xJC*CQXjj*sGi0yZ98f|7?7M*zDo2)>Wt`$bR>NR-_EY4x$4 z4p4f1dMcdsM3*A85-Vwm(5nf4qz|Dh4LZ|MiFY9PJrb+rl%AKO zvr?_}qN0?La|J@XPK5NRMCWz)U+pnVVwv6~4k1H&UolVyDMJC~MM_i|rVIyokpw?Z z@Oly66Cymv*}N<7mEehI^E!{_b)p!r)Le>d%4B7V)Y**$KiQ|V!WLh?q6cK3-kOw| z{bH7-93p{vir}YRU_ia!yme)0k3^YW>QtGpgrhP07f$6!0Qo?vP?MvfGWo+%as*MaI>B#_yvNu61;7dvQk+k;rAlJ+k5c) zH{H@s`B$GDcgT{-?3%17?aHe}vh-)Llv9)~QV(7t_+=M`!C)QD$;og)O6%3@$`0kM zOA>gtat;u99>K2?{F(^qb&0?`*1R89BN14y*NIY@+Si*?E>wyWpo^vQ24&CW=S_m& za$zRgz?^Lby$o|o;}Ydk5w-s2QOdiO_W)|3mEIxvT@e%{go=AS%2%z?otDNjkPFnN z*$uOYm7>*9E?2Hlb}LsB`~ktR6M84XyH+VzE5T|gVF2zXc#jBj@4u>+eq0wDcG_4q zS8sr;2*kk(ok=(MQBBHCO4!HOzmKYXR{5MH1p5g7*hT8ip(mz{{OFIWxv37I#$JKi zp?vLRrh6L*X!3TR``P2*xf4Il*H1`=@@52%Omtxx<z*81Yo*L?=p%r%(PfL{94G}jbP z`L*%~fOfHDo^-k#VCwq194R+_bs)|uk7t#?iKz5D=zdrJK}B&C!Cw)4R7B;NLmqv7 zlV5-GsoJ?Zy;cwQQI}>)6K9r&v@|%7*=1xn8OQgB7N_Doqz;}S_-j`OVfyn;-FXji zWYSFF=j+mpE@zMP<%0T!6wD2jAbm^lcYPoYzE(G5cF)i=yWDCnl8Y0&+TYOQ;yE}^ zi5pDt4+NhSLH#HVz4=Vh@;V7rx>g51fx#qlv$vNz&H!5?I6c8Xt>7TSbH*)umNQE+ zDM*Z2{8x*X&V-TP3>3!(B*->thtss1#Pj?w*yOI6)I4!|bHk*W6Q@j?J+-r8(yR`9 zR~MwZc1-H*N^xvSN`akAj-!773|#+k0e~I>;Ig=Eu>(U0{&@ul9X~572-g;>3wKyb z`<1vn$SUXZ2|fqe_}nmQ6D?K3jo?OdqojicT_+=yz#gSBT~izE?XZgrpC|Yif`9$L zj~t?&9b4PDda>hF8m^ctk)<-ME4v=Y)WTei-efdtj0J`Hn%vaf zT#YW@oR*t!fhG)=z8Kvo0fLN=3jpP7bq1r>VA7=KiCu$@cAE6uG`+@<3bz8~7o=%* zX>J(ZCIN!HjSB$f<>i^o`qWg7r9cn&B^9I>YI5^)3pDx0LW9|$P0KZ#-Dq^D1PJmj zE&!yn6sD#d&435Y`!q&lA$&?N%mcW21zKa8KG&G*)-~}^WjKZgGAJ$pq|M8NRtvP6 z0&RLK+;U{f)mT!^g&LDKUz@5m>x_8?xqWH0OacU14i^A2>9uK=!gK?mpfzcXI$f$J z*K91%SoEodT2p$urBK&*p^EF406~_*1%S+^Gz$b>&6)y(5!jz=(Q7P)`DvPTlQ};( z9cZL4F!#l1jRXi14K4s=vZR|p^3pW<77GyDpao>o({eTWxj-cyNUKTjMx)0iK#($U z0ie9XJgw1WNz<4M((^UORN!AagxZ1jx>UU$tX6JrVPA}%lmJ0?zy*Nv3-n+sb$U&{ zIb91FiR{`xgKzuo&~q>4iE?L2fP(J0Aoxw?Ln& zDa?n?S&T*?lv~$ckO0B@`~`pt(?E_b1{hq1bO59^8AOZ#TA{8W%~+sKP0uapi_s1V z5G=7@2q-<*4EJIIc?t`G*cOXUV>aidYx1=Qvo_CYF{SDA`vQ7R0t5@>7XZ>53$+%5 zHdkXPOa+Y0d0I`b(QJX9!caD+8_f9@y;F(4$-ONau(t>ux&j&DNaeq@U(Q+|a1d)) z!F@>R@DTvD zV^}*Jw=7h`X}9)S;>9im&Tga>gr*1`wVV5#`-0+WE%zn&6`X$3bGoWnOgehian7yd z|2c3w^%|O`so{=#Dig$ zq{c|-)Qg76W$A56)Oangq6t2M zxgRvSWqg4XP2fd_OSt)A+*gFobhS5_q@n9Xq>L}W#G6XK8s79B z?#?<^-gb#Pc7D<&>P+FMy6W()gwAz#c)HkOIIu0RpAPf0_}R`5=M%c%BEDRfLUr+F zo=Bxa7nK%>Tw(fhWg&l!h`vKt@z)Z1xD&}6L?mw{^oV|t_y-9+n$Tmq`G@$230+L+5>Z)-CmzFmrMc1WR1DHhIMOr6 zH58q2>KfcL1?M(2&FE}$l-0C|r(441N>iu7Y3uD7j<4diOck@zO;(f9$;?OiwIXBI z5V~{)zmCvwwV8Oxpm^AWbk2AGhfg@GKf!N;-M0J&ek1=Rfn!$b3PO)x$v?$EO9-f9V5M`){vb?im$xFHEE?{K(;c>40-zb=>yyC%!*aG!{HndRizOY9R-)US5pme>*aK+11@i00QWrJM%_m}NIgU?r&huRiEH5Y zx{Yw5;7f2Z`%da(xRU)#xRU)i^&3J+1=oXxzztyWC!P^3)Huut&&t>B>fL}o4Wmh10s6O+4uYzIN%0`?@9hg{x$w5{z7Y0%s3& zu6X0kUqBKI^;{S6Ka>;`cN`_7auibMcd2NKS1~G96lw9sJx4y%o1Yy7{nX}gAXRde zLUKFp-72~0Ec#Z$Rug-BlWlgmtrJeP)$8CmTlLot)u>Xz`8SjYT;uCJIz**b`NKh7 zDle6{%17m^g4jkUp=S_!7NO@5dfsYPfGSWGqzYCIB=psUUPS2Y34Jr6Z*vP&sKTWg zM%Uk-iujjVr>YnU4Y+dl@;7k(N6D|fDQb{@=a!zWN|bN_qwr5{-{_lws7jHVpZo9R zWxJtblu()f?;lS}IWFE-rKvLDTpLxo%1r15gciD0nJNgw5kfB%Eafwsn>r^~Oty>H z2}b2C+~F95t`9wiSCywK6k+6xFs^aH7^WIdXmA&=bHZ@daeZ)B9-|s7RxTDR-{7cR zswyKixR!8qnuLI>j_ZT7a;2)~0_c3^^D?@ObbB<$|JXlj#pWx-3; zVhPaw|8x>|-;Ef&l=M#<`|&bV_o(hIcO0_qa5RFbNNO;ZN@Y+(<#Xjkew+Mm`3gwu zTrb}se^S0#{;d23`8N5N@?RAS$TAzK7^Db;^sy*K3?zyrC^8gTifl!WB3F^GC{zqr zj8qgUsuc?qI~1QNd8I}K84ru20oP^&X44a_%VD5U&@c;EBFa~6<@=*@i*{y^DFpg`S8S z;I#p}2J9Q~?SMZ$2Y5z!4)Gl7Y4ObSEbtuWIoorg=Z&5>d*14~*zi&- zW$|k9y3uQs*LJTrymou-_1fpP-|KU)<6hr+{p9tVx3_nYccgcWcbs>Ex5aymcdfV8 z+veTqZTFt!-RwQZdye-!@2kB9?}gsicwgszgZE9|cX~hM{fPH=?|t4!yua~2=YxD` zAJ#|iqxA9i@%8cd3G@l}3GvDB8SgX4=T4soeU|w=?6bn>37;o@p7Po3^Q_PFKJWV+ z^f}~n*yjtMuY8XA{OZg2Dt&oh4_{B;5Z?&jDBl?0MBgOeWM8dsw(nS9tM6prF5fx6 z^L(%NUF3VM@AbYn`Y!c-$ajtJX5VeTZ~MOI`+@H+-#xw``F`#DlkYj-^S;0N{^7^_ zsr|hDeEov_2Ko*13-idUcU$Y zmiayG_mtlbzgPTT^Lx|pZNGQ@PWb)och>Km-+6zzKj*LV_w@Jj_wkSO*ZQaWr}>-x zGyRAAkM=M2AM0P?Kf%Aszs7%}f1Ce2f8xK$|62c>{BQBU&3}o1xBp}QTm5(Xe-j`J zPy}!Rs(=9jaRJ(Zw1B*Ti2>~aodGifW(CX%SR8PBz?}h01MUg9FQ7YMUBF`j>jO3f zJQ?tOz}A2l1KtRDE8v}gJpmsDd>n8r;B>&x0p|kF2l@p11qK8L1r7|14vY&-2pk+} z46F-m47@e)?!c{qF9jY8JRNv8@Rz{f0{;l2f|Nl6g499YLB2r|L9s#cL5V>rLAoGA zP->7VXlPJT(Ac1|pz@%qpqik%p!%TZpcz5e2i+KSbI`3pi-T?tx-)2L&^m z2|gKoD)@Bp&%x({&js7I)OXn1I3XjEuYXm)5p=$O#)p&g-f zLhlZJEcBVsmqR}Y-5I(&bZ_XP(8HnMg`N-nJ@n5o9L9vn!aTx4!(zgc!&1Yt!z^KW zVFh8OVbx&`VUxmUg)ItO5_VtM17WMeHiSJLwmt04u(!i@haC(1J{*U8geQfY!;8Yl zgqMVuhK~!c2%ivM6 zM0iIeN909RMKne znCUUs#M~LPJZ5#w+L*^;HpV;^vpMG3n0I16j`=j^aLgAm$78;U`99`kEFG(k^@;V1 z4U8QaJ190WRuij@HN=`?(_;%_hsTbL9UWT|TN-PPt&g?EHpWhiC9&7UULSi??5(j& zV(*N-JNCZVM`PE=Zj9X&`%LVX*ym!m#%_;&DfVdWA8}D}8FBS-^WyG^TNk$@?!CAV z<95aEjr%z6K-{so<8deAzKJ^>cP8#!Jc^gctKz-m2gXOn$Hd3S4~|ccH^sNaFN=RP zetrCg_)YQ8#BYgzHU5qGx8vW7|1f@6{PFlR@#o@yjsGJ7CC~{;3Fd^XgzN-MLViMF zLUBSxLS;ftf;GXG(3;SZ(3LPVVP3+5goO#$B;1p*JYjvpri7;xHYdE0@M6MC39lsV zOgNBmEaBUP?-NcYoJlyB@N2^FiR#3l#JPz#BtD$jowz!2ZQ^5zPb5B>_;liy#OD*Y zCGJSvm$*Oilf*-bM-snGJeK%%;&+KB6Hg_cPW*YW$Kb@l`GczmPagch;Pr#w8+<$o zCj}+NCZ#0llTwq?lQNU?lZGXYOd6e3l2n>>OVTq*JClCZC^ViLZ;hWOP!pz!)Wm4w zHHjKna@1sMvNf-3c5C)(_Gu0zS0_(SzACvTxh?r@3X|fIqE7Ki@lOd#iA;$}iBB1v z0x_JF>XaK(o=rKHaysQ~%K4PvwUicX{k37*XlouZwpZPRvYXKLqY=V`Ci-l1KoeMGxX`?z+4c9ZrQ?X%h!wC`#^(C*Ui)qbo! zs6C`TqWw~PRHxKM>xSy4>Tb}j)V-)XraP@Wqx)HRPS5IPdbwVy_tyLA1NFiBBuE6v z&}Zt0=tt^D>5KGZ^ws(reXZWApRAv*@6^xK&(`0hze|6Q{(k*3{c=NsL2nppC^U>P z6d8&Q6^2SfjlpWL873Rr40jkFH@s|k$MC*kr(w6@u;GZ|bHkU0?~EQsU!&1D(%592 zZk%UaU|eXt)_8;QX5-z)`-~47A2xOyR~y$D_od=gU21*mlGMjjpG)1Ex;^#f)Ynqq zNIjVPW$KC4Z&QCr{W0|q6K#^2l%@eDFO#py-xO_1Gv$~@n@UaPrU|B6Q@yFtWH+^% zZZh3zy4!T0=>gN@rVXY|re{pgra^W=T5(!MT4h>Inl)`=T60=UT3g!mv{`A((wA#z0W~EtW9$*eI2bss3tIU(kSDB}pr&#-|yFGrq_;nsFlI zn@s=A{LGHb?#vCDn=+ry+>-fx=GM&DGT+X8FZ099U74R{ewleR^LXZWnI|)U$~==5 zlogqkl4Z;?Wu<2g$r_rKo0Xq6I;$#cN>*#u^sLUTnOSqP=4T06i?Z&@x+m-YtYult zvsPw3lC>`D@vJAZc4mD$L_Q>SNXd{XL#`XLVaUcI+lIV2Wc!ephP*%IgCQRd*)`1;OJJKHDQH`_luEIU4XaCUOGHrtY&pFJ#lWcKLn zz1fGdzsWw8eJ1-{_OC=&|53L{CICSFB$wRw_&KNp#=8@qip`vaoTQwT9DPn|PI^vePIitZCqHLc&d8k6 zIVCw|ITbmTIW;-foCY|Gd~(i|oYtJ_Ih{E(bLQmC&k=GKACMp?#K z##+W%##^c^wU&BIqh+F{+0tTZv$R{fEVC?gEmvEJTNmYXcMT9#Puusm#8VOeQ; zBsU;8IyW{qK6h|#XD-QIlzVON4Y_~h@p&G3o_XGR)p?WiuF7l4Ys>p0?_}PoywiDS z^IP-h=FiVxkiRhho&1mU59EK6|5-s(!SsTTg06yD1>Y2$D>z^9Tfv`&t%Y+7=NB$0 zTv+&Z;n~7p3V$v9V_563xx?lUTQF?luy=-iJnX=*PlkOqym)xc@Vepk!yAXMAO8IC zt;1g&{?Z8Di0lzLBXUO+jMy^b)e*0ccyq)%BP}Dxj4T;hIh1k;T!)am5c7uPc76czyB4l7S`hC5a_TB`GC4O5Q8^pk!ys zp0OjwR*ao6wrXtc*bl~jGWO8e!(+cF9aCCeT3c!@Z76-b^tsX(O1G8nC^MAhl;xJ? zmklf1TJ~1iJ7w>ceK;<6T=BTEk6Y3}IoN#Eu;R&Bl_^Pt9a$@D=%Bw1;R(@9bZRPisCo6xd%BmVsHL7ZKRY}$M zs&}jQR_&|WUv;qR)2gFYC#t@!`o8MNs-LQUt7fZJ)j`#f)zQ_l)$!Gd)rM+QwYfU8 zI=ecjdPH?ub$xYn^_1$V)os<&tLIeDuNJBoR$p6vef5&+Wz~;XKUKZC`nl?@)!VDz ztbV8Z{pt^^cUSMNK3Nk`6H_y~rlO|4W@^ohnprh-YUb5kU2}cSO*OaHEUvku=B}D$ zHEU{~uGv)P*XPu8BQJyUzO&b!WB zH>|F$ZdM(syRGh?y8G%Ls9RR|aNXLv$LgM_+gSHh-7|GB*1cKxVcn;7N9&H)eO>o$ z-S>58>(1BxUiYUJTN$f|HNYBe)mXJwgVkg;TXU^&aJhA)b+onEI>BnQwpwRe=UC@k z1?wW~E!M@>JFItE@3G!zecF1^dZON|KDa)*KDj=#KEHlg{mA;!^(FO{^)>a@dRu){ z{lxmV`q}l@)i18Uqkd`qz4Z^&uc}{D|7iW=^&9G+tbe}#mHH3s_tzh+|Fr(I`XlvU z*MC=kvi?;4nfkLf%BHmW+rn%SwkTVSEzYL38Eht7x-HW-#8zl4w$<3|w#l|BwpQD8 z+Z@|`n_ydLyViESZHeuE+Zx+O+a}x7w#~L@Z7(x}mP2z5xy{Ygo{5 zL&MDtw>8|}a96{!hUE<_8&)^0ZFscdsfMi$uQlvyIN0!M!)Fag8op@ww&90{Qw^sZ z&Nlqgh#Nf{0~-f6hBihtMmK62wT*_x)W-D2jK;jilE(j2)0uzQkR@wIDf6I1cJF&@Z3frAcXEWGA>=1T1 zJCgm7oyyK-mo!dnki~2+YqB<*$A;Jl>#-}@b?g`HF7_aMnEi%5#(vA5Wh>cp?0NPA zdx?F*b>{kTGr62b$1dVb&gCc<;|jPH+!}5@w~_mt+rn+-c5wT-<6Jpc!Buhps}%6JZkU0=vRg z*bnxH1L0se432;wz{zk9Tm%^ipa4avLjoO`2VEF}%i$Wh8Sa4l;Q?3*55uGIB>WDZ zffcX{o`aX+P521Dgs+7rLNlSI@V3xiNEF@`It$4{nvfxk5Hf{n!c1YdFh|G{7y$@^ zfEy)mim+VRD;yJk5&k2*Ld{V-)ET{px}hGZ7aD*DqhV+S`aK$rCZL&U0pbxt5>k+g z0w{zc$U{p}0s0JWLSLi3s05XwBd83WLglCeRibm~Ji3Bv(K8%}o8lI@HBP|q;CFFn zoQzX&D(;6z;7mLX&%ht!**F_7#7i)Td5o}#bsWLVaUm|kf5hwX7W`+t9e;&);GOsY zK7lK7HNJ^&<2(2+zK@^c=lB(VEjAIGiV0$pm?mb31I5AOP;t08Rvafz5GRRK#4Ise zTqH`OAzETU42cnOxmYL`iN)etalQD3xI-)v|1O>szZ1`h--}h^6|qLVCf<+?iApi4 zKw2TKl8U6A(gEp^bW|#nDy3hfTIs&@PSIVp9VtK8+LEa?)N!}`N zlfRVr%Ln9A`H1{bu9q8>CQ379q%uL7q)b+_l!&rQDN>4+waOXgqVkhct7VHT$UoH|_80nB`#(3))f6>V?V zleH{ux;9gjG+WElT#afmEnoYKwo}`q?bAxMa_x$CTdURXY4^2<+G9OV@1UpYee`sF zs6JXBtB=#C>N)yi9qK+kPmkz@`Z|4&eo(K{Z|RTqr}}gKmHyg@Gujw$8|{rmBgyD& z^e}oEeT{VE17o}~!I)@FHnNNyLoyU2&u|TD#Eg7nnX%p2XB;pN8ApvWLOV zPpzg_3#+x&&PueBtTd~Sm2PENgRCLeXltxB&dRiMtohbLYmvoRz)~&4qE^f*uvS=w z)@ti>Ypb=*`pVjA?XmV*CDv){n%%-~V|TKX?G(Gaoo4s8huKr@x%MKPv4Jhvimlp) zZP|{!%RX&ix9{3d>}U21yWWX&;+?imqLbuwak@HbP9G=T$#4cbIZnQ_-}%P*n{(1R z=Uj5Cof_x5bH};o)H#owCr*7JE|3`L9_SnRU0^_9a9~tmbYN^?Tp%+rE$~TTL9i@% zJotU^a`0;KTJT2jcCa>hKlmb8A8ZK4hnk04hFXW-3JnN-5($Rl z4Aq2ggkFZ~->?~O8@H3&)9vl{bNjmk-64$<&kx;9cal5Bo#xJP=erBt#V+e!aBsM` z8m;no!}G#0jKX4A4*wLs9ljI38-5VsBL0XLF(Ovv1#L+aXj|HjcBGwXGVMxx(sVkM zj-gZN3_6Qu(|L3OT}&A&P(O8OK3z#y(_*@wZls&(7P_78rls^GEvFTDQ$9g_b^>mMT zwca!Dx%bk09o3@YD2+y=`O!7eb|19>zTHUIzs diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist deleted file mode 100644 index 05301bc2538..00000000000 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints.xcbkptlist +++ /dev/null @@ -1,5 +0,0 @@ - - - diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist deleted file mode 100644 index 24d58772dea..00000000000 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist +++ /dev/null @@ -1,101 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme index 03a279e1c62..00830cf82b3 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme @@ -1,6 +1,6 @@ @@ -28,12 +28,22 @@ shouldUseLaunchSchemeArgsEnv = "YES" buildConfiguration = "Debug"> + + + + @@ -51,8 +61,8 @@ @@ -69,8 +79,8 @@ diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist index b2f510b9606..163c84ef64d 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/xcschememanagement.plist @@ -9,20 +9,15 @@ orderHint 0 - PetstoreClientTests.xcscheme - - orderHint - 1 - SuppressBuildableAutocreation - EA07F4B816134F27006A2112 + EA6699951811D2FA00A70D03 primary - EA07F4F11613521A006A2112 + EA6699B91811D2FB00A70D03 primary diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h new file mode 100644 index 00000000000..c6172fd5fcc --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.h @@ -0,0 +1,15 @@ +// +// AppDelegate.h +// PetstoreClient +// +// Created by Tony Tam on 10/18/13. +// Copyright (c) 2013 Reverb. All rights reserved. +// + +#import + +@interface AppDelegate : UIResponder + +@property (strong, nonatomic) UIWindow *window; + +@end diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m new file mode 100644 index 00000000000..c0013e2cbed --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/AppDelegate.m @@ -0,0 +1,46 @@ +// +// AppDelegate.m +// PetstoreClient +// +// Created by Tony Tam on 10/18/13. +// Copyright (c) 2013 Reverb. All rights reserved. +// + +#import "AppDelegate.h" + +@implementation AppDelegate + +- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions +{ + // Override point for customization after application launch. + return YES; +} + +- (void)applicationWillResignActive:(UIApplication *)application +{ + // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. + // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. +} + +- (void)applicationDidEnterBackground:(UIApplication *)application +{ + // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. + // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. +} + +- (void)applicationWillEnterForeground:(UIApplication *)application +{ + // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. +} + +- (void)applicationDidBecomeActive:(UIApplication *)application +{ + // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. +} + +- (void)applicationWillTerminate:(UIApplication *)application +{ + // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. +} + +@end diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPad.storyboard b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPad.storyboard new file mode 100644 index 00000000000..a185e8a5dfa --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPad.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPhone.storyboard b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPhone.storyboard new file mode 100644 index 00000000000..b99208bd774 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Base.lproj/Main_iPhone.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 00000000000..91bf9c14a73 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,53 @@ +{ + "images" : [ + { + "idiom" : "iphone", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "iphone", + "size" : "60x60", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "29x29", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "40x40", + "scale" : "2x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "1x" + }, + { + "idiom" : "ipad", + "size" : "76x76", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/LaunchImage.launchimage/Contents.json b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/LaunchImage.launchimage/Contents.json new file mode 100644 index 00000000000..6f870a4629d --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/Images.xcassets/LaunchImage.launchimage/Contents.json @@ -0,0 +1,51 @@ +{ + "images" : [ + { + "orientation" : "portrait", + "idiom" : "iphone", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "iphone", + "subtype" : "retina4", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "1x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "1x" + }, + { + "orientation" : "portrait", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + }, + { + "orientation" : "landscape", + "idiom" : "ipad", + "extent" : "full-screen", + "minimum-system-version" : "7.0", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Info.plist b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Info.plist new file mode 100644 index 00000000000..7296c17fbf8 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Info.plist @@ -0,0 +1,49 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleDisplayName + ${PRODUCT_NAME} + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + com.reverb.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + ${PRODUCT_NAME} + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + LSRequiresIPhoneOS + + UIMainStoryboardFile + Main_iPhone + UIMainStoryboardFile~ipad + Main_iPad + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Prefix.pch b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Prefix.pch index 2a173ae6548..80b02fc3cad 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Prefix.pch +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient-Prefix.pch @@ -1,7 +1,17 @@ // -// Prefix header for all source files of the 'PetstoreClient' target in the 'PetstoreClient' project +// Prefix header +// +// The contents of this file are implicitly included at the beginning of every source file. // -#ifdef __OBJC__ - #import +#import + +#ifndef __IPHONE_5_0 +#warning "This project uses features only available in iOS SDK 5.0 and later." +#endif + +#ifdef __OBJC__ + #import + #import + #import #endif diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient.1 b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient.1 deleted file mode 100644 index 91252bc19a7..00000000000 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/PetstoreClient.1 +++ /dev/null @@ -1,79 +0,0 @@ -.\"Modified from man(1) of FreeBSD, the NetBSD mdoc.template, and mdoc.samples. -.\"See Also: -.\"man mdoc.samples for a complete listing of options -.\"man mdoc for the short list of editing options -.\"/usr/share/misc/mdoc.template -.Dd 9/26/12 \" DATE -.Dt PetstoreClient 1 \" Program name and manual section number -.Os Darwin -.Sh NAME \" Section Header - required - don't modify -.Nm PetstoreClient, -.\" The following lines are read in generating the apropos(man -k) database. Use only key -.\" words here as the database is built based on the words here and in the .ND line. -.Nm Other_name_for_same_program(), -.Nm Yet another name for the same program. -.\" Use .Nm macro to designate other names for the documented program. -.Nd This line parsed for whatis database. -.Sh SYNOPSIS \" Section Header - required - don't modify -.Nm -.Op Fl abcd \" [-abcd] -.Op Fl a Ar path \" [-a path] -.Op Ar file \" [file] -.Op Ar \" [file ...] -.Ar arg0 \" Underlined argument - use .Ar anywhere to underline -arg2 ... \" Arguments -.Sh DESCRIPTION \" Section Header - required - don't modify -Use the .Nm macro to refer to your program throughout the man page like such: -.Nm -Underlining is accomplished with the .Ar macro like this: -.Ar underlined text . -.Pp \" Inserts a space -A list of items with descriptions: -.Bl -tag -width -indent \" Begins a tagged list -.It item a \" Each item preceded by .It macro -Description of item a -.It item b -Description of item b -.El \" Ends the list -.Pp -A list of flags and their descriptions: -.Bl -tag -width -indent \" Differs from above in tag removed -.It Fl a \"-a flag as a list item -Description of -a flag -.It Fl b -Description of -b flag -.El \" Ends the list -.Pp -.\" .Sh ENVIRONMENT \" May not be needed -.\" .Bl -tag -width "ENV_VAR_1" -indent \" ENV_VAR_1 is width of the string ENV_VAR_1 -.\" .It Ev ENV_VAR_1 -.\" Description of ENV_VAR_1 -.\" .It Ev ENV_VAR_2 -.\" Description of ENV_VAR_2 -.\" .El -.Sh FILES \" File used or created by the topic of the man page -.Bl -tag -width "/Users/joeuser/Library/really_long_file_name" -compact -.It Pa /usr/share/file_name -FILE_1 description -.It Pa /Users/joeuser/Library/really_long_file_name -FILE_2 description -.El \" Ends the list -.\" .Sh DIAGNOSTICS \" May not be needed -.\" .Bl -diag -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .It Diagnostic Tag -.\" Diagnostic informtion here. -.\" .El -.Sh SEE ALSO -.\" List links in ascending order by section, alphabetically within a section. -.\" Please do not reference files that do not exist without filing a bug report -.Xr a 1 , -.Xr b 1 , -.Xr c 1 , -.Xr a 2 , -.Xr b 2 , -.Xr a 3 , -.Xr b 3 -.\" .Sh BUGS \" Document known, unremedied bugs -.\" .Sh HISTORY \" Document history if command behaves in a unique manner diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h new file mode 100644 index 00000000000..4df89c445de --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.h @@ -0,0 +1,13 @@ +// +// ViewController.h +// PetstoreClient +// +// Created by Tony Tam on 10/18/13. +// Copyright (c) 2013 Reverb. All rights reserved. +// + +#import + +@interface ViewController : UIViewController + +@end diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m new file mode 100644 index 00000000000..d8e593c5079 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m @@ -0,0 +1,36 @@ +// +// ViewController.m +// PetstoreClient +// +// Created by Tony Tam on 10/18/13. +// Copyright (c) 2013 Reverb. All rights reserved. +// + +#import "ViewController.h" +#import "SWGPetApi.h" + +@interface ViewController () + +@end + +@implementation ViewController + +- (void)viewDidLoad +{ + [super viewDidLoad]; + // Do any additional setup after loading the view, typically from a nib. + + SWGPetApi * api = [[SWGPetApi alloc] init]; + + [api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) { + NSLog(@"%@", [output asDictionary]); + }]; +} + +- (void)didReceiveMemoryWarning +{ + [super didReceiveMemoryWarning]; + // Dispose of any resources that can be recreated. +} + +@end diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/en.lproj/InfoPlist.strings b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/en.lproj/InfoPlist.strings new file mode 100644 index 00000000000..477b28ff8f8 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m index 33b41ff2485..644c21bf165 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/main.m @@ -2,21 +2,17 @@ // main.m // PetstoreClient // -// Created by Tony Tam on 9/26/12. -// Copyright (c) 2012 Tony Tam. All rights reserved. +// Created by Tony Tam on 10/18/13. +// Copyright (c) 2013 Reverb. All rights reserved. // -#import +#import -int main(int argc, const char * argv[]) +#import "AppDelegate.h" + +int main(int argc, char * argv[]) { - @autoreleasepool { - - // insert code here... - NSLog(@"Hello, World!"); - + return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); } - return 0; } - diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests-Info.plist b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests-Info.plist new file mode 100644 index 00000000000..f445ddd474d --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests-Info.plist @@ -0,0 +1,22 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + ${EXECUTABLE_NAME} + CFBundleIdentifier + com.reverb.${PRODUCT_NAME:rfc1034identifier} + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1 + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m new file mode 100644 index 00000000000..f523807b470 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m @@ -0,0 +1,34 @@ +// +// PetstoreClientTests.m +// PetstoreClientTests +// +// Created by Tony Tam on 10/18/13. +// Copyright (c) 2013 Reverb. All rights reserved. +// + +#import + +@interface PetstoreClientTests : XCTestCase + +@end + +@implementation PetstoreClientTests + +- (void)setUp +{ + [super setUp]; + // Put setup code here. This method is called before the invocation of each test method in the class. +} + +- (void)tearDown +{ + // Put teardown code here. This method is called after the invocation of each test method in the class. + [super tearDown]; +} + +- (void)testExample +{ + XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__); +} + +@end diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/en.lproj/InfoPlist.strings b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/en.lproj/InfoPlist.strings new file mode 100644 index 00000000000..477b28ff8f8 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/en.lproj/InfoPlist.strings @@ -0,0 +1,2 @@ +/* Localized versions of Info.plist keys */ + diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile new file mode 100644 index 00000000000..36e97d70a75 --- /dev/null +++ b/samples/client/petstore/objc/Podfile @@ -0,0 +1,4 @@ +platform :ios, '6.0' +xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' +pod 'AFNetworking', '~> 1.0' + diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock new file mode 100644 index 00000000000..f52a69324db --- /dev/null +++ b/samples/client/petstore/objc/Podfile.lock @@ -0,0 +1,10 @@ +PODS: + - AFNetworking (1.3.3) + +DEPENDENCIES: + - AFNetworking (~> 1.0) + +SPEC CHECKSUMS: + AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b + +COCOAPODS: 0.25.0 diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h new file mode 100644 index 00000000000..3826b6f2f5c --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.h @@ -0,0 +1,641 @@ +// AFHTTPClient.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFURLConnectionOperation.h" + +#import + +/** + `AFHTTPClient` captures the common patterns of communicating with an web application over HTTP. It encapsulates information like base URL, authorization credentials, and HTTP headers, and uses them to construct and manage the execution of HTTP request operations. + + ## Automatic Content Parsing + + Instances of `AFHTTPClient` may specify which types of requests it expects and should handle by registering HTTP operation classes for automatic parsing. Registered classes will determine whether they can handle a particular request, and then construct a request operation accordingly in `enqueueHTTPRequestOperationWithRequest:success:failure`. + + ## Subclassing Notes + + In most cases, one should create an `AFHTTPClient` subclass for each website or web application that your application communicates with. It is often useful, also, to define a class method that returns a singleton shared HTTP client in each subclass, that persists authentication credentials and other configuration across the entire application. + + ## Methods to Override + + To change the behavior of all url request construction for an `AFHTTPClient` subclass, override `requestWithMethod:path:parameters`. + + To change the behavior of all request operation construction for an `AFHTTPClient` subclass, override `HTTPRequestOperationWithRequest:success:failure`. + + ## Default Headers + + By default, `AFHTTPClient` sets the following HTTP headers: + + - `Accept-Language: (comma-delimited preferred languages), en-us;q=0.8` + - `User-Agent: (generated user agent)` + + You can override these HTTP headers or define new ones using `setDefaultHeader:value:`. + + ## URL Construction Using Relative Paths + + Both `-requestWithMethod:path:parameters:` and `-multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:` construct URLs from the path relative to the `-baseURL`, using `NSURL +URLWithString:relativeToURL:`. Below are a few examples of how `baseURL` and relative paths interact: + + NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; + [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz + [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo + [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo + [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ + [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/ + + Also important to note is that a trailing slash will be added to any `baseURL` without one, which would otherwise cause unexpected behavior when constructing URLs using paths without a leading slash. + + ## NSCoding / NSCopying Conformance + + `AFHTTPClient` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. There are a few minor caveats to keep in mind, however: + + - Archives and copies of HTTP clients will be initialized with an empty operation queue. + - NSCoding cannot serialize / deserialize block properties, so an archive of an HTTP client will not include any reachability callback block that may be set. + */ + +#ifdef _SYSTEMCONFIGURATION_H +typedef enum { + AFNetworkReachabilityStatusUnknown = -1, + AFNetworkReachabilityStatusNotReachable = 0, + AFNetworkReachabilityStatusReachableViaWWAN = 1, + AFNetworkReachabilityStatusReachableViaWiFi = 2, +} AFNetworkReachabilityStatus; +#else +#pragma message("SystemConfiguration framework not found in project, or not included in precompiled header. Network reachability functionality will not be available.") +#endif + +#ifndef __UTTYPE__ +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#pragma message("MobileCoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.") +#else +#pragma message("CoreServices framework not found in project, or not included in precompiled header. Automatic MIME type detection when uploading files in multipart requests will not be available.") +#endif +#endif + +typedef enum { + AFFormURLParameterEncoding, + AFJSONParameterEncoding, + AFPropertyListParameterEncoding, +} AFHTTPClientParameterEncoding; + +@class AFHTTPRequestOperation; +@protocol AFMultipartFormData; + +@interface AFHTTPClient : NSObject + +///--------------------------------------- +/// @name Accessing HTTP Client Properties +///--------------------------------------- + +/** + The url used as the base for paths specified in methods such as `getPath:parameters:success:failure` + */ +@property (readonly, nonatomic, strong) NSURL *baseURL; + +/** + The string encoding used in constructing url requests. This is `NSUTF8StringEncoding` by default. + */ +@property (nonatomic, assign) NSStringEncoding stringEncoding; + +/** + The `AFHTTPClientParameterEncoding` value corresponding to how parameters are encoded into a request body for request methods other than `GET`, `HEAD` or `DELETE`. This is `AFFormURLParameterEncoding` by default. + + @warning Some nested parameter structures, such as a keyed array of hashes containing inconsistent keys (i.e. `@{@"": @[@{@"a" : @(1)}, @{@"b" : @(2)}]}`), cannot be unambiguously represented in query strings. It is strongly recommended that an unambiguous encoding, such as `AFJSONParameterEncoding`, is used when posting complicated or nondeterministic parameter structures. + */ +@property (nonatomic, assign) AFHTTPClientParameterEncoding parameterEncoding; + +/** + The operation queue which manages operations enqueued by the HTTP client. + */ +@property (readonly, nonatomic, strong) NSOperationQueue *operationQueue; + +/** + The reachability status from the device to the current `baseURL` of the `AFHTTPClient`. + + @warning This property requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +#ifdef _SYSTEMCONFIGURATION_H +@property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +#endif + +/** + Default SSL pinning mode for each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:`. + */ +@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode defaultSSLPinningMode; + +/** + Whether each `AFHTTPRequestOperation` created by `HTTPRequestOperationWithRequest:success:failure:` should accept an invalid SSL certificate. + + If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate; + +///--------------------------------------------- +/// @name Creating and Initializing HTTP Clients +///--------------------------------------------- + +/** + Creates and initializes an `AFHTTPClient` object with the specified base URL. + + @param url The base URL for the HTTP client. This argument must not be `nil`. + + @return The newly-initialized HTTP client + */ ++ (instancetype)clientWithBaseURL:(NSURL *)url; + +/** + Initializes an `AFHTTPClient` object with the specified base URL. + + This is the designated initializer. + + @param url The base URL for the HTTP client. This argument must not be `nil`. + + @return The newly-initialized HTTP client + */ +- (id)initWithBaseURL:(NSURL *)url; + +///----------------------------------- +/// @name Managing Reachability Status +///----------------------------------- + +/** + Sets a callback to be executed when the network availability of the `baseURL` host changes. + + @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. + + @warning This method requires the `SystemConfiguration` framework. Add it in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +#ifdef _SYSTEMCONFIGURATION_H +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block; +#endif + +///------------------------------- +/// @name Managing HTTP Operations +///------------------------------- + +/** + Attempts to register a subclass of `AFHTTPRequestOperation`, adding it to a chain to automatically generate request operations from a URL request. + + When `enqueueHTTPRequestOperationWithRequest:success:failure` is invoked, each registered class is consulted in turn to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to create an operation using `initWithURLRequest:` and do `setCompletionBlockWithSuccess:failure:`. There is no guarantee that all registered classes will be consulted. Classes are consulted in the reverse order of their registration. Attempting to register an already-registered class will move it to the top of the list. + + @param operationClass The subclass of `AFHTTPRequestOperation` to register + + @return `YES` if the registration is successful, `NO` otherwise. The only failure condition is if `operationClass` is not a subclass of `AFHTTPRequestOperation`. + */ +- (BOOL)registerHTTPOperationClass:(Class)operationClass; + +/** + Unregisters the specified subclass of `AFHTTPRequestOperation` from the chain of classes consulted when `-requestWithMethod:path:parameters` is called. + + @param operationClass The subclass of `AFHTTPRequestOperation` to register + */ +- (void)unregisterHTTPOperationClass:(Class)operationClass; + +///---------------------------------- +/// @name Managing HTTP Header Values +///---------------------------------- + +/** + Returns the value for the HTTP headers set in request objects created by the HTTP client. + + @param header The HTTP header to return the default value for + + @return The default value for the HTTP header, or `nil` if unspecified + */ +- (NSString *)defaultValueForHeader:(NSString *)header; + +/** + Sets the value for the HTTP headers set in request objects made by the HTTP client. If `nil`, removes the existing value for that header. + + @param header The HTTP header to set a default value for + @param value The value set as default for the specified header, or `nil + */ +- (void)setDefaultHeader:(NSString *)header + value:(NSString *)value; + +/** + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a basic authentication value with Base64-encoded username and password. This overwrites any existing value for this header. + + @param username The HTTP basic auth username + @param password The HTTP basic auth password + */ +- (void)setAuthorizationHeaderWithUsername:(NSString *)username + password:(NSString *)password; + +/** + Sets the "Authorization" HTTP header set in request objects made by the HTTP client to a token-based authentication value, such as an OAuth access token. This overwrites any existing value for this header. + + @param token The authentication token + */ +- (void)setAuthorizationHeaderWithToken:(NSString *)token; + + +/** + Clears any existing value for the "Authorization" HTTP header. + */ +- (void)clearAuthorizationHeader; + +///------------------------------- +/// @name Managing URL Credentials +///------------------------------- + +/** + Set the default URL credential to be set for request operations. + + @param credential The URL credential + */ +- (void)setDefaultCredential:(NSURLCredential *)credential; + +///------------------------------- +/// @name Creating Request Objects +///------------------------------- + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and path. + + If the HTTP method is `GET`, `HEAD`, or `DELETE`, the parameters will be used to construct a url-encoded query string that is appended to the request's URL. Otherwise, the parameters will be encoded according to the value of the `parameterEncoding` property, and set as the request body. + + @param method The HTTP method for the request, such as `GET`, `POST`, `PUT`, or `DELETE`. This parameter must not be `nil`. + @param path The path to be appended to the HTTP client's base URL and used as the request URL. If `nil`, no path will be appended to the base URL. + @param parameters The parameters to be either set as a query string for `GET` requests, or the request HTTP body. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + path:(NSString *)path + parameters:(NSDictionary *)parameters; + +/** + Creates an `NSMutableURLRequest` object with the specified HTTP method and path, and constructs a `multipart/form-data` HTTP body, using the specified parameters and multipart form data block. See http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.2 + + Multipart form requests are automatically streamed, reading files directly from disk along with in-memory data in a single HTTP body. The resulting `NSMutableURLRequest` object has an `HTTPBodyStream` property, so refrain from setting `HTTPBodyStream` or `HTTPBody` on this request object, as it will clear out the multipart form body stream. + + @param method The HTTP method for the request. This parameter must not be `GET` or `HEAD`, or `nil`. + @param path The path to be appended to the HTTP client's base URL and used as the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param block A block that takes a single argument and appends data to the HTTP body. The block argument is an object adopting the `AFMultipartFormData` protocol. This can be used to upload files, encode HTTP body as JSON or XML, or specify multiple values for the same parameter, as one might for array values. + + @return An `NSMutableURLRequest` object + */ +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + path:(NSString *)path + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block; + +///------------------------------- +/// @name Creating HTTP Operations +///------------------------------- + +/** + Creates an `AFHTTPRequestOperation`. + + In order to determine what kind of operation is created, each registered subclass conforming to the `AFHTTPClient` protocol is consulted (in reverse order of when they were specified) to see if it can handle the specific request. The first class to return `YES` when sent a `canProcessRequest:` message is used to generate an operation using `HTTPRequestOperationWithRequest:success:failure:`. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. + @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments:, the created request operation and the `NSError` object describing the network or parsing error that occurred. + */ +- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +///---------------------------------------- +/// @name Managing Enqueued HTTP Operations +///---------------------------------------- + +/** + Enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue. + + @param operation The HTTP request operation to be enqueued. + */ +- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation; + +/** + Cancels all operations in the HTTP client's operation queue whose URLs match the specified HTTP method and path. + + This method only cancels `AFHTTPRequestOperations` whose request URL matches the HTTP client base URL with the path appended. For complete control over the lifecycle of enqueued operations, you can access the `operationQueue` property directly, which allows you to, for instance, cancel operations filtered by a predicate, or simply use `-cancelAllRequests`. Note that the operation queue may include non-HTTP operations, so be sure to check the type before attempting to directly introspect an operation's `request` property. + + @param method The HTTP method to match for the cancelled requests, such as `GET`, `POST`, `PUT`, or `DELETE`. If `nil`, all request operations with URLs matching the path will be cancelled. + @param path The path appended to the HTTP client base URL to match against the cancelled requests. If `nil`, no path will be appended to the base URL. + */ +- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method path:(NSString *)path; + +///--------------------------------------- +/// @name Batching HTTP Request Operations +///--------------------------------------- + +/** + Creates and enqueues an `AFHTTPRequestOperation` to the HTTP client's operation queue for each specified request object into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes. + + Operations are created by passing the specified `NSURLRequest` objects in `requests`, using `-HTTPRequestOperationWithRequest:success:failure:`, with `nil` for both the `success` and `failure` parameters. + + @param urlRequests The `NSURLRequest` objects used to create and enqueue operations. + @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations. + @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations. + */ +- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests + progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock + completionBlock:(void (^)(NSArray *operations))completionBlock; + +/** + Enqueues the specified request operations into a batch. When each request operation finishes, the specified progress block is executed, until all of the request operations have finished, at which point the completion block also executes. + + @param operations The request operations used to be batched and enqueued. + @param progressBlock A block object to be executed upon the completion of each request operation in the batch. This block has no return value and takes two arguments: the number of operations that have already finished execution, and the total number of operations. + @param completionBlock A block object to be executed upon the completion of all of the request operations in the batch. This block has no return value and takes a single argument: the batched request operations. + */ +- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations + progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock + completionBlock:(void (^)(NSArray *operations))completionBlock; + +///--------------------------- +/// @name Making HTTP Requests +///--------------------------- + +/** + Creates an `AFHTTPRequestOperation` with a `GET` request, and enqueues it to the HTTP client's operation queue. + + @param path The path to be appended to the HTTP client's base URL and used as the request URL. + @param parameters The parameters to be encoded and appended as the query string for the request URL. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. + @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (void)getPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates an `AFHTTPRequestOperation` with a `POST` request, and enqueues it to the HTTP client's operation queue. + + @param path The path to be appended to the HTTP client's base URL and used as the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. + @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (void)postPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates an `AFHTTPRequestOperation` with a `PUT` request, and enqueues it to the HTTP client's operation queue. + + @param path The path to be appended to the HTTP client's base URL and used as the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. + @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (void)putPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates an `AFHTTPRequestOperation` with a `DELETE` request, and enqueues it to the HTTP client's operation queue. + + @param path The path to be appended to the HTTP client's base URL and used as the request URL. + @param parameters The parameters to be encoded and appended as the query string for the request URL. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. + @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (void)deletePath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +/** + Creates an `AFHTTPRequestOperation` with a `PATCH` request, and enqueues it to the HTTP client's operation queue. + + @param path The path to be appended to the HTTP client's base URL and used as the request URL. + @param parameters The parameters to be encoded and set in the request HTTP body. + @param success A block object to be executed when the request operation finishes successfully. This block has no return value and takes two arguments: the created request operation and the object created from the response data of request. + @param failure A block object to be executed when the request operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes two arguments: the created request operation and the `NSError` object describing the network or parsing error that occurred. + + @see -HTTPRequestOperationWithRequest:success:failure: + */ +- (void)patchPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## Network Reachability + + The following constants are provided by `AFHTTPClient` as possible network reachability statuses. + + enum { + AFNetworkReachabilityStatusUnknown, + AFNetworkReachabilityStatusNotReachable, + AFNetworkReachabilityStatusReachableViaWWAN, + AFNetworkReachabilityStatusReachableViaWiFi, + } + + `AFNetworkReachabilityStatusUnknown` + The `baseURL` host reachability is not known. + + `AFNetworkReachabilityStatusNotReachable` + The `baseURL` host cannot be reached. + + `AFNetworkReachabilityStatusReachableViaWWAN` + The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. + + `AFNetworkReachabilityStatusReachableViaWiFi` + The `baseURL` host can be reached via a Wi-Fi connection. + + ### Keys for Notification UserInfo Dictionary + + Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. + + `AFNetworkingReachabilityNotificationStatusItem` + A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. + The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. + + ## Parameter Encoding + + The following constants are provided by `AFHTTPClient` as possible methods for serializing parameters into query string or message body values. + + enum { + AFFormURLParameterEncoding, + AFJSONParameterEncoding, + AFPropertyListParameterEncoding, + } + + `AFFormURLParameterEncoding` + Parameters are encoded into field/key pairs in the URL query string for `GET` `HEAD` and `DELETE` requests, and in the message body otherwise. Dictionary keys are sorted with the `caseInsensitiveCompare:` selector of their description, in order to mitigate the possibility of ambiguous query strings being generated non-deterministically. See the warning for the `parameterEncoding` property for additional information. + + `AFJSONParameterEncoding` + Parameters are encoded into JSON in the message body. + + `AFPropertyListParameterEncoding` + Parameters are encoded into a property list in the message body. + */ + +///---------------- +/// @name Functions +///---------------- + +/** + Returns a query string constructed by a set of parameters, using the specified encoding. + + Query strings are constructed by collecting each key-value pair, percent escaping a string representation of the key-value pair, and then joining the pairs with "&". + + If a query string pair has a an `NSArray` for its value, each member of the array will be represented in the format `field[]=value1&field[]value2`. Otherwise, the pair will be formatted as "field=value". String representations of both keys and values are derived using the `-description` method. The constructed query string does not include the ? character used to delimit the query component. + + @param parameters The parameters used to construct the query string + @param encoding The encoding to use in constructing the query string. If you are uncertain of the correct encoding, you should use UTF-8 (`NSUTF8StringEncoding`), which is the encoding designated by RFC 3986 as the correct encoding for use in URLs. + + @return A percent-escaped query string + */ +extern NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding encoding); + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when network reachability changes. + This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. + + @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). + */ +#ifdef _SYSTEMCONFIGURATION_H +extern NSString * const AFNetworkingReachabilityDidChangeNotification; +extern NSString * const AFNetworkingReachabilityNotificationStatusItem; +#endif + +#pragma mark - + +extern NSUInteger const kAFUploadStream3GSuggestedPacketSize; +extern NSTimeInterval const kAFUploadStream3GSuggestedDelay; + +/** + The `AFMultipartFormData` protocol defines the methods supported by the parameter in the block argument of `AFHTTPClient -multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:`. + */ +@protocol AFMultipartFormData + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{generated filename}; name=#{name}"` and `Content-Type: #{generated mimeType}`, followed by the encoded file data and the multipart form boundary. + + The filename and MIME type for this data in the form will be automatically generated, using the last path component of the `fileURL` and system associated MIME type for the `fileURL` extension, respectively. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended, otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param fileURL The URL corresponding to the file whose content will be appended to the form. This parameter must not be `nil`. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The file name to be used in the `Content-Disposition` header. This parameter must not be `nil`. + @param mimeType The declared MIME type of the file data. This parameter must not be `nil`. + @param error If an error occurs, upon return contains an `NSError` object that describes the problem. + + @return `YES` if the file data was successfully appended otherwise `NO`. + */ +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the data from the input stream and the multipart form boundary. + + @param inputStream The input stream to be appended to the form data + @param name The name to be associated with the specified input stream. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified input stream. This parameter must not be `nil`. + @param length The length of the specified input stream in bytes. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(unsigned long long)length + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP header `Content-Disposition: file; filename=#{filename}; name=#{name}"` and `Content-Type: #{mimeType}`, followed by the encoded file data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + @param fileName The filename to be associated with the specified data. This parameter must not be `nil`. + @param mimeType The MIME type of the specified data. (For example, the MIME type for a JPEG image is image/jpeg.) For a list of valid MIME types, see http://www.iana.org/assignments/media-types/. This parameter must not be `nil`. + */ +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType; + +/** + Appends the HTTP headers `Content-Disposition: form-data; name=#{name}"`, followed by the encoded data and the multipart form boundary. + + @param data The data to be encoded and appended to the form data. + @param name The name to be associated with the specified data. This parameter must not be `nil`. + */ + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name; + + +/** + Appends HTTP headers, followed by the encoded data and the multipart form boundary. + + @param headers The HTTP headers to be appended to the form data. + @param body The data to be encoded and appended to the form data. + */ +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body; + +/** + Throttles request bandwidth by limiting the packet size and adding a delay for each chunk read from the upload stream. + + When uploading over a 3G or EDGE connection, requests may fail with "request body stream exhausted". Setting a maximum packet size and delay according to the recommended values (`kAFUploadStream3GSuggestedPacketSize` and `kAFUploadStream3GSuggestedDelay`) lowers the risk of the input stream exceeding its allocated bandwidth. Unfortunately, as of iOS 6, there is no definite way to distinguish between a 3G, EDGE, or LTE connection. As such, it is not recommended that you throttle bandwidth based solely on network reachability. Instead, you should consider checking for the "request body stream exhausted" in a failure block, and then retrying the request with throttled bandwidth. + + @param numberOfBytes Maximum packet size, in number of bytes. The default packet size for an input stream is 32kb. + @param delay Duration of delay each time a packet is read. By default, no delay is set. + */ +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay; + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m new file mode 100644 index 00000000000..43b74a154de --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPClient.m @@ -0,0 +1,1396 @@ +// AFHTTPClient.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import "AFHTTPClient.h" +#import "AFHTTPRequestOperation.h" + +#import + +#ifdef _SYSTEMCONFIGURATION_H +#import +#import +#import +#import +#import +#endif + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import +#endif + +#ifdef _SYSTEMCONFIGURATION_H +NSString * const AFNetworkingReachabilityDidChangeNotification = @"com.alamofire.networking.reachability.change"; +NSString * const AFNetworkingReachabilityNotificationStatusItem = @"AFNetworkingReachabilityNotificationStatusItem"; + +typedef SCNetworkReachabilityRef AFNetworkReachabilityRef; +typedef void (^AFNetworkReachabilityStatusBlock)(AFNetworkReachabilityStatus status); +#else +typedef id AFNetworkReachabilityRef; +#endif + +typedef void (^AFCompletionBlock)(void); + +static NSString * AFBase64EncodedStringFromString(NSString *string) { + NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]]; + NSUInteger length = [data length]; + NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4]; + + uint8_t *input = (uint8_t *)[data bytes]; + uint8_t *output = (uint8_t *)[mutableData mutableBytes]; + + for (NSUInteger i = 0; i < length; i += 3) { + NSUInteger value = 0; + for (NSUInteger j = i; j < (i + 3); j++) { + value <<= 8; + if (j < length) { + value |= (0xFF & input[j]); + } + } + + static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + NSUInteger idx = (i / 3) * 4; + output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F]; + output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F]; + output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6) & 0x3F] : '='; + output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0) & 0x3F] : '='; + } + + return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding]; +} + +static NSString * const kAFCharactersToBeEscapedInQueryString = @":/?&=;+!@#$()',*"; + +static NSString * AFPercentEscapedQueryStringKeyFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { + static NSString * const kAFCharactersToLeaveUnescapedInQueryStringPairKey = @"[]."; + + return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, (__bridge CFStringRef)kAFCharactersToLeaveUnescapedInQueryStringPairKey, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); +} + +static NSString * AFPercentEscapedQueryStringValueFromStringWithEncoding(NSString *string, NSStringEncoding encoding) { + return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)string, NULL, (__bridge CFStringRef)kAFCharactersToBeEscapedInQueryString, CFStringConvertNSStringEncodingToEncoding(encoding)); +} + +#pragma mark - + +@interface AFQueryStringPair : NSObject +@property (readwrite, nonatomic, strong) id field; +@property (readwrite, nonatomic, strong) id value; + +- (id)initWithField:(id)field value:(id)value; + +- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding; +@end + +@implementation AFQueryStringPair +@synthesize field = _field; +@synthesize value = _value; + +- (id)initWithField:(id)field value:(id)value { + self = [super init]; + if (!self) { + return nil; + } + + self.field = field; + self.value = value; + + return self; +} + +- (NSString *)URLEncodedStringValueWithEncoding:(NSStringEncoding)stringEncoding { + if (!self.value || [self.value isEqual:[NSNull null]]) { + return AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding); + } else { + return [NSString stringWithFormat:@"%@=%@", AFPercentEscapedQueryStringKeyFromStringWithEncoding([self.field description], stringEncoding), AFPercentEscapedQueryStringValueFromStringWithEncoding([self.value description], stringEncoding)]; + } +} + +@end + +#pragma mark - + +extern NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary); +extern NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value); + +NSString * AFQueryStringFromParametersWithEncoding(NSDictionary *parameters, NSStringEncoding stringEncoding) { + NSMutableArray *mutablePairs = [NSMutableArray array]; + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + [mutablePairs addObject:[pair URLEncodedStringValueWithEncoding:stringEncoding]]; + } + + return [mutablePairs componentsJoinedByString:@"&"]; +} + +NSArray * AFQueryStringPairsFromDictionary(NSDictionary *dictionary) { + return AFQueryStringPairsFromKeyAndValue(nil, dictionary); +} + +NSArray * AFQueryStringPairsFromKeyAndValue(NSString *key, id value) { + NSMutableArray *mutableQueryStringComponents = [NSMutableArray array]; + + if ([value isKindOfClass:[NSDictionary class]]) { + NSDictionary *dictionary = value; + // Sort dictionary keys to ensure consistent ordering in query string, which is important when deserializing potentially ambiguous sequences, such as an array of dictionaries + NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"description" ascending:YES selector:@selector(caseInsensitiveCompare:)]; + for (id nestedKey in [dictionary.allKeys sortedArrayUsingDescriptors:@[ sortDescriptor ]]) { + id nestedValue = [dictionary objectForKey:nestedKey]; + if (nestedValue) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue((key ? [NSString stringWithFormat:@"%@[%@]", key, nestedKey] : nestedKey), nestedValue)]; + } + } + } else if ([value isKindOfClass:[NSArray class]]) { + NSArray *array = value; + for (id nestedValue in array) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue([NSString stringWithFormat:@"%@[]", key], nestedValue)]; + } + } else if ([value isKindOfClass:[NSSet class]]) { + NSSet *set = value; + for (id obj in set) { + [mutableQueryStringComponents addObjectsFromArray:AFQueryStringPairsFromKeyAndValue(key, obj)]; + } + } else { + [mutableQueryStringComponents addObject:[[AFQueryStringPair alloc] initWithField:key value:value]]; + } + + return mutableQueryStringComponents; +} + +@interface AFStreamingMultipartFormData : NSObject +- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding; + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData; +@end + +#pragma mark - + +@interface AFHTTPClient () +@property (readwrite, nonatomic, strong) NSURL *baseURL; +@property (readwrite, nonatomic, strong) NSMutableArray *registeredHTTPOperationClassNames; +@property (readwrite, nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (readwrite, nonatomic, strong) NSURLCredential *defaultCredential; +@property (readwrite, nonatomic, strong) NSOperationQueue *operationQueue; +#ifdef _SYSTEMCONFIGURATION_H +@property (readwrite, nonatomic, assign) AFNetworkReachabilityRef networkReachability; +@property (readwrite, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; +@property (readwrite, nonatomic, copy) AFNetworkReachabilityStatusBlock networkReachabilityStatusBlock; +#endif + +#ifdef _SYSTEMCONFIGURATION_H +- (void)startMonitoringNetworkReachability; +- (void)stopMonitoringNetworkReachability; +#endif +@end + +@implementation AFHTTPClient +@synthesize baseURL = _baseURL; +@synthesize stringEncoding = _stringEncoding; +@synthesize parameterEncoding = _parameterEncoding; +@synthesize registeredHTTPOperationClassNames = _registeredHTTPOperationClassNames; +@synthesize defaultHeaders = _defaultHeaders; +@synthesize defaultCredential = _defaultCredential; +@synthesize operationQueue = _operationQueue; +#ifdef _SYSTEMCONFIGURATION_H +@synthesize networkReachability = _networkReachability; +@synthesize networkReachabilityStatus = _networkReachabilityStatus; +@synthesize networkReachabilityStatusBlock = _networkReachabilityStatusBlock; +#endif +@synthesize defaultSSLPinningMode = _defaultSSLPinningMode; +@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate; + ++ (instancetype)clientWithBaseURL:(NSURL *)url { + return [[self alloc] initWithBaseURL:url]; +} + +- (id)init { + @throw [NSException exceptionWithName:NSInternalInconsistencyException reason:[NSString stringWithFormat:@"%@ Failed to call designated initializer. Invoke `initWithBaseURL:` instead.", NSStringFromClass([self class])] userInfo:nil]; +} + +- (id)initWithBaseURL:(NSURL *)url { + NSParameterAssert(url); + + self = [super init]; + if (!self) { + return nil; + } + + // Ensure terminal slash for baseURL path, so that NSURL +URLWithString:relativeToURL: works as expected + if ([[url path] length] > 0 && ![[url absoluteString] hasSuffix:@"/"]) { + url = [url URLByAppendingPathComponent:@""]; + } + + self.baseURL = url; + + self.stringEncoding = NSUTF8StringEncoding; + self.parameterEncoding = AFFormURLParameterEncoding; + + self.registeredHTTPOperationClassNames = [NSMutableArray array]; + + self.defaultHeaders = [NSMutableDictionary dictionary]; + + // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 + NSMutableArray *acceptLanguagesComponents = [NSMutableArray array]; + [[NSLocale preferredLanguages] enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + float q = 1.0f - (idx * 0.1f); + [acceptLanguagesComponents addObject:[NSString stringWithFormat:@"%@;q=%0.1g", obj, q]]; + *stop = q <= 0.5f; + }]; + [self setDefaultHeader:@"Accept-Language" value:[acceptLanguagesComponents componentsJoinedByString:@", "]]; + + NSString *userAgent = nil; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43 + userAgent = [NSString stringWithFormat:@"%@/%@ (%@; iOS %@; Scale/%0.2f)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], (__bridge id)CFBundleGetValueForInfoDictionaryKey(CFBundleGetMainBundle(), kCFBundleVersionKey) ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] ? [[UIScreen mainScreen] scale] : 1.0f)]; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + userAgent = [NSString stringWithFormat:@"%@/%@ (Mac OS X %@)", [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleExecutableKey] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleIdentifierKey], [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"] ?: [[[NSBundle mainBundle] infoDictionary] objectForKey:(__bridge NSString *)kCFBundleVersionKey], [[NSProcessInfo processInfo] operatingSystemVersionString]]; +#endif +#pragma clang diagnostic pop + if (userAgent) { + if (![userAgent canBeConvertedToEncoding:NSASCIIStringEncoding]) { + NSMutableString *mutableUserAgent = [userAgent mutableCopy]; + CFStringTransform((__bridge CFMutableStringRef)(mutableUserAgent), NULL, kCFStringTransformToLatin, false); + userAgent = mutableUserAgent; + } + [self setDefaultHeader:@"User-Agent" value:userAgent]; + } + +#ifdef _SYSTEMCONFIGURATION_H + self.networkReachabilityStatus = AFNetworkReachabilityStatusUnknown; + [self startMonitoringNetworkReachability]; +#endif + + self.operationQueue = [[NSOperationQueue alloc] init]; + [self.operationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; + + // #ifdef included for backwards-compatibility +#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ + self.allowsInvalidSSLCertificate = YES; +#endif + + return self; +} + +- (void)dealloc { +#ifdef _SYSTEMCONFIGURATION_H + [self stopMonitoringNetworkReachability]; +#endif +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, baseURL: %@, defaultHeaders: %@, registeredOperationClasses: %@, operationQueue: %@>", NSStringFromClass([self class]), self, [self.baseURL absoluteString], self.defaultHeaders, self.registeredHTTPOperationClassNames, self.operationQueue]; +} + +#pragma mark - + +#ifdef _SYSTEMCONFIGURATION_H +static BOOL AFURLHostIsIPAddress(NSURL *url) { + struct sockaddr_in sa_in; + struct sockaddr_in6 sa_in6; + + return [url host] && (inet_pton(AF_INET, [[url host] UTF8String], &sa_in) == 1 || inet_pton(AF_INET6, [[url host] UTF8String], &sa_in6) == 1); +} + +static AFNetworkReachabilityStatus AFNetworkReachabilityStatusForFlags(SCNetworkReachabilityFlags flags) { + BOOL isReachable = ((flags & kSCNetworkReachabilityFlagsReachable) != 0); + BOOL needsConnection = ((flags & kSCNetworkReachabilityFlagsConnectionRequired) != 0); + BOOL canConnectionAutomatically = (((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) || ((flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0)); + BOOL canConnectWithoutUserInteraction = (canConnectionAutomatically && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0); + BOOL isNetworkReachable = (isReachable && (!needsConnection || canConnectWithoutUserInteraction)); + + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusUnknown; + if (isNetworkReachable == NO) { + status = AFNetworkReachabilityStatusNotReachable; + } +#if TARGET_OS_IPHONE + else if ((flags & kSCNetworkReachabilityFlagsIsWWAN) != 0) { + status = AFNetworkReachabilityStatusReachableViaWWAN; + } +#endif + else { + status = AFNetworkReachabilityStatusReachableViaWiFi; + } + + return status; +} + +static void AFNetworkReachabilityCallback(SCNetworkReachabilityRef __unused target, SCNetworkReachabilityFlags flags, void *info) { + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + AFNetworkReachabilityStatusBlock block = (__bridge AFNetworkReachabilityStatusBlock)info; + if (block) { + block(status); + } + + dispatch_async(dispatch_get_main_queue(), ^{ + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + [notificationCenter postNotificationName:AFNetworkingReachabilityDidChangeNotification object:nil userInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:status] forKey:AFNetworkingReachabilityNotificationStatusItem]]; + }); +} + +static const void * AFNetworkReachabilityRetainCallback(const void *info) { + return Block_copy(info); +} + +static void AFNetworkReachabilityReleaseCallback(const void *info) { + if (info) { + Block_release(info); + } +} + +- (void)startMonitoringNetworkReachability { + [self stopMonitoringNetworkReachability]; + + if (!self.baseURL) { + return; + } + + self.networkReachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [[self.baseURL host] UTF8String]); + + if (!self.networkReachability) { + return; + } + + __weak __typeof(&*self)weakSelf = self; + AFNetworkReachabilityStatusBlock callback = ^(AFNetworkReachabilityStatus status) { + __strong __typeof(&*weakSelf)strongSelf = weakSelf; + if (!strongSelf) { + return; + } + + strongSelf.networkReachabilityStatus = status; + if (strongSelf.networkReachabilityStatusBlock) { + strongSelf.networkReachabilityStatusBlock(status); + } + }; + + SCNetworkReachabilityContext context = {0, (__bridge void *)callback, AFNetworkReachabilityRetainCallback, AFNetworkReachabilityReleaseCallback, NULL}; + SCNetworkReachabilitySetCallback(self.networkReachability, AFNetworkReachabilityCallback, &context); + + /* Network reachability monitoring does not establish a baseline for IP addresses as it does for hostnames, so if the base URL host is an IP address, the initial reachability callback is manually triggered. + */ + if (AFURLHostIsIPAddress(self.baseURL)) { + SCNetworkReachabilityFlags flags; + SCNetworkReachabilityGetFlags(self.networkReachability, &flags); + dispatch_async(dispatch_get_main_queue(), ^{ + AFNetworkReachabilityStatus status = AFNetworkReachabilityStatusForFlags(flags); + callback(status); + }); + } + + SCNetworkReachabilityScheduleWithRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); +} + +- (void)stopMonitoringNetworkReachability { + if (self.networkReachability) { + SCNetworkReachabilityUnscheduleFromRunLoop(self.networkReachability, CFRunLoopGetMain(), kCFRunLoopCommonModes); + + CFRelease(_networkReachability); + _networkReachability = NULL; + } +} + +- (void)setReachabilityStatusChangeBlock:(void (^)(AFNetworkReachabilityStatus status))block { + self.networkReachabilityStatusBlock = block; +} +#endif + +#pragma mark - + +- (BOOL)registerHTTPOperationClass:(Class)operationClass { + if (![operationClass isSubclassOfClass:[AFHTTPRequestOperation class]]) { + return NO; + } + + NSString *className = NSStringFromClass(operationClass); + [self.registeredHTTPOperationClassNames removeObject:className]; + [self.registeredHTTPOperationClassNames insertObject:className atIndex:0]; + + return YES; +} + +- (void)unregisterHTTPOperationClass:(Class)operationClass { + NSString *className = NSStringFromClass(operationClass); + [self.registeredHTTPOperationClassNames removeObject:className]; +} + +#pragma mark - + +- (NSString *)defaultValueForHeader:(NSString *)header { + return [self.defaultHeaders valueForKey:header]; +} + +- (void)setDefaultHeader:(NSString *)header value:(NSString *)value { + [self.defaultHeaders setValue:value forKey:header]; +} + +- (void)setAuthorizationHeaderWithUsername:(NSString *)username password:(NSString *)password { + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Basic %@", AFBase64EncodedStringFromString(basicAuthCredentials)]]; +} + +- (void)setAuthorizationHeaderWithToken:(NSString *)token { + [self setDefaultHeader:@"Authorization" value:[NSString stringWithFormat:@"Token token=\"%@\"", token]]; +} + +- (void)clearAuthorizationHeader { + [self.defaultHeaders removeObjectForKey:@"Authorization"]; +} + +#pragma mark - + +- (NSMutableURLRequest *)requestWithMethod:(NSString *)method + path:(NSString *)path + parameters:(NSDictionary *)parameters +{ + NSParameterAssert(method); + + if (!path) { + path = @""; + } + + NSURL *url = [NSURL URLWithString:path relativeToURL:self.baseURL]; + NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url]; + [request setHTTPMethod:method]; + [request setAllHTTPHeaderFields:self.defaultHeaders]; + + if (parameters) { + if ([method isEqualToString:@"GET"] || [method isEqualToString:@"HEAD"] || [method isEqualToString:@"DELETE"]) { + url = [NSURL URLWithString:[[url absoluteString] stringByAppendingFormat:[path rangeOfString:@"?"].location == NSNotFound ? @"?%@" : @"&%@", AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding)]]; + [request setURL:url]; + } else { + NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding)); + NSError *error = nil; + + switch (self.parameterEncoding) { + case AFFormURLParameterEncoding:; + [request setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [request setHTTPBody:[AFQueryStringFromParametersWithEncoding(parameters, self.stringEncoding) dataUsingEncoding:self.stringEncoding]]; + break; + case AFJSONParameterEncoding:; + [request setValue:[NSString stringWithFormat:@"application/json; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [request setHTTPBody:[NSJSONSerialization dataWithJSONObject:parameters options:(NSJSONWritingOptions)0 error:&error]]; + break; + case AFPropertyListParameterEncoding:; + [request setValue:[NSString stringWithFormat:@"application/x-plist; charset=%@", charset] forHTTPHeaderField:@"Content-Type"]; + [request setHTTPBody:[NSPropertyListSerialization dataWithPropertyList:parameters format:NSPropertyListXMLFormat_v1_0 options:0 error:&error]]; + break; + } + + if (error) { + NSLog(@"%@ %@: %@", [self class], NSStringFromSelector(_cmd), error); + } + } + } + + return request; +} + +- (NSMutableURLRequest *)multipartFormRequestWithMethod:(NSString *)method + path:(NSString *)path + parameters:(NSDictionary *)parameters + constructingBodyWithBlock:(void (^)(id formData))block +{ + NSParameterAssert(method); + NSParameterAssert(![method isEqualToString:@"GET"] && ![method isEqualToString:@"HEAD"]); + + NSMutableURLRequest *request = [self requestWithMethod:method path:path parameters:nil]; + + __block AFStreamingMultipartFormData *formData = [[AFStreamingMultipartFormData alloc] initWithURLRequest:request stringEncoding:self.stringEncoding]; + + if (parameters) { + for (AFQueryStringPair *pair in AFQueryStringPairsFromDictionary(parameters)) { + NSData *data = nil; + if ([pair.value isKindOfClass:[NSData class]]) { + data = pair.value; + } else if ([pair.value isEqual:[NSNull null]]) { + data = [NSData data]; + } else { + data = [[pair.value description] dataUsingEncoding:self.stringEncoding]; + } + + if (data) { + [formData appendPartWithFormData:data name:[pair.field description]]; + } + } + } + + if (block) { + block(formData); + } + + return [formData requestByFinalizingMultipartFormData]; +} + +- (AFHTTPRequestOperation *)HTTPRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + AFHTTPRequestOperation *operation = nil; + + for (NSString *className in self.registeredHTTPOperationClassNames) { + Class operationClass = NSClassFromString(className); + if (operationClass && [operationClass canProcessRequest:urlRequest]) { + operation = [(AFHTTPRequestOperation *)[operationClass alloc] initWithRequest:urlRequest]; + break; + } + } + + if (!operation) { + operation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; + } + + [operation setCompletionBlockWithSuccess:success failure:failure]; + + operation.credential = self.defaultCredential; + operation.SSLPinningMode = self.defaultSSLPinningMode; + operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate; + + return operation; +} + +#pragma mark - + +- (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *)operation { + [self.operationQueue addOperation:operation]; +} + +- (void)cancelAllHTTPOperationsWithMethod:(NSString *)method + path:(NSString *)path +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + NSString *pathToBeMatched = [[[self requestWithMethod:(method ?: @"GET") path:path parameters:nil] URL] path]; +#pragma clang diagnostic pop + + for (NSOperation *operation in [self.operationQueue operations]) { + if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) { + continue; + } + + BOOL hasMatchingMethod = !method || [method isEqualToString:[[(AFHTTPRequestOperation *)operation request] HTTPMethod]]; + BOOL hasMatchingPath = [[[[(AFHTTPRequestOperation *)operation request] URL] path] isEqual:pathToBeMatched]; + + if (hasMatchingMethod && hasMatchingPath) { + [operation cancel]; + } + } +} + +- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests + progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock + completionBlock:(void (^)(NSArray *operations))completionBlock +{ + NSMutableArray *mutableOperations = [NSMutableArray array]; + for (NSURLRequest *request in urlRequests) { + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:nil failure:nil]; + [mutableOperations addObject:operation]; + } + + [self enqueueBatchOfHTTPRequestOperations:mutableOperations progressBlock:progressBlock completionBlock:completionBlock]; +} + +- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations + progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock + completionBlock:(void (^)(NSArray *operations))completionBlock +{ + __block dispatch_group_t dispatchGroup = dispatch_group_create(); + NSBlockOperation *batchedOperation = [NSBlockOperation blockOperationWithBlock:^{ + dispatch_group_notify(dispatchGroup, dispatch_get_main_queue(), ^{ + if (completionBlock) { + completionBlock(operations); + } + }); +#if !OS_OBJECT_USE_OBJC + dispatch_release(dispatchGroup); +#endif + }]; + + for (AFHTTPRequestOperation *operation in operations) { + AFCompletionBlock originalCompletionBlock = [operation.completionBlock copy]; + __weak __typeof(&*operation)weakOperation = operation; + operation.completionBlock = ^{ + __strong __typeof(&*weakOperation)strongOperation = weakOperation; +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_queue_t queue = strongOperation.successCallbackQueue ?: dispatch_get_main_queue(); +#pragma clang diagnostic pop + dispatch_group_async(dispatchGroup, queue, ^{ + if (originalCompletionBlock) { + originalCompletionBlock(); + } + + NSUInteger numberOfFinishedOperations = [[operations indexesOfObjectsPassingTest:^BOOL(id op, NSUInteger __unused idx, BOOL __unused *stop) { + return [op isFinished]; + }] count]; + + if (progressBlock) { + progressBlock(numberOfFinishedOperations, [operations count]); + } + + dispatch_group_leave(dispatchGroup); + }); + }; + + dispatch_group_enter(dispatchGroup); + [batchedOperation addDependency:operation]; + } + [self.operationQueue addOperations:operations waitUntilFinished:NO]; + [self.operationQueue addOperation:batchedOperation]; +} + +#pragma mark - + +- (void)getPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSURLRequest *request = [self requestWithMethod:@"GET" path:path parameters:parameters]; + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperation:operation]; +} + +- (void)postPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSURLRequest *request = [self requestWithMethod:@"POST" path:path parameters:parameters]; + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperation:operation]; +} + +- (void)putPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSURLRequest *request = [self requestWithMethod:@"PUT" path:path parameters:parameters]; + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperation:operation]; +} + +- (void)deletePath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSURLRequest *request = [self requestWithMethod:@"DELETE" path:path parameters:parameters]; + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperation:operation]; +} + +- (void)patchPath:(NSString *)path + parameters:(NSDictionary *)parameters + success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + NSURLRequest *request = [self requestWithMethod:@"PATCH" path:path parameters:parameters]; + AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure]; + [self enqueueHTTPRequestOperation:operation]; +} + +#pragma mark - NSCoding + +- (id)initWithCoder:(NSCoder *)aDecoder { + NSURL *baseURL = [aDecoder decodeObjectForKey:@"baseURL"]; + + self = [self initWithBaseURL:baseURL]; + if (!self) { + return nil; + } + + self.stringEncoding = [aDecoder decodeIntegerForKey:@"stringEncoding"]; + self.parameterEncoding = (AFHTTPClientParameterEncoding) [aDecoder decodeIntegerForKey:@"parameterEncoding"]; + self.registeredHTTPOperationClassNames = [aDecoder decodeObjectForKey:@"registeredHTTPOperationClassNames"]; + self.defaultHeaders = [aDecoder decodeObjectForKey:@"defaultHeaders"]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [aCoder encodeObject:self.baseURL forKey:@"baseURL"]; + [aCoder encodeInteger:(NSInteger)self.stringEncoding forKey:@"stringEncoding"]; + [aCoder encodeInteger:self.parameterEncoding forKey:@"parameterEncoding"]; + [aCoder encodeObject:self.registeredHTTPOperationClassNames forKey:@"registeredHTTPOperationClassNames"]; + [aCoder encodeObject:self.defaultHeaders forKey:@"defaultHeaders"]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPClient *HTTPClient = [[[self class] allocWithZone:zone] initWithBaseURL:self.baseURL]; + + HTTPClient.stringEncoding = self.stringEncoding; + HTTPClient.parameterEncoding = self.parameterEncoding; + HTTPClient.registeredHTTPOperationClassNames = [self.registeredHTTPOperationClassNames mutableCopyWithZone:zone]; + HTTPClient.defaultHeaders = [self.defaultHeaders mutableCopyWithZone:zone]; +#ifdef _SYSTEMCONFIGURATION_H + HTTPClient.networkReachabilityStatusBlock = self.networkReachabilityStatusBlock; +#endif + return HTTPClient; +} + +@end + +#pragma mark - + +static NSString * const kAFMultipartFormBoundary = @"Boundary+0xAbCdEfGbOuNdArY"; + +static NSString * const kAFMultipartFormCRLF = @"\r\n"; + +static NSInteger const kAFStreamToStreamBufferSize = 1024 * 1024; //1 meg default + +static inline NSString * AFMultipartFormInitialBoundary() { + return [NSString stringWithFormat:@"--%@%@", kAFMultipartFormBoundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormEncapsulationBoundary() { + return [NSString stringWithFormat:@"%@--%@%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFMultipartFormFinalBoundary() { + return [NSString stringWithFormat:@"%@--%@--%@", kAFMultipartFormCRLF, kAFMultipartFormBoundary, kAFMultipartFormCRLF]; +} + +static inline NSString * AFContentTypeForPathExtension(NSString *extension) { +#ifdef __UTTYPE__ + NSString *UTI = (__bridge_transfer NSString *)UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef)extension, NULL); + NSString *contentType = (__bridge_transfer NSString *)UTTypeCopyPreferredTagWithClass((__bridge CFStringRef)UTI, kUTTagClassMIMEType); + if (!contentType) { + return @"application/octet-stream"; + } else { + return contentType; + } +#else + return @"application/octet-stream"; +#endif +} + +NSUInteger const kAFUploadStream3GSuggestedPacketSize = 1024 * 16; +NSTimeInterval const kAFUploadStream3GSuggestedDelay = 0.2; + +@interface AFHTTPBodyPart : NSObject +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSDictionary *headers; +@property (nonatomic, strong) id body; +@property (nonatomic, assign) unsigned long long bodyContentLength; +@property (nonatomic, strong) NSInputStream *inputStream; + +@property (nonatomic, assign) BOOL hasInitialBoundary; +@property (nonatomic, assign) BOOL hasFinalBoundary; + +@property (nonatomic, readonly, getter = hasBytesAvailable) BOOL bytesAvailable; +@property (nonatomic, readonly) unsigned long long contentLength; + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@interface AFMultipartBodyStream : NSInputStream +@property (nonatomic, assign) NSUInteger numberOfBytesInPacket; +@property (nonatomic, assign) NSTimeInterval delay; +@property (nonatomic, strong) NSInputStream *inputStream; +@property (nonatomic, readonly) unsigned long long contentLength; +@property (nonatomic, readonly, getter = isEmpty) BOOL empty; + +- (id)initWithStringEncoding:(NSStringEncoding)encoding; +- (void)setInitialAndFinalBoundaries; +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart; +@end + +#pragma mark - + +@interface AFStreamingMultipartFormData () +@property (readwrite, nonatomic, copy) NSMutableURLRequest *request; +@property (readwrite, nonatomic, strong) AFMultipartBodyStream *bodyStream; +@property (readwrite, nonatomic, assign) NSStringEncoding stringEncoding; +@end + +@implementation AFStreamingMultipartFormData +@synthesize request = _request; +@synthesize bodyStream = _bodyStream; +@synthesize stringEncoding = _stringEncoding; + +- (id)initWithURLRequest:(NSMutableURLRequest *)urlRequest + stringEncoding:(NSStringEncoding)encoding +{ + self = [super init]; + if (!self) { + return nil; + } + + self.request = urlRequest; + self.stringEncoding = encoding; + self.bodyStream = [[AFMultipartBodyStream alloc] initWithStringEncoding:encoding]; + + return self; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + + NSString *fileName = [fileURL lastPathComponent]; + NSString *mimeType = AFContentTypeForPathExtension([fileURL pathExtension]); + + return [self appendPartWithFileURL:fileURL name:name fileName:fileName mimeType:mimeType error:error]; +} + +- (BOOL)appendPartWithFileURL:(NSURL *)fileURL + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType + error:(NSError * __autoreleasing *)error +{ + NSParameterAssert(fileURL); + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + if (![fileURL isFileURL]) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"Expected URL to be a file URL", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey]; + if (error != NULL) { + *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } else if ([fileURL checkResourceIsReachableAndReturnError:error] == NO) { + NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedStringFromTable(@"File URL not reachable.", @"AFNetworking", nil) forKey:NSLocalizedFailureReasonErrorKey]; + if (error != NULL) { + *error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadURL userInfo:userInfo]; + } + + return NO; + } + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.body = fileURL; + + NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[fileURL path] error:nil]; + bodyPart.bodyContentLength = [[fileAttributes objectForKey:NSFileSize] unsignedLongLongValue]; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; + + return YES; +} + + +- (void)appendPartWithInputStream:(NSInputStream *)inputStream + name:(NSString *)name + fileName:(NSString *)fileName + length:(unsigned long long)length + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = mutableHeaders; + bodyPart.body = inputStream; + + bodyPart.bodyContentLength = length; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)appendPartWithFileData:(NSData *)data + name:(NSString *)name + fileName:(NSString *)fileName + mimeType:(NSString *)mimeType +{ + NSParameterAssert(name); + NSParameterAssert(fileName); + NSParameterAssert(mimeType); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"; filename=\"%@\"", name, fileName] forKey:@"Content-Disposition"]; + [mutableHeaders setValue:mimeType forKey:@"Content-Type"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithFormData:(NSData *)data + name:(NSString *)name +{ + NSParameterAssert(name); + + NSMutableDictionary *mutableHeaders = [NSMutableDictionary dictionary]; + [mutableHeaders setValue:[NSString stringWithFormat:@"form-data; name=\"%@\"", name] forKey:@"Content-Disposition"]; + + [self appendPartWithHeaders:mutableHeaders body:data]; +} + +- (void)appendPartWithHeaders:(NSDictionary *)headers + body:(NSData *)body +{ + NSParameterAssert(body); + + AFHTTPBodyPart *bodyPart = [[AFHTTPBodyPart alloc] init]; + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = headers; + bodyPart.bodyContentLength = [body length]; + bodyPart.body = body; + + [self.bodyStream appendHTTPBodyPart:bodyPart]; +} + +- (void)throttleBandwidthWithPacketSize:(NSUInteger)numberOfBytes + delay:(NSTimeInterval)delay +{ + self.bodyStream.numberOfBytesInPacket = numberOfBytes; + self.bodyStream.delay = delay; +} + +- (NSMutableURLRequest *)requestByFinalizingMultipartFormData { + if ([self.bodyStream isEmpty]) { + return self.request; + } + + // Reset the initial and final boundaries to ensure correct Content-Length + [self.bodyStream setInitialAndFinalBoundaries]; + + [self.request setValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", kAFMultipartFormBoundary] forHTTPHeaderField:@"Content-Type"]; + [self.request setValue:[NSString stringWithFormat:@"%llu", [self.bodyStream contentLength]] forHTTPHeaderField:@"Content-Length"]; + [self.request setHTTPBodyStream:self.bodyStream]; + + return self.request; +} + +@end + +#pragma mark - + +@interface AFMultipartBodyStream () +@property (nonatomic, assign) NSStreamStatus streamStatus; +@property (nonatomic, strong) NSError *streamError; +@property (nonatomic, assign) NSStringEncoding stringEncoding; +@property (nonatomic, strong) NSMutableArray *HTTPBodyParts; +@property (nonatomic, strong) NSEnumerator *HTTPBodyPartEnumerator; +@property (nonatomic, strong) AFHTTPBodyPart *currentHTTPBodyPart; +@property (nonatomic, strong) NSOutputStream *outputStream; +@property (nonatomic, strong) NSMutableData *buffer; +@end + +@implementation AFMultipartBodyStream +@synthesize streamStatus = _streamStatus; +@synthesize streamError = _streamError; +@synthesize stringEncoding = _stringEncoding; +@synthesize HTTPBodyParts = _HTTPBodyParts; +@synthesize HTTPBodyPartEnumerator = _HTTPBodyPartEnumerator; +@synthesize currentHTTPBodyPart = _currentHTTPBodyPart; +@synthesize inputStream = _inputStream; +@synthesize outputStream = _outputStream; +@synthesize buffer = _buffer; +@synthesize numberOfBytesInPacket = _numberOfBytesInPacket; +@synthesize delay = _delay; + +- (id)initWithStringEncoding:(NSStringEncoding)encoding { + self = [super init]; + if (!self) { + return nil; + } + + self.stringEncoding = encoding; + self.HTTPBodyParts = [NSMutableArray array]; + self.numberOfBytesInPacket = NSIntegerMax; + + return self; +} + +- (void)setInitialAndFinalBoundaries { + if ([self.HTTPBodyParts count] > 0) { + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + bodyPart.hasInitialBoundary = NO; + bodyPart.hasFinalBoundary = NO; + } + + [[self.HTTPBodyParts objectAtIndex:0] setHasInitialBoundary:YES]; + [[self.HTTPBodyParts lastObject] setHasFinalBoundary:YES]; + } +} + +- (void)appendHTTPBodyPart:(AFHTTPBodyPart *)bodyPart { + [self.HTTPBodyParts addObject:bodyPart]; +} + +- (BOOL)isEmpty { + return [self.HTTPBodyParts count] == 0; +} + +#pragma mark - NSInputStream + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + if ([self streamStatus] == NSStreamStatusClosed) { + return 0; + } + + NSInteger totalNumberOfBytesRead = 0; + + while ((NSUInteger)totalNumberOfBytesRead < MIN(length, self.numberOfBytesInPacket)) { + if (!self.currentHTTPBodyPart || ![self.currentHTTPBodyPart hasBytesAvailable]) { + if (!(self.currentHTTPBodyPart = [self.HTTPBodyPartEnumerator nextObject])) { + break; + } + } else { + NSUInteger maxLength = length - (NSUInteger)totalNumberOfBytesRead; + NSInteger numberOfBytesRead = [self.currentHTTPBodyPart read:&buffer[totalNumberOfBytesRead] maxLength:maxLength]; + if (numberOfBytesRead == -1) { + self.streamError = self.currentHTTPBodyPart.inputStream.streamError; + break; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if (self.delay > 0.0f) { + [NSThread sleepForTimeInterval:self.delay]; + } + } + } + } + + return totalNumberOfBytesRead; +} + +- (BOOL)getBuffer:(__unused uint8_t **)buffer + length:(__unused NSUInteger *)len +{ + return NO; +} + +- (BOOL)hasBytesAvailable { + return [self streamStatus] == NSStreamStatusOpen; +} + +#pragma mark - NSStream + +- (void)open { + if (self.streamStatus == NSStreamStatusOpen) { + return; + } + + self.streamStatus = NSStreamStatusOpen; + + [self setInitialAndFinalBoundaries]; + self.HTTPBodyPartEnumerator = [self.HTTPBodyParts objectEnumerator]; +} + +- (void)close { + self.streamStatus = NSStreamStatusClosed; +} + +- (id)propertyForKey:(__unused NSString *)key { + return nil; +} + +- (BOOL)setProperty:(__unused id)property + forKey:(__unused NSString *)key +{ + return NO; +} + +- (void)scheduleInRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (void)removeFromRunLoop:(__unused NSRunLoop *)aRunLoop + forMode:(__unused NSString *)mode +{} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + length += [bodyPart contentLength]; + } + + return length; +} + +#pragma mark - Undocumented CFReadStream Bridged Methods + +- (void)_scheduleInCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (void)_unscheduleFromCFRunLoop:(__unused CFRunLoopRef)aRunLoop + forMode:(__unused CFStringRef)aMode +{} + +- (BOOL)_setCFClientFlags:(__unused CFOptionFlags)inFlags + callback:(__unused CFReadStreamClientCallBack)inCallback + context:(__unused CFStreamClientContext *)inContext { + return NO; +} + +#pragma mark - NSCopying + +-(id)copyWithZone:(NSZone *)zone { + AFMultipartBodyStream *bodyStreamCopy = [[[self class] allocWithZone:zone] initWithStringEncoding:self.stringEncoding]; + + for (AFHTTPBodyPart *bodyPart in self.HTTPBodyParts) { + [bodyStreamCopy appendHTTPBodyPart:[bodyPart copy]]; + } + + [bodyStreamCopy setInitialAndFinalBoundaries]; + + return bodyStreamCopy; +} + +@end + +#pragma mark - + +typedef enum { + AFEncapsulationBoundaryPhase = 1, + AFHeaderPhase = 2, + AFBodyPhase = 3, + AFFinalBoundaryPhase = 4, +} AFHTTPBodyPartReadPhase; + +@interface AFHTTPBodyPart () { + AFHTTPBodyPartReadPhase _phase; + NSInputStream *_inputStream; + unsigned long long _phaseReadOffset; +} + +- (BOOL)transitionToNextPhase; +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length; +@end + +@implementation AFHTTPBodyPart +@synthesize stringEncoding = _stringEncoding; +@synthesize headers = _headers; +@synthesize body = _body; +@synthesize bodyContentLength = _bodyContentLength; +@synthesize inputStream = _inputStream; +@synthesize hasInitialBoundary = _hasInitialBoundary; +@synthesize hasFinalBoundary = _hasFinalBoundary; + +- (id)init { + self = [super init]; + if (!self) { + return nil; + } + + [self transitionToNextPhase]; + + return self; +} + +- (void)dealloc { + if (_inputStream) { + [_inputStream close]; + _inputStream = nil; + } +} + +- (NSInputStream *)inputStream { + if (!_inputStream) { + if ([self.body isKindOfClass:[NSData class]]) { + _inputStream = [NSInputStream inputStreamWithData:self.body]; + } else if ([self.body isKindOfClass:[NSURL class]]) { + _inputStream = [NSInputStream inputStreamWithURL:self.body]; + } else if ([self.body isKindOfClass:[NSInputStream class]]) { + _inputStream = self.body; + } + } + + return _inputStream; +} + +- (NSString *)stringForHeaders { + NSMutableString *headerString = [NSMutableString string]; + for (NSString *field in [self.headers allKeys]) { + [headerString appendString:[NSString stringWithFormat:@"%@: %@%@", field, [self.headers valueForKey:field], kAFMultipartFormCRLF]]; + } + [headerString appendString:kAFMultipartFormCRLF]; + + return [NSString stringWithString:headerString]; +} + +- (unsigned long long)contentLength { + unsigned long long length = 0; + + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding]; + length += [encapsulationBoundaryData length]; + + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + length += [headersData length]; + + length += _bodyContentLength; + + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]); + length += [closingBoundaryData length]; + + return length; +} + +- (BOOL)hasBytesAvailable { + // Allows `read:maxLength:` to be called again if `AFMultipartFormFinalBoundary` doesn't fit into the available buffer + if (_phase == AFFinalBoundaryPhase) { + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (self.inputStream.streamStatus) { + case NSStreamStatusNotOpen: + case NSStreamStatusOpening: + case NSStreamStatusOpen: + case NSStreamStatusReading: + case NSStreamStatusWriting: + return YES; + case NSStreamStatusAtEnd: + case NSStreamStatusClosed: + case NSStreamStatusError: + default: + return NO; + } +#pragma clang diagnostic pop +} + +- (NSInteger)read:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ + NSUInteger totalNumberOfBytesRead = 0; + + if (_phase == AFEncapsulationBoundaryPhase) { + NSData *encapsulationBoundaryData = [([self hasInitialBoundary] ? AFMultipartFormInitialBoundary() : AFMultipartFormEncapsulationBoundary()) dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:encapsulationBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFHeaderPhase) { + NSData *headersData = [[self stringForHeaders] dataUsingEncoding:self.stringEncoding]; + totalNumberOfBytesRead += [self readData:headersData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + if (_phase == AFBodyPhase) { + NSInteger numberOfBytesRead = 0; + + numberOfBytesRead = [self.inputStream read:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + if (numberOfBytesRead == -1) { + return -1; + } else { + totalNumberOfBytesRead += numberOfBytesRead; + + if ([self.inputStream streamStatus] >= NSStreamStatusAtEnd) { + [self transitionToNextPhase]; + } + } + } + + if (_phase == AFFinalBoundaryPhase) { + NSData *closingBoundaryData = ([self hasFinalBoundary] ? [AFMultipartFormFinalBoundary() dataUsingEncoding:self.stringEncoding] : [NSData data]); + totalNumberOfBytesRead += [self readData:closingBoundaryData intoBuffer:&buffer[totalNumberOfBytesRead] maxLength:(length - (NSUInteger)totalNumberOfBytesRead)]; + } + + return totalNumberOfBytesRead; +} + +- (NSInteger)readData:(NSData *)data + intoBuffer:(uint8_t *)buffer + maxLength:(NSUInteger)length +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + NSRange range = NSMakeRange((NSUInteger)_phaseReadOffset, MIN([data length] - ((NSUInteger)_phaseReadOffset), length)); + [data getBytes:buffer range:range]; +#pragma clang diagnostic pop + + _phaseReadOffset += range.length; + + if (((NSUInteger)_phaseReadOffset) >= [data length]) { + [self transitionToNextPhase]; + } + + return (NSInteger)range.length; +} + +- (BOOL)transitionToNextPhase { + if (![[NSThread currentThread] isMainThread]) { + [self performSelectorOnMainThread:@selector(transitionToNextPhase) withObject:nil waitUntilDone:YES]; + return YES; + } + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wcovered-switch-default" + switch (_phase) { + case AFEncapsulationBoundaryPhase: + _phase = AFHeaderPhase; + break; + case AFHeaderPhase: + [self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes]; + [self.inputStream open]; + _phase = AFBodyPhase; + break; + case AFBodyPhase: + [self.inputStream close]; + _phase = AFFinalBoundaryPhase; + break; + case AFFinalBoundaryPhase: + default: + _phase = AFEncapsulationBoundaryPhase; + break; + } + _phaseReadOffset = 0; +#pragma clang diagnostic pop + + return YES; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFHTTPBodyPart *bodyPart = [[[self class] allocWithZone:zone] init]; + + bodyPart.stringEncoding = self.stringEncoding; + bodyPart.headers = self.headers; + bodyPart.bodyContentLength = self.bodyContentLength; + bodyPart.body = self.body; + + return bodyPart; +} + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h new file mode 100644 index 00000000000..b40e3d50671 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.h @@ -0,0 +1,133 @@ +// AFHTTPRequestOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFURLConnectionOperation.h" + +/** + `AFHTTPRequestOperation` is a subclass of `AFURLConnectionOperation` for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request. + */ +@interface AFHTTPRequestOperation : AFURLConnectionOperation + +///---------------------------------------------- +/// @name Getting HTTP URL Connection Information +///---------------------------------------------- + +/** + The last HTTP response received by the operation's connection. + */ +@property (readonly, nonatomic, strong) NSHTTPURLResponse *response; + +///---------------------------------------------------------- +/// @name Managing And Checking For Acceptable HTTP Responses +///---------------------------------------------------------- + +/** + A Boolean value that corresponds to whether the status code of the response is within the specified set of acceptable status codes. Returns `YES` if `acceptableStatusCodes` is `nil`. + */ +@property (nonatomic, readonly) BOOL hasAcceptableStatusCode; + +/** + A Boolean value that corresponds to whether the MIME type of the response is among the specified set of acceptable content types. Returns `YES` if `acceptableContentTypes` is `nil`. + */ +@property (nonatomic, readonly) BOOL hasAcceptableContentType; + +/** + The callback dispatch queue on success. If `NULL` (default), the main queue is used. + */ +@property (nonatomic, assign) dispatch_queue_t successCallbackQueue; + +/** + The callback dispatch queue on failure. If `NULL` (default), the main queue is used. + */ +@property (nonatomic, assign) dispatch_queue_t failureCallbackQueue; + +///------------------------------------------------------------ +/// @name Managing Acceptable HTTP Status Codes & Content Types +///------------------------------------------------------------ + +/** + Returns an `NSIndexSet` object containing the ranges of acceptable HTTP status codes. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html + + By default, this is the range 200 to 299, inclusive. + */ ++ (NSIndexSet *)acceptableStatusCodes; + +/** + Adds status codes to the set of acceptable HTTP status codes returned by `+acceptableStatusCodes` in subsequent calls by this class and its descendants. + + @param statusCodes The status codes to be added to the set of acceptable HTTP status codes + */ ++ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes; + +/** + Returns an `NSSet` object containing the acceptable MIME types. When non-`nil`, the operation will set the `error` property to an error in `AFErrorDomain`. See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17 + + By default, this is `nil`. + */ ++ (NSSet *)acceptableContentTypes; + +/** + Adds content types to the set of acceptable MIME types returned by `+acceptableContentTypes` in subsequent calls by this class and its descendants. + + @param contentTypes The content types to be added to the set of acceptable MIME types + */ ++ (void)addAcceptableContentTypes:(NSSet *)contentTypes; + + +///----------------------------------------------------- +/// @name Determining Whether A Request Can Be Processed +///----------------------------------------------------- + +/** + A Boolean value determining whether or not the class can process the specified request. For example, `AFJSONRequestOperation` may check to make sure the content type was `application/json` or the URL path extension was `.json`. + + @param urlRequest The request that is determined to be supported or not supported for this class. + */ ++ (BOOL)canProcessRequest:(NSURLRequest *)urlRequest; + +///----------------------------------------------------------- +/// @name Setting Completion Block Success / Failure Callbacks +///----------------------------------------------------------- + +/** + Sets the `completionBlock` property with a block that executes either the specified success or failure block, depending on the state of the request on completion. If `error` returns a value, which can be caused by an unacceptable status code or content type, then `failure` is executed. Otherwise, `success` is executed. + + This method should be overridden in subclasses in order to specify the response object passed into the success block. + + @param success The block to be executed on the completion of a successful request. This block has no return value and takes two arguments: the receiver operation and the object constructed from the response data of the request. + @param failure The block to be executed on the completion of an unsuccessful request. This block has no return value and takes two arguments: the receiver operation and the error that occurred during the request. + */ +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure; + +@end + +///---------------- +/// @name Functions +///---------------- + +/** + Returns a set of MIME types detected in an HTTP `Accept` or `Content-Type` header. + */ +extern NSSet * AFContentTypesFromHTTPHeader(NSString *string); + diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m new file mode 100644 index 00000000000..84f2badb694 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFHTTPRequestOperation.m @@ -0,0 +1,327 @@ +// AFHTTPRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFHTTPRequestOperation.h" +#import + +// Workaround for change in imp_implementationWithBlock() with Xcode 4.5 +#if defined(__IPHONE_6_0) || defined(__MAC_10_8) +#define AF_CAST_TO_BLOCK id +#else +#define AF_CAST_TO_BLOCK __bridge void * +#endif + +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wstrict-selector-match" + +NSSet * AFContentTypesFromHTTPHeader(NSString *string) { + if (!string) { + return nil; + } + + NSArray *mediaRanges = [string componentsSeparatedByString:@","]; + NSMutableSet *mutableContentTypes = [NSMutableSet setWithCapacity:mediaRanges.count]; + + [mediaRanges enumerateObjectsUsingBlock:^(NSString *mediaRange, __unused NSUInteger idx, __unused BOOL *stop) { + NSRange parametersRange = [mediaRange rangeOfString:@";"]; + if (parametersRange.location != NSNotFound) { + mediaRange = [mediaRange substringToIndex:parametersRange.location]; + } + + mediaRange = [mediaRange stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + + if (mediaRange.length > 0) { + [mutableContentTypes addObject:mediaRange]; + } + }]; + + return [NSSet setWithSet:mutableContentTypes]; +} + +static void AFGetMediaTypeAndSubtypeWithString(NSString *string, NSString **type, NSString **subtype) { + if (!string) { + return; + } + + NSScanner *scanner = [NSScanner scannerWithString:string]; + [scanner setCharactersToBeSkipped:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; + [scanner scanUpToString:@"/" intoString:type]; + [scanner scanString:@"/" intoString:nil]; + [scanner scanUpToString:@";" intoString:subtype]; +} + +static NSString * AFStringFromIndexSet(NSIndexSet *indexSet) { + NSMutableString *string = [NSMutableString string]; + + NSRange range = NSMakeRange([indexSet firstIndex], 1); + while (range.location != NSNotFound) { + NSUInteger nextIndex = [indexSet indexGreaterThanIndex:range.location]; + while (nextIndex == range.location + range.length) { + range.length++; + nextIndex = [indexSet indexGreaterThanIndex:nextIndex]; + } + + if (string.length) { + [string appendString:@","]; + } + + if (range.length == 1) { + [string appendFormat:@"%lu", (long)range.location]; + } else { + NSUInteger firstIndex = range.location; + NSUInteger lastIndex = firstIndex + range.length - 1; + [string appendFormat:@"%lu-%lu", (long)firstIndex, (long)lastIndex]; + } + + range.location = nextIndex; + range.length = 1; + } + + return string; +} + +static void AFSwizzleClassMethodWithClassAndSelectorUsingBlock(Class klass, SEL selector, id block) { + Method originalMethod = class_getClassMethod(klass, selector); + IMP implementation = imp_implementationWithBlock((AF_CAST_TO_BLOCK)block); + class_replaceMethod(objc_getMetaClass([NSStringFromClass(klass) UTF8String]), selector, implementation, method_getTypeEncoding(originalMethod)); +} + +#pragma mark - + +@interface AFHTTPRequestOperation () +@property (readwrite, nonatomic, strong) NSURLRequest *request; +@property (readwrite, nonatomic, strong) NSHTTPURLResponse *response; +@property (readwrite, nonatomic, strong) NSError *HTTPError; +@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; +@end + +@implementation AFHTTPRequestOperation +@synthesize HTTPError = _HTTPError; +@synthesize successCallbackQueue = _successCallbackQueue; +@synthesize failureCallbackQueue = _failureCallbackQueue; +@dynamic lock; +@dynamic request; +@dynamic response; + +- (void)dealloc { + if (_successCallbackQueue) { +#if !OS_OBJECT_USE_OBJC + dispatch_release(_successCallbackQueue); +#endif + _successCallbackQueue = NULL; + } + + if (_failureCallbackQueue) { +#if !OS_OBJECT_USE_OBJC + dispatch_release(_failureCallbackQueue); +#endif + _failureCallbackQueue = NULL; + } +} + +- (NSError *)error { + [self.lock lock]; + if (!self.HTTPError && self.response) { + if (![self hasAcceptableStatusCode] || ![self hasAcceptableContentType]) { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + [userInfo setValue:self.responseString forKey:NSLocalizedRecoverySuggestionErrorKey]; + [userInfo setValue:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; + [userInfo setValue:self.request forKey:AFNetworkingOperationFailingURLRequestErrorKey]; + [userInfo setValue:self.response forKey:AFNetworkingOperationFailingURLResponseErrorKey]; + + if (![self hasAcceptableStatusCode]) { + NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; + [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected status code in (%@), got %d", @"AFNetworking", nil), AFStringFromIndexSet([[self class] acceptableStatusCodes]), statusCode] forKey:NSLocalizedDescriptionKey]; + self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorBadServerResponse userInfo:userInfo]; + } else if (![self hasAcceptableContentType]) { + // Don't invalidate content type if there is no content + if ([self.responseData length] > 0) { + [userInfo setValue:[NSString stringWithFormat:NSLocalizedStringFromTable(@"Expected content type %@, got %@", @"AFNetworking", nil), [[self class] acceptableContentTypes], [self.response MIMEType]] forKey:NSLocalizedDescriptionKey]; + self.HTTPError = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; + } + } + } + } + [self.lock unlock]; + + if (self.HTTPError) { + return self.HTTPError; + } else { + return [super error]; + } +} + +- (NSStringEncoding)responseStringEncoding { + // When no explicit charset parameter is provided by the sender, media subtypes of the "text" type are defined to have a default charset value of "ISO-8859-1" when received via HTTP. Data in character sets other than "ISO-8859-1" or its subsets MUST be labeled with an appropriate charset value. + // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.4.1 + if (self.response && !self.response.textEncodingName && self.responseData && [self.response respondsToSelector:@selector(allHeaderFields)]) { + NSString *type = nil; + AFGetMediaTypeAndSubtypeWithString([[self.response allHeaderFields] valueForKey:@"Content-Type"], &type, nil); + + if ([type isEqualToString:@"text"]) { + return NSISOLatin1StringEncoding; + } + } + + return [super responseStringEncoding]; +} + +- (void)pause { + unsigned long long offset = 0; + if ([self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey]) { + offset = [[self.outputStream propertyForKey:NSStreamFileCurrentOffsetKey] unsignedLongLongValue]; + } else { + offset = [[self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey] length]; + } + + NSMutableURLRequest *mutableURLRequest = [self.request mutableCopy]; + if ([self.response respondsToSelector:@selector(allHeaderFields)] && [[self.response allHeaderFields] valueForKey:@"ETag"]) { + [mutableURLRequest setValue:[[self.response allHeaderFields] valueForKey:@"ETag"] forHTTPHeaderField:@"If-Range"]; + } + [mutableURLRequest setValue:[NSString stringWithFormat:@"bytes=%llu-", offset] forHTTPHeaderField:@"Range"]; + self.request = mutableURLRequest; + + [super pause]; +} + +- (BOOL)hasAcceptableStatusCode { + if (!self.response) { + return NO; + } + + NSUInteger statusCode = ([self.response isKindOfClass:[NSHTTPURLResponse class]]) ? (NSUInteger)[self.response statusCode] : 200; + return ![[self class] acceptableStatusCodes] || [[[self class] acceptableStatusCodes] containsIndex:statusCode]; +} + +- (BOOL)hasAcceptableContentType { + if (!self.response) { + return NO; + } + + // Any HTTP/1.1 message containing an entity-body SHOULD include a Content-Type header field defining the media type of that body. If and only if the media type is not given by a Content-Type field, the recipient MAY attempt to guess the media type via inspection of its content and/or the name extension(s) of the URI used to identify the resource. If the media type remains unknown, the recipient SHOULD treat it as type "application/octet-stream". + // See http://www.w3.org/Protocols/rfc2616/rfc2616-sec7.html + NSString *contentType = [self.response MIMEType]; + if (!contentType) { + contentType = @"application/octet-stream"; + } + + return ![[self class] acceptableContentTypes] || [[[self class] acceptableContentTypes] containsObject:contentType]; +} + +- (void)setSuccessCallbackQueue:(dispatch_queue_t)successCallbackQueue { + if (successCallbackQueue != _successCallbackQueue) { + if (_successCallbackQueue) { +#if !OS_OBJECT_USE_OBJC + dispatch_release(_successCallbackQueue); +#endif + _successCallbackQueue = NULL; + } + + if (successCallbackQueue) { +#if !OS_OBJECT_USE_OBJC + dispatch_retain(successCallbackQueue); +#endif + _successCallbackQueue = successCallbackQueue; + } + } +} + +- (void)setFailureCallbackQueue:(dispatch_queue_t)failureCallbackQueue { + if (failureCallbackQueue != _failureCallbackQueue) { + if (_failureCallbackQueue) { +#if !OS_OBJECT_USE_OBJC + dispatch_release(_failureCallbackQueue); +#endif + _failureCallbackQueue = NULL; + } + + if (failureCallbackQueue) { +#if !OS_OBJECT_USE_OBJC + dispatch_retain(failureCallbackQueue); +#endif + _failureCallbackQueue = failureCallbackQueue; + } + } +} + +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ + // completionBlock is manually nilled out in AFURLConnectionOperation to break the retain cycle. +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" +#pragma clang diagnostic ignored "-Wgnu" + self.completionBlock = ^{ + if (self.error) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + if (success) { + dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ + success(self, self.responseData); + }); + } + } + }; +#pragma clang diagnostic pop +} + +#pragma mark - AFHTTPRequestOperation + ++ (NSIndexSet *)acceptableStatusCodes { + return [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(200, 100)]; +} + ++ (void)addAcceptableStatusCodes:(NSIndexSet *)statusCodes { + NSMutableIndexSet *mutableStatusCodes = [[NSMutableIndexSet alloc] initWithIndexSet:[self acceptableStatusCodes]]; + [mutableStatusCodes addIndexes:statusCodes]; + AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableStatusCodes), ^(__unused id _self) { + return mutableStatusCodes; + }); +} + ++ (NSSet *)acceptableContentTypes { + return nil; +} + ++ (void)addAcceptableContentTypes:(NSSet *)contentTypes { + NSMutableSet *mutableContentTypes = [[NSMutableSet alloc] initWithSet:[self acceptableContentTypes] copyItems:YES]; + [mutableContentTypes unionSet:contentTypes]; + AFSwizzleClassMethodWithClassAndSelectorUsingBlock([self class], @selector(acceptableContentTypes), ^(__unused id _self) { + return mutableContentTypes; + }); +} + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + if ([[self class] isEqual:[AFHTTPRequestOperation class]]) { + return YES; + } + + return [[self acceptableContentTypes] intersectsSet:AFContentTypesFromHTTPHeader([request valueForHTTPHeaderField:@"Accept"])]; +} + +@end + +#pragma clang diagnostic pop diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h new file mode 100644 index 00000000000..d5e659679db --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.h @@ -0,0 +1,113 @@ +// AFImageRequestOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFHTTPRequestOperation.h" + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +#import +#endif + +/** + `AFImageRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and processing images. + + ## Acceptable Content Types + + By default, `AFImageRequestOperation` accepts the following MIME types, which correspond to the image formats supported by UIImage or NSImage: + + - `image/tiff` + - `image/jpeg` + - `image/gif` + - `image/png` + - `image/ico` + - `image/x-icon` + - `image/bmp` + - `image/x-bmp` + - `image/x-xbitmap` + - `image/x-win-bitmap` + */ +@interface AFImageRequestOperation : AFHTTPRequestOperation + +/** + An image constructed from the response data. If an error occurs during the request, `nil` will be returned, and the `error` property will be set to the error. + */ +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +@property (readonly, nonatomic, strong) UIImage *responseImage; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +@property (readonly, nonatomic, strong) NSImage *responseImage; +#endif + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +/** + The scale factor used when interpreting the image data to construct `responseImage`. Specifying a scale factor of 1.0 results in an image whose size matches the pixel-based dimensions of the image. Applying a different scale factor changes the size of the image as reported by the size property. This is set to the value of scale of the main screen by default, which automatically scales images for retina displays, for instance. + */ +@property (nonatomic, assign) CGFloat imageScale; + +/** + Whether to automatically inflate response image data for compressed formats (such as PNG or JPEG). Enabling this can significantly improve drawing performance on iOS when used with `setCompletionBlockWithSuccess:failure:`, as it allows a bitmap representation to be constructed in the background rather than on the main thread. `YES` by default. + */ +@property (nonatomic, assign) BOOL automaticallyInflatesResponseImage; +#endif + +/** + Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation. + @param success A block object to be executed when the request finishes successfully. This block has no return value and takes a single argument, the image created from the response data of the request. + + @return A new image request operation + */ +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(UIImage *image))success; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSImage *image))success; +#endif + +/** + Creates and returns an `AFImageRequestOperation` object and sets the specified success callback. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation. + @param imageProcessingBlock A block object to be executed after the image request finishes successfully, but before the image is returned in the `success` block. This block takes a single argument, the image loaded from the response body, and returns the processed image. + @param success A block object to be executed when the request finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the image created from the response data. + @param failure A block object to be executed when the request finishes unsuccessfully. This block has no return value and takes three arguments: the request object of the operation, the response for the request, and the error associated with the cause for the unsuccessful operation. + + @return A new image request operation + */ +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + imageProcessingBlock:(UIImage *(^)(UIImage *image))imageProcessingBlock + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + imageProcessingBlock:(NSImage *(^)(NSImage *image))imageProcessingBlock + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; +#endif + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m new file mode 100644 index 00000000000..7023b37afaa --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFImageRequestOperation.m @@ -0,0 +1,321 @@ +// AFImageRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFImageRequestOperation.h" + +static dispatch_queue_t image_request_operation_processing_queue() { + static dispatch_queue_t af_image_request_operation_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_image_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.image-request.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_image_request_operation_processing_queue; +} + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +static UIImage * AFImageWithDataAtScale(NSData *data, CGFloat scale) { + UIImage *image = [[UIImage alloc] initWithData:data]; + + return [[UIImage alloc] initWithCGImage:[image CGImage] scale:scale orientation:image.imageOrientation]; +} + +static UIImage * AFInflatedImageFromResponseWithDataAtScale(NSHTTPURLResponse *response, NSData *data, CGFloat scale) { + if (!data || [data length] == 0) { + return nil; + } + + UIImage *image = AFImageWithDataAtScale(data, scale); + if (image.images) { + return image; + } + + CGImageRef imageRef = nil; + CGDataProviderRef dataProvider = CGDataProviderCreateWithCFData((__bridge CFDataRef)data); + + if ([response.MIMEType isEqualToString:@"image/png"]) { + imageRef = CGImageCreateWithPNGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } else if ([response.MIMEType isEqualToString:@"image/jpeg"]) { + imageRef = CGImageCreateWithJPEGDataProvider(dataProvider, NULL, true, kCGRenderingIntentDefault); + } + + if (!imageRef) { + imageRef = CGImageCreateCopy([image CGImage]); + + if (!imageRef) { + CGDataProviderRelease(dataProvider); + return image; + } + } + + CGDataProviderRelease(dataProvider); + + size_t width = CGImageGetWidth(imageRef); + size_t height = CGImageGetHeight(imageRef); + size_t bitsPerComponent = CGImageGetBitsPerComponent(imageRef); + size_t bytesPerRow = 0; // CGImageGetBytesPerRow() calculates incorrectly in iOS 5.0, so defer to CGBitmapContextCreate() + CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); + CGBitmapInfo bitmapInfo = CGImageGetBitmapInfo(imageRef); + + if (CGColorSpaceGetNumberOfComponents(colorSpace) == 3) { + int alpha = (bitmapInfo & kCGBitmapAlphaInfoMask); + if (alpha == kCGImageAlphaNone) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaNoneSkipFirst; + } else if (!(alpha == kCGImageAlphaNoneSkipFirst || alpha == kCGImageAlphaNoneSkipLast)) { + bitmapInfo &= ~kCGBitmapAlphaInfoMask; + bitmapInfo |= kCGImageAlphaPremultipliedFirst; + } + } + + CGContextRef context = CGBitmapContextCreate(NULL, width, height, bitsPerComponent, bytesPerRow, colorSpace, bitmapInfo); + + CGColorSpaceRelease(colorSpace); + + if (!context) { + CGImageRelease(imageRef); + + return image; + } + + CGRect rect = CGRectMake(0.0f, 0.0f, width, height); + CGContextDrawImage(context, rect, imageRef); + CGImageRef inflatedImageRef = CGBitmapContextCreateImage(context); + CGContextRelease(context); + + UIImage *inflatedImage = [[UIImage alloc] initWithCGImage:inflatedImageRef scale:scale orientation:image.imageOrientation]; + CGImageRelease(inflatedImageRef); + CGImageRelease(imageRef); + + return inflatedImage; +} +#endif + +@interface AFImageRequestOperation () +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +@property (readwrite, nonatomic, strong) UIImage *responseImage; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +@property (readwrite, nonatomic, strong) NSImage *responseImage; +#endif +@end + +@implementation AFImageRequestOperation +@synthesize responseImage = _responseImage; +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +@synthesize imageScale = _imageScale; +#endif + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(UIImage *image))success +{ + return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, UIImage *image) { + if (success) { + success(image); + } + } failure:nil]; +} +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSImage *image))success +{ + return [self imageRequestOperationWithRequest:urlRequest imageProcessingBlock:nil success:^(NSURLRequest __unused *request, NSHTTPURLResponse __unused *response, NSImage *image) { + if (success) { + success(image); + } + } failure:nil]; +} +#endif + + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + imageProcessingBlock:(UIImage *(^)(UIImage *))imageProcessingBlock + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure +{ + AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest]; + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + if (success) { + UIImage *image = responseObject; + if (imageProcessingBlock) { + dispatch_async(image_request_operation_processing_queue(), ^(void) { + UIImage *processedImage = imageProcessingBlock(image); +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { + success(operation.request, operation.response, processedImage); + }); +#pragma clang diagnostic pop + }); + } else { + success(operation.request, operation.response, image); + } + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if (failure) { + failure(operation.request, operation.response, error); + } + }]; + + + return requestOperation; +} +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) ++ (instancetype)imageRequestOperationWithRequest:(NSURLRequest *)urlRequest + imageProcessingBlock:(NSImage *(^)(NSImage *))imageProcessingBlock + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure +{ + AFImageRequestOperation *requestOperation = [(AFImageRequestOperation *)[self alloc] initWithRequest:urlRequest]; + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + if (success) { + NSImage *image = responseObject; + if (imageProcessingBlock) { + dispatch_async(image_request_operation_processing_queue(), ^(void) { + NSImage *processedImage = imageProcessingBlock(image); + + dispatch_async(operation.successCallbackQueue ?: dispatch_get_main_queue(), ^(void) { + success(operation.request, operation.response, processedImage); + }); + }); + } else { + success(operation.request, operation.response, image); + } + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if (failure) { + failure(operation.request, operation.response, error); + } + }]; + + return requestOperation; +} +#endif + +- (id)initWithRequest:(NSURLRequest *)urlRequest { + self = [super initWithRequest:urlRequest]; + if (!self) { + return nil; + } + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + self.imageScale = [[UIScreen mainScreen] scale]; + self.automaticallyInflatesResponseImage = YES; +#endif + + return self; +} + + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +- (UIImage *)responseImage { + if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { + if (self.automaticallyInflatesResponseImage) { + self.responseImage = AFInflatedImageFromResponseWithDataAtScale(self.response, self.responseData, self.imageScale); + } else { + self.responseImage = AFImageWithDataAtScale(self.responseData, self.imageScale); + } + } + + return _responseImage; +} + +- (void)setImageScale:(CGFloat)imageScale { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wfloat-equal" + if (imageScale == _imageScale) { + return; + } +#pragma clang diagnostic pop + + _imageScale = imageScale; + + self.responseImage = nil; +} +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) +- (NSImage *)responseImage { + if (!_responseImage && [self.responseData length] > 0 && [self isFinished]) { + // Ensure that the image is set to it's correct pixel width and height + NSBitmapImageRep *bitimage = [[NSBitmapImageRep alloc] initWithData:self.responseData]; + self.responseImage = [[NSImage alloc] initWithSize:NSMakeSize([bitimage pixelsWide], [bitimage pixelsHigh])]; + [self.responseImage addRepresentation:bitimage]; + } + + return _responseImage; +} +#endif + +#pragma mark - AFHTTPRequestOperation + ++ (NSSet *)acceptableContentTypes { + return [NSSet setWithObjects:@"image/tiff", @"image/jpeg", @"image/gif", @"image/png", @"image/ico", @"image/x-icon", @"image/bmp", @"image/x-bmp", @"image/x-xbitmap", @"image/x-win-bitmap", nil]; +} + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + static NSSet * _acceptablePathExtension = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _acceptablePathExtension = [[NSSet alloc] initWithObjects:@"tif", @"tiff", @"jpg", @"jpeg", @"gif", @"png", @"ico", @"bmp", @"cur", nil]; + }); + + return [_acceptablePathExtension containsObject:[[request URL] pathExtension]] || [super canProcessRequest:request]; +} + +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" +#pragma clang diagnostic ignored "-Wgnu" + + self.completionBlock = ^ { + dispatch_async(image_request_operation_processing_queue(), ^(void) { + if (self.error) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + if (success) { +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + UIImage *image = nil; +#elif defined(__MAC_OS_X_VERSION_MIN_REQUIRED) + NSImage *image = nil; +#endif + + image = self.responseImage; + + dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ + success(self, image); + }); + } + } + }); + }; +#pragma clang diagnostic pop +} + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h new file mode 100644 index 00000000000..5493a40775f --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.h @@ -0,0 +1,71 @@ +// AFJSONRequestOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFHTTPRequestOperation.h" + +/** + `AFJSONRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with JSON response data. + + ## Acceptable Content Types + + By default, `AFJSONRequestOperation` accepts the following MIME types, which includes the official standard, `application/json`, as well as other commonly-used types: + + - `application/json` + - `text/json` + + @warning JSON parsing will use the built-in `NSJSONSerialization` class. + */ +@interface AFJSONRequestOperation : AFHTTPRequestOperation + +///---------------------------- +/// @name Getting Response Data +///---------------------------- + +/** + A JSON object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. + */ +@property (readonly, nonatomic, strong) id responseJSON; + +/** + Options for reading the response JSON data and creating the Foundation objects. For possible values, see the `NSJSONSerialization` documentation section "NSJSONReadingOptions". + */ +@property (nonatomic, assign) NSJSONReadingOptions JSONReadingOptions; + +///---------------------------------- +/// @name Creating Request Operations +///---------------------------------- + +/** + Creates and returns an `AFJSONRequestOperation` object and sets the specified success and failure callbacks. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation + @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the JSON object created from the response data of request. + @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as JSON. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. + + @return A new JSON request operation + */ ++ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure; + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m new file mode 100644 index 00000000000..fffc60c5907 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFJSONRequestOperation.m @@ -0,0 +1,150 @@ +// AFJSONRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFJSONRequestOperation.h" + +static dispatch_queue_t json_request_operation_processing_queue() { + static dispatch_queue_t af_json_request_operation_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_json_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.json-request.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_json_request_operation_processing_queue; +} + +@interface AFJSONRequestOperation () +@property (readwrite, nonatomic, strong) id responseJSON; +@property (readwrite, nonatomic, strong) NSError *JSONError; +@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; +@end + +@implementation AFJSONRequestOperation +@synthesize responseJSON = _responseJSON; +@synthesize JSONReadingOptions = _JSONReadingOptions; +@synthesize JSONError = _JSONError; +@dynamic lock; + ++ (instancetype)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure +{ + AFJSONRequestOperation *requestOperation = [(AFJSONRequestOperation *)[self alloc] initWithRequest:urlRequest]; + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + if (success) { + success(operation.request, operation.response, responseObject); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if (failure) { + failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]); + } + }]; + + return requestOperation; +} + + +- (id)responseJSON { + [self.lock lock]; + if (!_responseJSON && [self.responseData length] > 0 && [self isFinished] && !self.JSONError) { + NSError *error = nil; + + // Workaround for behavior of Rails to return a single space for `head :ok` (a workaround for a bug in Safari), which is not interpreted as valid input by NSJSONSerialization. + // See https://github.com/rails/rails/issues/1742 + if (self.responseString && ![self.responseString isEqualToString:@" "]) { + // Workaround for a bug in NSJSONSerialization when Unicode character escape codes are used instead of the actual character + // See http://stackoverflow.com/a/12843465/157142 + NSData *data = [self.responseString dataUsingEncoding:NSUTF8StringEncoding]; + + if (data) { + self.responseJSON = [NSJSONSerialization JSONObjectWithData:data options:self.JSONReadingOptions error:&error]; + } else { + NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; + [userInfo setValue:@"Operation responseData failed decoding as a UTF-8 string" forKey:NSLocalizedDescriptionKey]; + [userInfo setValue:[NSString stringWithFormat:@"Could not decode string: %@", self.responseString] forKey:NSLocalizedFailureReasonErrorKey]; + error = [[NSError alloc] initWithDomain:AFNetworkingErrorDomain code:NSURLErrorCannotDecodeContentData userInfo:userInfo]; + } + } + + self.JSONError = error; + } + [self.lock unlock]; + + return _responseJSON; +} + +- (NSError *)error { + if (_JSONError) { + return _JSONError; + } else { + return [super error]; + } +} + +#pragma mark - AFHTTPRequestOperation + ++ (NSSet *)acceptableContentTypes { + return [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", nil]; +} + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + return [[[request URL] pathExtension] isEqualToString:@"json"] || [super canProcessRequest:request]; +} + +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" +#pragma clang diagnostic ignored "-Wgnu" + + self.completionBlock = ^ { + if (self.error) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + dispatch_async(json_request_operation_processing_queue(), ^{ + id JSON = self.responseJSON; + + if (self.error) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + if (success) { + dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ + success(self, JSON); + }); + } + } + }); + } + }; +#pragma clang diagnostic pop +} + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 100644 index 00000000000..714193baf37 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1,75 @@ +// AFNetworkActivityIndicatorManager.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import + +/** + `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a network request operation has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. + + You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: + + [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; + + By setting `isNetworkActivityIndicatorVisible` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. + + See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: + http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 + */ +@interface AFNetworkActivityIndicatorManager : NSObject + +/** + A Boolean value indicating whether the manager is enabled. + + If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. + */ +@property (nonatomic, assign, getter = isEnabled) BOOL enabled; + +/** + A Boolean value indicating whether the network activity indicator is currently displayed in the status bar. + */ +@property (readonly, nonatomic, assign) BOOL isNetworkActivityIndicatorVisible; + +/** + Returns the shared network activity indicator manager object for the system. + + @return The systemwide network activity indicator manager. + */ ++ (instancetype)sharedManager; + +/** + Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. + */ +- (void)incrementActivityCount; + +/** + Decrements the number of active network requests. If this number becomes zero before decrementing, this will stop animating the status bar network activity indicator. + */ +- (void)decrementActivityCount; + +@end + +#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m new file mode 100644 index 00000000000..68cbd339691 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.m @@ -0,0 +1,157 @@ +// AFNetworkActivityIndicatorManager.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFNetworkActivityIndicatorManager.h" + +#import "AFHTTPRequestOperation.h" + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +static NSTimeInterval const kAFNetworkActivityIndicatorInvisibilityDelay = 0.17; + +@interface AFNetworkActivityIndicatorManager () +@property (readwrite, nonatomic, assign) NSInteger activityCount; +@property (readwrite, nonatomic, strong) NSTimer *activityIndicatorVisibilityTimer; +@property (readonly, nonatomic, getter = isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; + +- (void)updateNetworkActivityIndicatorVisibility; +- (void)updateNetworkActivityIndicatorVisibilityDelayed; +@end + +@implementation AFNetworkActivityIndicatorManager +@synthesize activityCount = _activityCount; +@synthesize activityIndicatorVisibilityTimer = _activityIndicatorVisibilityTimer; +@synthesize enabled = _enabled; +@dynamic networkActivityIndicatorVisible; + ++ (instancetype)sharedManager { + static AFNetworkActivityIndicatorManager *_sharedManager = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _sharedManager = [[self alloc] init]; + }); + + return _sharedManager; +} + ++ (NSSet *)keyPathsForValuesAffectingIsNetworkActivityIndicatorVisible { + return [NSSet setWithObject:@"activityCount"]; +} + +- (id)init { + self = [super init]; + if (!self) { + return nil; + } + + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidStart:) name:AFNetworkingOperationDidStartNotification object:nil]; + [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(networkingOperationDidFinish:) name:AFNetworkingOperationDidFinishNotification object:nil]; + + return self; +} + +- (void)dealloc { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + + [_activityIndicatorVisibilityTimer invalidate]; + +} + +- (void)updateNetworkActivityIndicatorVisibilityDelayed { + if (self.enabled) { + // Delay hiding of activity indicator for a short interval, to avoid flickering + if (![self isNetworkActivityIndicatorVisible]) { + [self.activityIndicatorVisibilityTimer invalidate]; + self.activityIndicatorVisibilityTimer = [NSTimer timerWithTimeInterval:kAFNetworkActivityIndicatorInvisibilityDelay target:self selector:@selector(updateNetworkActivityIndicatorVisibility) userInfo:nil repeats:NO]; + [[NSRunLoop mainRunLoop] addTimer:self.activityIndicatorVisibilityTimer forMode:NSRunLoopCommonModes]; + } else { + [self performSelectorOnMainThread:@selector(updateNetworkActivityIndicatorVisibility) withObject:nil waitUntilDone:NO modes:[NSArray arrayWithObject:NSRunLoopCommonModes]]; + } + } +} + +- (BOOL)isNetworkActivityIndicatorVisible { + return _activityCount > 0; +} + +- (void)updateNetworkActivityIndicatorVisibility { + [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:[self isNetworkActivityIndicatorVisible]]; +} + +// Not exposed, but used if activityCount is set via KVC. +- (NSInteger)activityCount { + return _activityCount; +} + +- (void)setActivityCount:(NSInteger)activityCount { + @synchronized(self) { + _activityCount = activityCount; + } + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateNetworkActivityIndicatorVisibilityDelayed]; + }); +} + +- (void)incrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { + _activityCount++; + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateNetworkActivityIndicatorVisibilityDelayed]; + }); +} + +- (void)decrementActivityCount { + [self willChangeValueForKey:@"activityCount"]; + @synchronized(self) { +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wgnu" + _activityCount = MAX(_activityCount - 1, 0); +#pragma clang diagnostic pop + } + [self didChangeValueForKey:@"activityCount"]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [self updateNetworkActivityIndicatorVisibilityDelayed]; + }); +} + +- (void)networkingOperationDidStart:(NSNotification *)notification { + AFURLConnectionOperation *connectionOperation = [notification object]; + if (connectionOperation.request.URL) { + [self incrementActivityCount]; + } +} + +- (void)networkingOperationDidFinish:(NSNotification *)notification { + AFURLConnectionOperation *connectionOperation = [notification object]; + if (connectionOperation.request.URL) { + [self decrementActivityCount]; + } +} + +@end + +#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h new file mode 100644 index 00000000000..b8f840b92cf --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFNetworking.h @@ -0,0 +1,43 @@ +// AFNetworking.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#ifndef _AFNETWORKING_ + #define _AFNETWORKING_ + + #import "AFURLConnectionOperation.h" + + #import "AFHTTPRequestOperation.h" + #import "AFJSONRequestOperation.h" + #import "AFXMLRequestOperation.h" + #import "AFPropertyListRequestOperation.h" + #import "AFHTTPClient.h" + + #import "AFImageRequestOperation.h" + + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + #import "AFNetworkActivityIndicatorManager.h" + #import "UIImageView+AFNetworking.h" + #endif +#endif /* _AFNETWORKING_ */ diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h new file mode 100644 index 00000000000..9ebb6057437 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.h @@ -0,0 +1,68 @@ +// AFPropertyListRequestOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFHTTPRequestOperation.h" + +/** + `AFPropertyListRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and deserializing objects with property list (plist) response data. + + ## Acceptable Content Types + + By default, `AFPropertyListRequestOperation` accepts the following MIME types: + + - `application/x-plist` + */ +@interface AFPropertyListRequestOperation : AFHTTPRequestOperation + +///---------------------------- +/// @name Getting Response Data +///---------------------------- + +/** + An object deserialized from a plist constructed using the response data. + */ +@property (readonly, nonatomic) id responsePropertyList; + +///-------------------------------------- +/// @name Managing Property List Behavior +///-------------------------------------- + +/** + One of the `NSPropertyListMutabilityOptions` options, specifying the mutability of objects deserialized from the property list. By default, this is `NSPropertyListImmutable`. + */ +@property (nonatomic, assign) NSPropertyListReadOptions propertyListReadOptions; + +/** + Creates and returns an `AFPropertyListRequestOperation` object and sets the specified success and failure callbacks. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation + @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the object deserialized from a plist constructed using the response data. + @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while deserializing the object from a property list. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. + + @return A new property list request operation + */ ++ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure; + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m new file mode 100644 index 00000000000..370e12be8e3 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFPropertyListRequestOperation.m @@ -0,0 +1,143 @@ +// AFPropertyListRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFPropertyListRequestOperation.h" + +static dispatch_queue_t property_list_request_operation_processing_queue() { + static dispatch_queue_t af_property_list_request_operation_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_property_list_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.property-list-request.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_property_list_request_operation_processing_queue; +} + +@interface AFPropertyListRequestOperation () +@property (readwrite, nonatomic) id responsePropertyList; +@property (readwrite, nonatomic, assign) NSPropertyListFormat propertyListFormat; +@property (readwrite, nonatomic) NSError *propertyListError; +@end + +@implementation AFPropertyListRequestOperation +@synthesize responsePropertyList = _responsePropertyList; +@synthesize propertyListReadOptions = _propertyListReadOptions; +@synthesize propertyListFormat = _propertyListFormat; +@synthesize propertyListError = _propertyListError; + ++ (instancetype)propertyListRequestOperationWithRequest:(NSURLRequest *)request + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id propertyList))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id propertyList))failure +{ + AFPropertyListRequestOperation *requestOperation = [(AFPropertyListRequestOperation *)[self alloc] initWithRequest:request]; + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + if (success) { + success(operation.request, operation.response, responseObject); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if (failure) { + failure(operation.request, operation.response, error, [(AFPropertyListRequestOperation *)operation responsePropertyList]); + } + }]; + + return requestOperation; +} + +- (id)initWithRequest:(NSURLRequest *)urlRequest { + self = [super initWithRequest:urlRequest]; + if (!self) { + return nil; + } + + self.propertyListReadOptions = NSPropertyListImmutable; + + return self; +} + + +- (id)responsePropertyList { + if (!_responsePropertyList && [self.responseData length] > 0 && [self isFinished]) { + NSPropertyListFormat format; + NSError *error = nil; + self.responsePropertyList = [NSPropertyListSerialization propertyListWithData:self.responseData options:self.propertyListReadOptions format:&format error:&error]; + self.propertyListFormat = format; + self.propertyListError = error; + } + + return _responsePropertyList; +} + +- (NSError *)error { + if (_propertyListError) { + return _propertyListError; + } else { + return [super error]; + } +} + +#pragma mark - AFHTTPRequestOperation + ++ (NSSet *)acceptableContentTypes { + return [NSSet setWithObjects:@"application/x-plist", nil]; +} + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + return [[[request URL] pathExtension] isEqualToString:@"plist"] || [super canProcessRequest:request]; +} + +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" +#pragma clang diagnostic ignored "-Wgnu" + self.completionBlock = ^ { + if (self.error) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + dispatch_async(property_list_request_operation_processing_queue(), ^(void) { + id propertyList = self.responsePropertyList; + + if (self.propertyListError) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + if (success) { + dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ + success(self, propertyList); + }); + } + } + }); + } + }; +#pragma clang diagnostic pop +} + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h new file mode 100644 index 00000000000..0ac9e105c3f --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1,370 @@ +// AFURLConnectionOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import + +#import + +/** + `AFURLConnectionOperation` is a subclass of `NSOperation` that implements `NSURLConnection` delegate methods. + + ## Subclassing Notes + + This is the base class of all network request operations. You may wish to create your own subclass in order to implement additional `NSURLConnection` delegate methods (see "`NSURLConnection` Delegate Methods" below), or to provide additional properties and/or class constructors. + + If you are creating a subclass that communicates over the HTTP or HTTPS protocols, you may want to consider subclassing `AFHTTPRequestOperation` instead, as it supports specifying acceptable content types or status codes. + + ## NSURLConnection Delegate Methods + + `AFURLConnectionOperation` implements the following `NSURLConnection` delegate methods: + + - `connection:didReceiveResponse:` + - `connection:didReceiveData:` + - `connectionDidFinishLoading:` + - `connection:didFailWithError:` + - `connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:` + - `connection:willCacheResponse:` + - `connectionShouldUseCredentialStorage:` + - `connection:willSendRequestForAuthenticationChallenge:` + + If any of these methods are overridden in a subclass, they _must_ call the `super` implementation first. + + ## Class Constructors + + Class constructors, or methods that return an unowned instance, are the preferred way for subclasses to encapsulate any particular logic for handling the setup or parsing of response data. For instance, `AFJSONRequestOperation` provides `JSONRequestOperationWithRequest:success:failure:`, which takes block arguments, whose parameter on for a successful request is the JSON object initialized from the `response data`. + + ## Callbacks and Completion Blocks + + The built-in `completionBlock` provided by `NSOperation` allows for custom behavior to be executed after the request finishes. It is a common pattern for class constructors in subclasses to take callback block parameters, and execute them conditionally in the body of its `completionBlock`. Make sure to handle cancelled operations appropriately when setting a `completionBlock` (i.e. returning early before parsing response data). See the implementation of any of the `AFHTTPRequestOperation` subclasses for an example of this. + + Subclasses are strongly discouraged from overriding `setCompletionBlock:`, as `AFURLConnectionOperation`'s implementation includes a workaround to mitigate retain cycles, and what Apple rather ominously refers to as ["The Deallocation Problem"](http://developer.apple.com/library/ios/#technotes/tn2109/). + + ## SSL Pinning + + Relying on the CA trust model to validate SSL certificates exposes your app to security vulnerabilities, such as man-in-the-middle attacks. For applications that connect to known servers, SSL certificate pinning provides an increased level of security, by checking server certificate validity against those specified in the app bundle. + + SSL with certificate pinning is strongly recommended for any application that transmits sensitive information to an external webservice. + + When `defaultSSLPinningMode` is defined on `AFHTTPClient` and the Security framework is linked, connections will be validated on all matching certificates with a `.cer` extension in the bundle root. + + ## NSCoding & NSCopying Conformance + + `AFURLConnectionOperation` conforms to the `NSCoding` and `NSCopying` protocols, allowing operations to be archived to disk, and copied in memory, respectively. However, because of the intrinsic limitations of capturing the exact state of an operation at a particular moment, there are some important caveats to keep in mind: + + ### NSCoding Caveats + + - Encoded operations do not include any block or stream properties. Be sure to set `completionBlock`, `outputStream`, and any callback blocks as necessary when using `-initWithCoder:` or `NSKeyedUnarchiver`. + - Operations are paused on `encodeWithCoder:`. If the operation was encoded while paused or still executing, its archived state will return `YES` for `isReady`. Otherwise, the state of an operation when encoding will remain unchanged. + + ### NSCopying Caveats + + - `-copy` and `-copyWithZone:` return a new operation with the `NSURLRequest` of the original. So rather than an exact copy of the operation at that particular instant, the copying mechanism returns a completely new instance, which can be useful for retrying operations. + - A copy of an operation will not include the `outputStream` of the original. + - Operation copies do not include `completionBlock`. `completionBlock` often strongly captures a reference to `self`, which would otherwise have the unintuitive side-effect of pointing to the _original_ operation when copied. + */ + +typedef enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, +} AFURLConnectionOperationSSLPinningMode; + +@interface AFURLConnectionOperation : NSOperation = 50000) || \ + (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1080) +NSURLConnectionDataDelegate, +#endif +NSCoding, NSCopying> + +///------------------------------- +/// @name Accessing Run Loop Modes +///------------------------------- + +/** + The run loop modes in which the operation will run on the network thread. By default, this is a single-member set containing `NSRunLoopCommonModes`. + */ +@property (nonatomic, strong) NSSet *runLoopModes; + +///----------------------------------------- +/// @name Getting URL Connection Information +///----------------------------------------- + +/** + The request used by the operation's connection. + */ +@property (readonly, nonatomic, strong) NSURLRequest *request; + +/** + The last response received by the operation's connection. + */ +@property (readonly, nonatomic, strong) NSURLResponse *response; + +/** + The error, if any, that occurred in the lifecycle of the request. + */ +@property (readonly, nonatomic, strong) NSError *error; + +/** + Whether the connection should accept an invalid SSL certificate. + + If `_AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_` is set, this property defaults to `YES` for backwards compatibility. Otherwise, this property defaults to `NO`. + */ +@property (nonatomic, assign) BOOL allowsInvalidSSLCertificate; + +///---------------------------- +/// @name Getting Response Data +///---------------------------- + +/** + The data received during the request. + */ +@property (readonly, nonatomic, strong) NSData *responseData; + +/** + The string representation of the response data. + */ +@property (readonly, nonatomic, copy) NSString *responseString; + +/** + The string encoding of the response. + + If the response does not specify a valid string encoding, `responseStringEncoding` will return `NSUTF8StringEncoding`. + */ +@property (readonly, nonatomic, assign) NSStringEncoding responseStringEncoding; + +///------------------------------- +/// @name Managing URL Credentials +///------------------------------- + +/** + Whether the URL connection should consult the credential storage for authenticating the connection. `YES` by default. + + This is the value that is returned in the `NSURLConnectionDelegate` method `-connectionShouldUseCredentialStorage:`. + */ +@property (nonatomic, assign) BOOL shouldUseCredentialStorage; + +/** + The credential used for authentication challenges in `-connection:didReceiveAuthenticationChallenge:`. + + This will be overridden by any shared credentials that exist for the username or password of the request URL, if present. + */ +@property (nonatomic, strong) NSURLCredential *credential; + +/** + The pinning mode which will be used for SSL connections. `AFSSLPinningModePublicKey` by default. + + SSL Pinning requires that the Security framework is linked with the binary. See the "SSL Pinning" section in the `AFURLConnectionOperation`" header for more information. + */ +@property (nonatomic, assign) AFURLConnectionOperationSSLPinningMode SSLPinningMode; + +///------------------------ +/// @name Accessing Streams +///------------------------ + +/** + The input stream used to read data to be sent during the request. + + This property acts as a proxy to the `HTTPBodyStream` property of `request`. + */ +@property (nonatomic, strong) NSInputStream *inputStream; + +/** + The output stream that is used to write data received until the request is finished. + + By default, data is accumulated into a buffer that is stored into `responseData` upon completion of the request. When `outputStream` is set, the data will not be accumulated into an internal buffer, and as a result, the `responseData` property of the completed request will be `nil`. The output stream will be scheduled in the network thread runloop upon being set. + */ +@property (nonatomic, strong) NSOutputStream *outputStream; + +///--------------------------------------------- +/// @name Managing Request Operation Information +///--------------------------------------------- + +/** + The user info dictionary for the receiver. + */ +@property (nonatomic, strong) NSDictionary *userInfo; + +///------------------------------------------------------ +/// @name Initializing an AFURLConnectionOperation Object +///------------------------------------------------------ + +/** + Initializes and returns a newly allocated operation object with a url connection configured with the specified url request. + + This is the designated initializer. + + @param urlRequest The request object to be used by the operation connection. + */ +- (id)initWithRequest:(NSURLRequest *)urlRequest; + +///---------------------------------- +/// @name Pausing / Resuming Requests +///---------------------------------- + +/** + Pauses the execution of the request operation. + + A paused operation returns `NO` for `-isReady`, `-isExecuting`, and `-isFinished`. As such, it will remain in an `NSOperationQueue` until it is either cancelled or resumed. Pausing a finished, cancelled, or paused operation has no effect. + */ +- (void)pause; + +/** + Whether the request operation is currently paused. + + @return `YES` if the operation is currently paused, otherwise `NO`. + */ +- (BOOL)isPaused; + +/** + Resumes the execution of the paused request operation. + + Pause/Resume behavior varies depending on the underlying implementation for the operation class. In its base implementation, resuming a paused requests restarts the original request. However, since HTTP defines a specification for how to request a specific content range, `AFHTTPRequestOperation` will resume downloading the request from where it left off, instead of restarting the original request. + */ +- (void)resume; + +///---------------------------------------------- +/// @name Configuring Backgrounding Task Behavior +///---------------------------------------------- + +/** + Specifies that the operation should continue execution after the app has entered the background, and the expiration handler for that background task. + + @param handler A handler to be called shortly before the application’s remaining background time reaches 0. The handler is wrapped in a block that cancels the operation, and cleans up and marks the end of execution, unlike the `handler` parameter in `UIApplication -beginBackgroundTaskWithExpirationHandler:`, which expects this to be done in the handler itself. The handler is called synchronously on the main thread, thus blocking the application’s suspension momentarily while the application is notified. + */ +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler; +#endif + +///--------------------------------- +/// @name Setting Progress Callbacks +///--------------------------------- + +/** + Sets a callback to be called when an undetermined number of bytes have been uploaded to the server. + + @param block A block object to be called when an undetermined number of bytes have been uploaded to the server. This block has no return value and takes three arguments: the number of bytes written since the last time the upload progress block was called, the total bytes written, and the total bytes expected to be written during the request, as initially determined by the length of the HTTP body. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block; + +/** + Sets a callback to be called when an undetermined number of bytes have been downloaded from the server. + + @param block A block object to be called when an undetermined number of bytes have been downloaded from the server. This block has no return value and takes three arguments: the number of bytes read since the last time the download progress block was called, the total bytes read, and the total bytes expected to be read during the request, as initially determined by the expected content size of the `NSHTTPURLResponse` object. This block may be called multiple times, and will execute on the main thread. + */ +- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block; + +///------------------------------------------------- +/// @name Setting NSURLConnection Delegate Callbacks +///------------------------------------------------- + +/** + Sets a block to be executed when the connection will authenticate a challenge in order to download its request, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequestForAuthenticationChallenge:`. + + @param block A block object to be executed when the connection will authenticate a challenge in order to download its request. The block has no return type and takes two arguments: the URL connection object, and the challenge that must be authenticated. This block must invoke one of the challenge-responder methods (NSURLAuthenticationChallengeSender protocol). + + If `allowsInvalidSSLCertificate` is set to YES, `connection:willSendRequestForAuthenticationChallenge:` will attempt to have the challenge sender use credentials with invalid SSL certificates. + */ +- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block; + +/** + Sets a block to be executed when the server redirects the request from one URL to another URL, or when the request URL changed by the `NSURLProtocol` subclass handling the request in order to standardize its format, as handled by the `NSURLConnectionDelegate` method `connection:willSendRequest:redirectResponse:`. + + @param block A block object to be executed when the request URL was changed. The block returns an `NSURLRequest` object, the URL request to redirect, and takes three arguments: the URL connection object, the the proposed redirected request, and the URL response that caused the redirect. + */ +- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block; + +/** + Sets a block to be executed to modify the response a connection will cache, if any, as handled by the `NSURLConnectionDelegate` method `connection:willCacheResponse:`. + + @param block A block object to be executed to determine what response a connection will cache, if any. The block returns an `NSCachedURLResponse` object, the cached response to store in memory or `nil` to prevent the response from being cached, and takes two arguments: the URL connection object, and the cached response provided for the request. + */ +- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block; + +@end + +///---------------- +/// @name Constants +///---------------- + +/** + ## SSL Pinning Options + + The following constants are provided by `AFURLConnectionOperation` as possible SSL Pinning options. + + enum { + AFSSLPinningModeNone, + AFSSLPinningModePublicKey, + AFSSLPinningModeCertificate, + } + + `AFSSLPinningModeNone` + Do not pin SSL connections + + `AFSSLPinningModePublicKey` + Pin SSL connections to certificate public key (SPKI). + + `AFSSLPinningModeCertificate` + Pin SSL connections to exact certificate. This may cause problems when your certificate expires and needs re-issuance. + + ## User info dictionary keys + + These keys may exist in the user info dictionary, in addition to those defined for NSError. + + - `NSString * const AFNetworkingOperationFailingURLRequestErrorKey` + - `NSString * const AFNetworkingOperationFailingURLResponseErrorKey` + + ### Constants + + `AFNetworkingOperationFailingURLRequestErrorKey` + The corresponding value is an `NSURLRequest` containing the request of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. + + `AFNetworkingOperationFailingURLResponseErrorKey` + The corresponding value is an `NSURLResponse` containing the response of the operation associated with an error. This key is only present in the `AFNetworkingErrorDomain`. + + ## Error Domains + + The following error domain is predefined. + + - `NSString * const AFNetworkingErrorDomain` + + ### Constants + + `AFNetworkingErrorDomain` + AFNetworking errors. Error codes for `AFNetworkingErrorDomain` correspond to codes in `NSURLErrorDomain`. + */ +extern NSString * const AFNetworkingErrorDomain; +extern NSString * const AFNetworkingOperationFailingURLRequestErrorKey; +extern NSString * const AFNetworkingOperationFailingURLResponseErrorKey; + +///-------------------- +/// @name Notifications +///-------------------- + +/** + Posted when an operation begins executing. + */ +extern NSString * const AFNetworkingOperationDidStartNotification; + +/** + Posted when an operation finishes. + */ +extern NSString * const AFNetworkingOperationDidFinishNotification; diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m new file mode 100644 index 00000000000..595ea864317 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFURLConnectionOperation.m @@ -0,0 +1,848 @@ +// AFURLConnectionOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFURLConnectionOperation.h" + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import +#endif + +#if !__has_feature(objc_arc) +#error AFNetworking must be built with ARC. +// You can turn on ARC for only AFNetworking files by adding -fobjc-arc to the build phase for each of its files. +#endif + +typedef enum { + AFOperationPausedState = -1, + AFOperationReadyState = 1, + AFOperationExecutingState = 2, + AFOperationFinishedState = 3, +} _AFOperationState; + +typedef signed short AFOperationState; + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +typedef UIBackgroundTaskIdentifier AFBackgroundTaskIdentifier; +#else +typedef id AFBackgroundTaskIdentifier; +#endif + +static NSString * const kAFNetworkingLockName = @"com.alamofire.networking.operation.lock"; + +NSString * const AFNetworkingErrorDomain = @"AFNetworkingErrorDomain"; +NSString * const AFNetworkingOperationFailingURLRequestErrorKey = @"AFNetworkingOperationFailingURLRequestErrorKey"; +NSString * const AFNetworkingOperationFailingURLResponseErrorKey = @"AFNetworkingOperationFailingURLResponseErrorKey"; + +NSString * const AFNetworkingOperationDidStartNotification = @"com.alamofire.networking.operation.start"; +NSString * const AFNetworkingOperationDidFinishNotification = @"com.alamofire.networking.operation.finish"; + +typedef void (^AFURLConnectionOperationProgressBlock)(NSUInteger bytes, long long totalBytes, long long totalBytesExpected); +typedef void (^AFURLConnectionOperationAuthenticationChallengeBlock)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge); +typedef NSCachedURLResponse * (^AFURLConnectionOperationCacheResponseBlock)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse); +typedef NSURLRequest * (^AFURLConnectionOperationRedirectResponseBlock)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse); + +static inline NSString * AFKeyPathFromOperationState(AFOperationState state) { + switch (state) { + case AFOperationReadyState: + return @"isReady"; + case AFOperationExecutingState: + return @"isExecuting"; + case AFOperationFinishedState: + return @"isFinished"; + case AFOperationPausedState: + return @"isPaused"; + default: + return @"state"; + } +} + +static inline BOOL AFStateTransitionIsValid(AFOperationState fromState, AFOperationState toState, BOOL isCancelled) { + switch (fromState) { + case AFOperationReadyState: + switch (toState) { + case AFOperationPausedState: + case AFOperationExecutingState: + return YES; + case AFOperationFinishedState: + return isCancelled; + default: + return NO; + } + case AFOperationExecutingState: + switch (toState) { + case AFOperationPausedState: + case AFOperationFinishedState: + return YES; + default: + return NO; + } + case AFOperationFinishedState: + return NO; + case AFOperationPausedState: + return toState == AFOperationReadyState; + default: + return YES; + } +} + +#if !defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +static NSData *AFSecKeyGetData(SecKeyRef key) { + CFDataRef data = NULL; + + OSStatus status = SecItemExport(key, kSecFormatUnknown, kSecItemPemArmour, NULL, &data); + NSCAssert(status == errSecSuccess, @"SecItemExport error: %ld", (long int)status); + NSCParameterAssert(data); + + return (__bridge_transfer NSData *)data; +} +#endif + +static BOOL AFSecKeyIsEqualToKey(SecKeyRef key1, SecKeyRef key2) { +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + return [(__bridge id)key1 isEqual:(__bridge id)key2]; +#else + return [AFSecKeyGetData(key1) isEqual:AFSecKeyGetData(key2)]; +#endif +} + +@interface AFURLConnectionOperation () +@property (readwrite, nonatomic, assign) AFOperationState state; +@property (readwrite, nonatomic, assign, getter = isCancelled) BOOL cancelled; +@property (readwrite, nonatomic, strong) NSRecursiveLock *lock; +@property (readwrite, nonatomic, strong) NSURLConnection *connection; +@property (readwrite, nonatomic, strong) NSURLRequest *request; +@property (readwrite, nonatomic, strong) NSURLResponse *response; +@property (readwrite, nonatomic, strong) NSError *error; +@property (readwrite, nonatomic, strong) NSData *responseData; +@property (readwrite, nonatomic, copy) NSString *responseString; +@property (readwrite, nonatomic, assign) NSStringEncoding responseStringEncoding; +@property (readwrite, nonatomic, assign) long long totalBytesRead; +@property (readwrite, nonatomic, assign) AFBackgroundTaskIdentifier backgroundTaskIdentifier; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock uploadProgress; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationProgressBlock downloadProgress; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationAuthenticationChallengeBlock authenticationChallenge; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationCacheResponseBlock cacheResponse; +@property (readwrite, nonatomic, copy) AFURLConnectionOperationRedirectResponseBlock redirectResponse; + +- (void)operationDidStart; +- (void)finish; +- (void)cancelConnection; +@end + +@implementation AFURLConnectionOperation +@synthesize state = _state; +@synthesize cancelled = _cancelled; +@synthesize connection = _connection; +@synthesize runLoopModes = _runLoopModes; +@synthesize request = _request; +@synthesize response = _response; +@synthesize error = _error; +@synthesize allowsInvalidSSLCertificate = _allowsInvalidSSLCertificate; +@synthesize responseData = _responseData; +@synthesize responseString = _responseString; +@synthesize responseStringEncoding = _responseStringEncoding; +@synthesize totalBytesRead = _totalBytesRead; +@dynamic inputStream; +@synthesize outputStream = _outputStream; +@synthesize credential = _credential; +@synthesize SSLPinningMode = _SSLPinningMode; +@synthesize shouldUseCredentialStorage = _shouldUseCredentialStorage; +@synthesize userInfo = _userInfo; +@synthesize backgroundTaskIdentifier = _backgroundTaskIdentifier; +@synthesize uploadProgress = _uploadProgress; +@synthesize downloadProgress = _downloadProgress; +@synthesize authenticationChallenge = _authenticationChallenge; +@synthesize cacheResponse = _cacheResponse; +@synthesize redirectResponse = _redirectResponse; +@synthesize lock = _lock; + ++ (void)networkRequestThreadEntryPoint:(id __unused)object { + @autoreleasepool { + [[NSThread currentThread] setName:@"AFNetworking"]; + + NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; + [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; + [runLoop run]; + } +} + ++ (NSThread *)networkRequestThread { + static NSThread *_networkRequestThread = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoint:) object:nil]; + [_networkRequestThread start]; + }); + + return _networkRequestThread; +} + ++ (NSArray *)pinnedCertificates { + static NSArray *_pinnedCertificates = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSBundle *bundle = [NSBundle mainBundle]; + NSArray *paths = [bundle pathsForResourcesOfType:@"cer" inDirectory:@"."]; + + NSMutableArray *certificates = [NSMutableArray arrayWithCapacity:[paths count]]; + for (NSString *path in paths) { + NSData *certificateData = [NSData dataWithContentsOfFile:path]; + [certificates addObject:certificateData]; + } + + _pinnedCertificates = [[NSArray alloc] initWithArray:certificates]; + }); + + return _pinnedCertificates; +} + ++ (NSArray *)pinnedPublicKeys { + static NSArray *_pinnedPublicKeys = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + NSArray *pinnedCertificates = [self pinnedCertificates]; + NSMutableArray *publicKeys = [NSMutableArray arrayWithCapacity:[pinnedCertificates count]]; + + for (NSData *data in pinnedCertificates) { + SecCertificateRef allowedCertificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef)data); + NSParameterAssert(allowedCertificate); + + SecCertificateRef allowedCertificates[] = {allowedCertificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)allowedCertificates, 1, NULL); + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + SecTrustRef allowedTrust = NULL; + OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &allowedTrust); + NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); + if (status == errSecSuccess && allowedTrust) { + SecTrustResultType result = 0; + status = SecTrustEvaluate(allowedTrust, &result); + NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); + if (status == errSecSuccess) { + SecKeyRef allowedPublicKey = SecTrustCopyPublicKey(allowedTrust); + NSParameterAssert(allowedPublicKey); + if (allowedPublicKey) { + [publicKeys addObject:(__bridge_transfer id)allowedPublicKey]; + } + } + + CFRelease(allowedTrust); + } + + CFRelease(policy); + CFRelease(certificates); + CFRelease(allowedCertificate); + } + + _pinnedPublicKeys = [[NSArray alloc] initWithArray:publicKeys]; + }); + + return _pinnedPublicKeys; +} + +- (id)initWithRequest:(NSURLRequest *)urlRequest { + NSParameterAssert(urlRequest); + + self = [super init]; + if (!self) { + return nil; + } + + self.lock = [[NSRecursiveLock alloc] init]; + self.lock.name = kAFNetworkingLockName; + + self.runLoopModes = [NSSet setWithObject:NSRunLoopCommonModes]; + + self.request = urlRequest; + + self.shouldUseCredentialStorage = YES; + + // #ifdef included for backwards-compatibility +#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ + self.allowsInvalidSSLCertificate = YES; +#endif + + self.state = AFOperationReadyState; + + return self; +} + +- (void)dealloc { + if (_outputStream) { + [_outputStream close]; + _outputStream = nil; + } + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) + if (_backgroundTaskIdentifier) { + [[UIApplication sharedApplication] endBackgroundTask:_backgroundTaskIdentifier]; + _backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } +#endif +} + +- (NSString *)description { + return [NSString stringWithFormat:@"<%@: %p, state: %@, cancelled: %@ request: %@, response: %@>", NSStringFromClass([self class]), self, AFKeyPathFromOperationState(self.state), ([self isCancelled] ? @"YES" : @"NO"), self.request, self.response]; +} + +- (void)setCompletionBlock:(void (^)(void))block { + [self.lock lock]; + if (!block) { + [super setCompletionBlock:nil]; + } else { + __weak __typeof(&*self)weakSelf = self; + [super setCompletionBlock:^ { + __strong __typeof(&*weakSelf)strongSelf = weakSelf; + + block(); + [strongSelf setCompletionBlock:nil]; + }]; + } + [self.lock unlock]; +} + +- (NSInputStream *)inputStream { + return self.request.HTTPBodyStream; +} + +- (void)setInputStream:(NSInputStream *)inputStream { + [self willChangeValueForKey:@"inputStream"]; + NSMutableURLRequest *mutableRequest = [self.request mutableCopy]; + mutableRequest.HTTPBodyStream = inputStream; + self.request = mutableRequest; + [self didChangeValueForKey:@"inputStream"]; +} + +- (NSOutputStream *)outputStream { + if (!_outputStream) { + self.outputStream = [NSOutputStream outputStreamToMemory]; + } + + return _outputStream; +} + +- (void)setOutputStream:(NSOutputStream *)outputStream { + [self.lock lock]; + if (outputStream != _outputStream) { + [self willChangeValueForKey:@"outputStream"]; + if (_outputStream) { + [_outputStream close]; + } + _outputStream = outputStream; + [self didChangeValueForKey:@"outputStream"]; + } + [self.lock unlock]; +} + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +- (void)setShouldExecuteAsBackgroundTaskWithExpirationHandler:(void (^)(void))handler { + [self.lock lock]; + if (!self.backgroundTaskIdentifier) { + UIApplication *application = [UIApplication sharedApplication]; + __weak __typeof(&*self)weakSelf = self; + self.backgroundTaskIdentifier = [application beginBackgroundTaskWithExpirationHandler:^{ + __strong __typeof(&*weakSelf)strongSelf = weakSelf; + + if (handler) { + handler(); + } + + if (strongSelf) { + [strongSelf cancel]; + + [application endBackgroundTask:strongSelf.backgroundTaskIdentifier]; + strongSelf.backgroundTaskIdentifier = UIBackgroundTaskInvalid; + } + }]; + } + [self.lock unlock]; +} +#endif + +- (void)setUploadProgressBlock:(void (^)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite))block { + self.uploadProgress = block; +} + +- (void)setDownloadProgressBlock:(void (^)(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead))block { + self.downloadProgress = block; +} + +- (void)setWillSendRequestForAuthenticationChallengeBlock:(void (^)(NSURLConnection *connection, NSURLAuthenticationChallenge *challenge))block { + self.authenticationChallenge = block; +} + +- (void)setCacheResponseBlock:(NSCachedURLResponse * (^)(NSURLConnection *connection, NSCachedURLResponse *cachedResponse))block { + self.cacheResponse = block; +} + +- (void)setRedirectResponseBlock:(NSURLRequest * (^)(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse))block { + self.redirectResponse = block; +} + +- (void)setState:(AFOperationState)state { + if (!AFStateTransitionIsValid(self.state, state, [self isCancelled])) { + return; + } + + [self.lock lock]; + NSString *oldStateKey = AFKeyPathFromOperationState(self.state); + NSString *newStateKey = AFKeyPathFromOperationState(state); + + [self willChangeValueForKey:newStateKey]; + [self willChangeValueForKey:oldStateKey]; + _state = state; + [self didChangeValueForKey:oldStateKey]; + [self didChangeValueForKey:newStateKey]; + [self.lock unlock]; +} + +- (NSString *)responseString { + [self.lock lock]; + if (!_responseString && self.response && self.responseData) { + self.responseString = [[NSString alloc] initWithData:self.responseData encoding:self.responseStringEncoding]; + } + [self.lock unlock]; + + return _responseString; +} + +- (NSStringEncoding)responseStringEncoding { + [self.lock lock]; + if (!_responseStringEncoding && self.response) { + NSStringEncoding stringEncoding = NSUTF8StringEncoding; + if (self.response.textEncodingName) { + CFStringEncoding IANAEncoding = CFStringConvertIANACharSetNameToEncoding((__bridge CFStringRef)self.response.textEncodingName); + if (IANAEncoding != kCFStringEncodingInvalidId) { + stringEncoding = CFStringConvertEncodingToNSStringEncoding(IANAEncoding); + } + } + + self.responseStringEncoding = stringEncoding; + } + [self.lock unlock]; + + return _responseStringEncoding; +} + +- (void)pause { + if ([self isPaused] || [self isFinished] || [self isCancelled]) { + return; + } + + [self.lock lock]; + + if ([self isExecuting]) { + [self.connection performSelector:@selector(cancel) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; + + dispatch_async(dispatch_get_main_queue(), ^{ + NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; + [notificationCenter postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; + }); + } + + self.state = AFOperationPausedState; + + [self.lock unlock]; +} + +- (BOOL)isPaused { + return self.state == AFOperationPausedState; +} + +- (void)resume { + if (![self isPaused]) { + return; + } + + [self.lock lock]; + self.state = AFOperationReadyState; + + [self start]; + [self.lock unlock]; +} + +#pragma mark - NSOperation + +- (BOOL)isReady { + return self.state == AFOperationReadyState && [super isReady]; +} + +- (BOOL)isExecuting { + return self.state == AFOperationExecutingState; +} + +- (BOOL)isFinished { + return self.state == AFOperationFinishedState; +} + +- (BOOL)isConcurrent { + return YES; +} + +- (void)start { + [self.lock lock]; + if ([self isReady]) { + self.state = AFOperationExecutingState; + + [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; + } + [self.lock unlock]; +} + +- (void)operationDidStart { + [self.lock lock]; + if (![self isCancelled]) { + self.connection = [[NSURLConnection alloc] initWithRequest:self.request delegate:self startImmediately:NO]; + + NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; + for (NSString *runLoopMode in self.runLoopModes) { + [self.connection scheduleInRunLoop:runLoop forMode:runLoopMode]; + [self.outputStream scheduleInRunLoop:runLoop forMode:runLoopMode]; + } + + [self.connection start]; + } + [self.lock unlock]; + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidStartNotification object:self]; + }); + + if ([self isCancelled]) { + NSDictionary *userInfo = nil; + if ([self.request URL]) { + userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; + } + self.error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + + [self finish]; + } +} + +- (void)finish { + self.state = AFOperationFinishedState; + + dispatch_async(dispatch_get_main_queue(), ^{ + [[NSNotificationCenter defaultCenter] postNotificationName:AFNetworkingOperationDidFinishNotification object:self]; + }); +} + +- (void)cancel { + [self.lock lock]; + if (![self isFinished] && ![self isCancelled]) { + [self willChangeValueForKey:@"isCancelled"]; + _cancelled = YES; + [super cancel]; + [self didChangeValueForKey:@"isCancelled"]; + + // Cancel the connection on the thread it runs on to prevent race conditions + [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; + } + [self.lock unlock]; +} + +- (void)cancelConnection { + NSDictionary *userInfo = nil; + if ([self.request URL]) { + userInfo = [NSDictionary dictionaryWithObject:[self.request URL] forKey:NSURLErrorFailingURLErrorKey]; + } + NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo]; + + if (![self isFinished] && self.connection) { + [self.connection cancel]; + [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:error]; + } +} + +#pragma mark - NSURLConnectionDelegate + +- (void)connection:(NSURLConnection *)connection +willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge +{ + if (self.authenticationChallenge) { + self.authenticationChallenge(connection, challenge); + return; + } + + if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) { + SecTrustRef serverTrust = challenge.protectionSpace.serverTrust; + + SecPolicyRef policy = SecPolicyCreateBasicX509(); + CFIndex certificateCount = SecTrustGetCertificateCount(serverTrust); + NSMutableArray *trustChain = [NSMutableArray arrayWithCapacity:certificateCount]; + + for (CFIndex i = 0; i < certificateCount; i++) { + SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, i); + + if (self.SSLPinningMode == AFSSLPinningModeCertificate) { + [trustChain addObject:(__bridge_transfer NSData *)SecCertificateCopyData(certificate)]; + } else if (self.SSLPinningMode == AFSSLPinningModePublicKey) { + SecCertificateRef someCertificates[] = {certificate}; + CFArrayRef certificates = CFArrayCreate(NULL, (const void **)someCertificates, 1, NULL); + + SecTrustRef trust = NULL; + + OSStatus status = SecTrustCreateWithCertificates(certificates, policy, &trust); + NSAssert(status == errSecSuccess, @"SecTrustCreateWithCertificates error: %ld", (long int)status); + if (status == errSecSuccess && trust) { + SecTrustResultType result; + status = SecTrustEvaluate(trust, &result); + NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); + if (status == errSecSuccess) { + [trustChain addObject:(__bridge_transfer id)SecTrustCopyPublicKey(trust)]; + } + + CFRelease(trust); + } + + CFRelease(certificates); + } + } + + CFRelease(policy); + + switch (self.SSLPinningMode) { + case AFSSLPinningModePublicKey: { + NSArray *pinnedPublicKeys = [self.class pinnedPublicKeys]; + + for (id publicKey in trustChain) { + for (id pinnedPublicKey in pinnedPublicKeys) { + if (AFSecKeyIsEqualToKey((__bridge SecKeyRef)publicKey, (__bridge SecKeyRef)pinnedPublicKey)) { + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; + return; + } + } + } + + [[challenge sender] cancelAuthenticationChallenge:challenge]; + break; + } + case AFSSLPinningModeCertificate: { + for (id serverCertificateData in trustChain) { + if ([[self.class pinnedCertificates] containsObject:serverCertificateData]) { + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; + return; + } + } + + [[challenge sender] cancelAuthenticationChallenge:challenge]; + break; + } + case AFSSLPinningModeNone: { + if (self.allowsInvalidSSLCertificate){ + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; + } else { + SecTrustResultType result = 0; + OSStatus status = SecTrustEvaluate(serverTrust, &result); + NSAssert(status == errSecSuccess, @"SecTrustEvaluate error: %ld", (long int)status); + + if (status == errSecSuccess && (result == kSecTrustResultUnspecified || result == kSecTrustResultProceed)) { + NSURLCredential *credential = [NSURLCredential credentialForTrust:serverTrust]; + [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; + } else { + [[challenge sender] cancelAuthenticationChallenge:challenge]; + } + } + break; + } + } + } else { + if ([challenge previousFailureCount] == 0) { + if (self.credential) { + [[challenge sender] useCredential:self.credential forAuthenticationChallenge:challenge]; + } else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } else { + [[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge]; + } + } +} + +- (BOOL)connectionShouldUseCredentialStorage:(NSURLConnection __unused *)connection { + return self.shouldUseCredentialStorage; +} + +- (NSURLRequest *)connection:(NSURLConnection *)connection + willSendRequest:(NSURLRequest *)request + redirectResponse:(NSURLResponse *)redirectResponse +{ + if (self.redirectResponse) { + return self.redirectResponse(connection, request, redirectResponse); + } else { + return request; + } +} + +- (void)connection:(NSURLConnection __unused *)connection + didSendBodyData:(NSInteger)bytesWritten + totalBytesWritten:(NSInteger)totalBytesWritten +totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite +{ + if (self.uploadProgress) { + dispatch_async(dispatch_get_main_queue(), ^{ + self.uploadProgress((NSUInteger)bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); + }); + } +} + +- (void)connection:(NSURLConnection __unused *)connection +didReceiveResponse:(NSURLResponse *)response +{ + self.response = response; + + [self.outputStream open]; +} + +- (void)connection:(NSURLConnection __unused *)connection + didReceiveData:(NSData *)data +{ + NSUInteger length = [data length]; + while (YES) { + NSUInteger totalNumberOfBytesWritten = 0; + if ([self.outputStream hasSpaceAvailable]) { + const uint8_t *dataBuffer = (uint8_t *)[data bytes]; + + NSInteger numberOfBytesWritten = 0; + while (totalNumberOfBytesWritten < length) { + numberOfBytesWritten = [self.outputStream write:&dataBuffer[0] maxLength:length]; + if (numberOfBytesWritten == -1) { + [self.connection cancel]; + [self performSelector:@selector(connection:didFailWithError:) withObject:self.connection withObject:self.outputStream.streamError]; + return; + } else { + totalNumberOfBytesWritten += numberOfBytesWritten; + } + } + + break; + } + } + + dispatch_async(dispatch_get_main_queue(), ^{ + self.totalBytesRead += length; + + if (self.downloadProgress) { + self.downloadProgress(length, self.totalBytesRead, self.response.expectedContentLength); + } + }); +} + +- (void)connectionDidFinishLoading:(NSURLConnection __unused *)connection { + self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey]; + + [self.outputStream close]; + + [self finish]; + + self.connection = nil; +} + +- (void)connection:(NSURLConnection __unused *)connection + didFailWithError:(NSError *)error +{ + self.error = error; + + [self.outputStream close]; + + [self finish]; + + self.connection = nil; +} + +- (NSCachedURLResponse *)connection:(NSURLConnection *)connection + willCacheResponse:(NSCachedURLResponse *)cachedResponse +{ + if (self.cacheResponse) { + return self.cacheResponse(connection, cachedResponse); + } else { + if ([self isCancelled]) { + return nil; + } + + return cachedResponse; + } +} + +#pragma mark - NSCoding + +- (id)initWithCoder:(NSCoder *)aDecoder { + NSURLRequest *request = [aDecoder decodeObjectForKey:@"request"]; + + self = [self initWithRequest:request]; + if (!self) { + return nil; + } + + self.state = (AFOperationState)[aDecoder decodeIntegerForKey:@"state"]; + self.cancelled = [aDecoder decodeBoolForKey:@"isCancelled"]; + self.response = [aDecoder decodeObjectForKey:@"response"]; + self.error = [aDecoder decodeObjectForKey:@"error"]; + self.responseData = [aDecoder decodeObjectForKey:@"responseData"]; + self.totalBytesRead = [[aDecoder decodeObjectForKey:@"totalBytesRead"] longLongValue]; + self.allowsInvalidSSLCertificate = [[aDecoder decodeObjectForKey:@"allowsInvalidSSLCertificate"] boolValue]; + + return self; +} + +- (void)encodeWithCoder:(NSCoder *)aCoder { + [self pause]; + + [aCoder encodeObject:self.request forKey:@"request"]; + + switch (self.state) { + case AFOperationExecutingState: + case AFOperationPausedState: + [aCoder encodeInteger:AFOperationReadyState forKey:@"state"]; + break; + default: + [aCoder encodeInteger:self.state forKey:@"state"]; + break; + } + + [aCoder encodeBool:[self isCancelled] forKey:@"isCancelled"]; + [aCoder encodeObject:self.response forKey:@"response"]; + [aCoder encodeObject:self.error forKey:@"error"]; + [aCoder encodeObject:self.responseData forKey:@"responseData"]; + [aCoder encodeObject:[NSNumber numberWithLongLong:self.totalBytesRead] forKey:@"totalBytesRead"]; + [aCoder encodeObject:[NSNumber numberWithBool:self.allowsInvalidSSLCertificate] forKey:@"allowsInvalidSSLCertificate"]; +} + +#pragma mark - NSCopying + +- (id)copyWithZone:(NSZone *)zone { + AFURLConnectionOperation *operation = [(AFURLConnectionOperation *)[[self class] allocWithZone:zone] initWithRequest:self.request]; + + operation.uploadProgress = self.uploadProgress; + operation.downloadProgress = self.downloadProgress; + operation.authenticationChallenge = self.authenticationChallenge; + operation.cacheResponse = self.cacheResponse; + operation.redirectResponse = self.redirectResponse; + operation.allowsInvalidSSLCertificate = self.allowsInvalidSSLCertificate; + + return operation; +} + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h new file mode 100644 index 00000000000..4130932e698 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.h @@ -0,0 +1,89 @@ +// AFXMLRequestOperation.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFHTTPRequestOperation.h" + +#import + +/** + `AFXMLRequestOperation` is a subclass of `AFHTTPRequestOperation` for downloading and working with XML response data. + + ## Acceptable Content Types + + By default, `AFXMLRequestOperation` accepts the following MIME types, which includes the official standard, `application/xml`, as well as other commonly-used types: + + - `application/xml` + - `text/xml` + + ## Use With AFHTTPClient + + When `AFXMLRequestOperation` is registered with `AFHTTPClient`, the response object in the success callback of `HTTPRequestOperationWithRequest:success:failure:` will be an instance of `NSXMLParser`. On platforms that support `NSXMLDocument`, you have the option to ignore the response object, and simply use the `responseXMLDocument` property of the operation argument of the callback. + */ +@interface AFXMLRequestOperation : AFHTTPRequestOperation + +///---------------------------- +/// @name Getting Response Data +///---------------------------- + +/** + An `NSXMLParser` object constructed from the response data. + */ +@property (readonly, nonatomic, strong) NSXMLParser *responseXMLParser; + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +/** + An `NSXMLDocument` object constructed from the response data. If an error occurs while parsing, `nil` will be returned, and the `error` property will be set to the error. + */ +@property (readonly, nonatomic, strong) NSXMLDocument *responseXMLDocument; +#endif + +/** + Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation + @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML parser constructed with the response data of request. + @param failure A block object to be executed when the operation finishes unsuccessfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network error that occurred. + + @return A new XML request operation + */ ++ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure; + + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +/** + Creates and returns an `AFXMLRequestOperation` object and sets the specified success and failure callbacks. + + @param urlRequest The request object to be loaded asynchronously during execution of the operation + @param success A block object to be executed when the operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the XML document created from the response data of request. + @param failure A block object to be executed when the operation finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data as XML. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error describing the network or parsing error that occurred. + + @return A new XML request operation + */ ++ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure; +#endif + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m new file mode 100644 index 00000000000..a97cd88478d --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/AFXMLRequestOperation.m @@ -0,0 +1,167 @@ +// AFXMLRequestOperation.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import "AFXMLRequestOperation.h" + +#include + +static dispatch_queue_t xml_request_operation_processing_queue() { + static dispatch_queue_t af_xml_request_operation_processing_queue; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + af_xml_request_operation_processing_queue = dispatch_queue_create("com.alamofire.networking.xml-request.processing", DISPATCH_QUEUE_CONCURRENT); + }); + + return af_xml_request_operation_processing_queue; +} + +@interface AFXMLRequestOperation () +@property (readwrite, nonatomic, strong) NSXMLParser *responseXMLParser; +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +@property (readwrite, nonatomic, strong) NSXMLDocument *responseXMLDocument; +#endif +@property (readwrite, nonatomic, strong) NSError *XMLError; +@end + +@implementation AFXMLRequestOperation +@synthesize responseXMLParser = _responseXMLParser; +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +@synthesize responseXMLDocument = _responseXMLDocument; +#endif +@synthesize XMLError = _XMLError; + ++ (instancetype)XMLParserRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLParser *XMLParser))failure +{ + AFXMLRequestOperation *requestOperation = [(AFXMLRequestOperation *)[self alloc] initWithRequest:urlRequest]; + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + if (success) { + success(operation.request, operation.response, responseObject); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if (failure) { + failure(operation.request, operation.response, error, [(AFXMLRequestOperation *)operation responseXMLParser]); + } + }]; + + return requestOperation; +} + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED ++ (instancetype)XMLDocumentRequestOperationWithRequest:(NSURLRequest *)urlRequest + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLDocument *document))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, NSXMLDocument *document))failure +{ + AFXMLRequestOperation *requestOperation = [[self alloc] initWithRequest:urlRequest]; + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, __unused id responseObject) { + if (success) { + NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; + success(operation.request, operation.response, XMLDocument); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if (failure) { + NSXMLDocument *XMLDocument = [(AFXMLRequestOperation *)operation responseXMLDocument]; + failure(operation.request, operation.response, error, XMLDocument); + } + }]; + + return requestOperation; +} +#endif + + +- (NSXMLParser *)responseXMLParser { + if (!_responseXMLParser && [self.responseData length] > 0 && [self isFinished]) { + self.responseXMLParser = [[NSXMLParser alloc] initWithData:self.responseData]; + } + + return _responseXMLParser; +} + +#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED +- (NSXMLDocument *)responseXMLDocument { + if (!_responseXMLDocument && [self.responseData length] > 0 && [self isFinished]) { + NSError *error = nil; + self.responseXMLDocument = [[NSXMLDocument alloc] initWithData:self.responseData options:0 error:&error]; + self.XMLError = error; + } + + return _responseXMLDocument; +} +#endif + +- (NSError *)error { + if (_XMLError) { + return _XMLError; + } else { + return [super error]; + } +} + +#pragma mark - NSOperation + +- (void)cancel { + [super cancel]; + + self.responseXMLParser.delegate = nil; +} + +#pragma mark - AFHTTPRequestOperation + ++ (NSSet *)acceptableContentTypes { + return [NSSet setWithObjects:@"application/xml", @"text/xml", nil]; +} + ++ (BOOL)canProcessRequest:(NSURLRequest *)request { + return [[[request URL] pathExtension] isEqualToString:@"xml"] || [super canProcessRequest:request]; +} + +- (void)setCompletionBlockWithSuccess:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success + failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure +{ +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Warc-retain-cycles" +#pragma clang diagnostic ignored "-Wgnu" + self.completionBlock = ^ { + dispatch_async(xml_request_operation_processing_queue(), ^(void) { + NSXMLParser *XMLParser = self.responseXMLParser; + + if (self.error) { + if (failure) { + dispatch_async(self.failureCallbackQueue ?: dispatch_get_main_queue(), ^{ + failure(self, self.error); + }); + } + } else { + if (success) { + dispatch_async(self.successCallbackQueue ?: dispatch_get_main_queue(), ^{ + success(self, XMLParser); + }); + } + } + }); + }; +#pragma clang diagnostic pop +} + +@end diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h new file mode 100644 index 00000000000..bafb7901ea7 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1,78 @@ +// UIImageView+AFNetworking.h +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import "AFImageRequestOperation.h" + +#import + +#if __IPHONE_OS_VERSION_MIN_REQUIRED +#import + +/** + This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. + */ +@interface UIImageView (AFNetworking) + +/** + Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL, and sets it the request is finished. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + */ +- (void)setImageWithURL:(NSURL *)url; + +/** + Creates and enqueues an image request operation, which asynchronously downloads the image from the specified URL. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + By default, URL requests have a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` + + @param url The URL used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + */ +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage; + +/** + Creates and enqueues an image request operation, which asynchronously downloads the image with the specified URL request object. Any previous image request for the receiver will be cancelled. If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. + + If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is executed. + + @param urlRequest The URL request used for the image request. + @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. + @param success A block to be executed when the image request operation finishes successfully, with a status code in the 2xx range, and with an acceptable content type (e.g. `image/png`). This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`. + @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. + */ +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure; + +/** + Cancels any executing image request operation for the receiver, if one exists. + */ +- (void)cancelImageRequestOperation; + +@end + +#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m new file mode 100644 index 00000000000..839a2b85722 --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/AFNetworking/UIImageView+AFNetworking.m @@ -0,0 +1,191 @@ +// UIImageView+AFNetworking.m +// +// Copyright (c) 2011 Gowalla (http://gowalla.com/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +#import +#import + +#if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) +#import "UIImageView+AFNetworking.h" + +@interface AFImageCache : NSCache +- (UIImage *)cachedImageForRequest:(NSURLRequest *)request; +- (void)cacheImage:(UIImage *)image + forRequest:(NSURLRequest *)request; +@end + +#pragma mark - + +static char kAFImageRequestOperationObjectKey; + +@interface UIImageView (_AFNetworking) +@property (readwrite, nonatomic, strong, setter = af_setImageRequestOperation:) AFImageRequestOperation *af_imageRequestOperation; +@end + +@implementation UIImageView (_AFNetworking) +@dynamic af_imageRequestOperation; +@end + +#pragma mark - + +@implementation UIImageView (AFNetworking) + +- (AFHTTPRequestOperation *)af_imageRequestOperation { + return (AFHTTPRequestOperation *)objc_getAssociatedObject(self, &kAFImageRequestOperationObjectKey); +} + +- (void)af_setImageRequestOperation:(AFImageRequestOperation *)imageRequestOperation { + objc_setAssociatedObject(self, &kAFImageRequestOperationObjectKey, imageRequestOperation, OBJC_ASSOCIATION_RETAIN_NONATOMIC); +} + ++ (NSOperationQueue *)af_sharedImageRequestOperationQueue { + static NSOperationQueue *_af_imageRequestOperationQueue = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + _af_imageRequestOperationQueue = [[NSOperationQueue alloc] init]; + [_af_imageRequestOperationQueue setMaxConcurrentOperationCount:NSOperationQueueDefaultMaxConcurrentOperationCount]; + }); + + return _af_imageRequestOperationQueue; +} + ++ (AFImageCache *)af_sharedImageCache { + static AFImageCache *_af_imageCache = nil; + static dispatch_once_t oncePredicate; + dispatch_once(&oncePredicate, ^{ + _af_imageCache = [[AFImageCache alloc] init]; + }); + + return _af_imageCache; +} + +#pragma mark - + +- (void)setImageWithURL:(NSURL *)url { + [self setImageWithURL:url placeholderImage:nil]; +} + +- (void)setImageWithURL:(NSURL *)url + placeholderImage:(UIImage *)placeholderImage +{ + NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; + [request addValue:@"image/*" forHTTPHeaderField:@"Accept"]; + + [self setImageWithURLRequest:request placeholderImage:placeholderImage success:nil failure:nil]; +} + +- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest + placeholderImage:(UIImage *)placeholderImage + success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success + failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure +{ + [self cancelImageRequestOperation]; + + UIImage *cachedImage = [[[self class] af_sharedImageCache] cachedImageForRequest:urlRequest]; + if (cachedImage) { + self.af_imageRequestOperation = nil; + + if (success) { + success(nil, nil, cachedImage); + } else { + self.image = cachedImage; + } + } else { + if (placeholderImage) { + self.image = placeholderImage; + } + + AFImageRequestOperation *requestOperation = [[AFImageRequestOperation alloc] initWithRequest:urlRequest]; + +#ifdef _AFNETWORKING_ALLOW_INVALID_SSL_CERTIFICATES_ + requestOperation.allowsInvalidSSLCertificate = YES; +#endif + + [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { + if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) { + if (self.af_imageRequestOperation == operation) { + self.af_imageRequestOperation = nil; + } + + if (success) { + success(operation.request, operation.response, responseObject); + } else if (responseObject) { + self.image = responseObject; + } + } + + [[[self class] af_sharedImageCache] cacheImage:responseObject forRequest:urlRequest]; + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if ([urlRequest isEqual:[self.af_imageRequestOperation request]]) { + if (self.af_imageRequestOperation == operation) { + self.af_imageRequestOperation = nil; + } + + if (failure) { + failure(operation.request, operation.response, error); + } + } + }]; + + self.af_imageRequestOperation = requestOperation; + + [[[self class] af_sharedImageRequestOperationQueue] addOperation:self.af_imageRequestOperation]; + } +} + +- (void)cancelImageRequestOperation { + [self.af_imageRequestOperation cancel]; + self.af_imageRequestOperation = nil; +} + +@end + +#pragma mark - + +static inline NSString * AFImageCacheKeyFromURLRequest(NSURLRequest *request) { + return [[request URL] absoluteString]; +} + +@implementation AFImageCache + +- (UIImage *)cachedImageForRequest:(NSURLRequest *)request { + switch ([request cachePolicy]) { + case NSURLRequestReloadIgnoringCacheData: + case NSURLRequestReloadIgnoringLocalAndRemoteCacheData: + return nil; + default: + break; + } + + return [self objectForKey:AFImageCacheKeyFromURLRequest(request)]; +} + +- (void)cacheImage:(UIImage *)image + forRequest:(NSURLRequest *)request +{ + if (image && request) { + [self setObject:image forKey:AFImageCacheKeyFromURLRequest(request)]; + } +} + +@end + +#endif diff --git a/samples/client/petstore/objc/Pods/AFNetworking/LICENSE b/samples/client/petstore/objc/Pods/AFNetworking/LICENSE new file mode 100644 index 00000000000..42d32adadad --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/LICENSE @@ -0,0 +1,19 @@ +Copyright (c) 2011 Gowalla (http://gowalla.com/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/samples/client/petstore/objc/Pods/AFNetworking/README.md b/samples/client/petstore/objc/Pods/AFNetworking/README.md new file mode 100644 index 00000000000..4d2f226d4eb --- /dev/null +++ b/samples/client/petstore/objc/Pods/AFNetworking/README.md @@ -0,0 +1,208 @@ +

+ AFNetworking +

+ +[![Build Status](https://travis-ci.org/AFNetworking/AFNetworking.png?branch=master)](https://travis-ci.org/AFNetworking/AFNetworking) + +AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of [NSURLConnection](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/Reference/Reference.html), [NSOperation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/NSOperation_class/Reference/Reference.html), and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. For example, here's how easy it is to get JSON from a URL: + +```objective-c +NSURL *url = [NSURL URLWithString:@"https://alpha-api.app.net/stream/0/posts/stream/global"]; +NSURLRequest *request = [NSURLRequest requestWithURL:url]; +AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { + NSLog(@"App.net Global Stream: %@", JSON); +} failure:nil]; +[operation start]; +``` + +Perhaps the most important feature of all, however, is the amazing community of developers who use and contribute to AFNetworking every day. AFNetworking powers some of the most popular and critically-acclaimed apps on the iPhone, iPad, and Mac. + +Choose AFNetworking for your next project, or migrate over your existing projects—you'll be happy you did! + +## How To Get Started + +- [Download AFNetworking](https://github.com/AFNetworking/AFNetworking/zipball/master) and try out the included Mac and iPhone example apps +- Read the ["Getting Started" guide](https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking), [FAQ](https://github.com/AFNetworking/AFNetworking/wiki/AFNetworking-FAQ), or [other articles in the wiki](https://github.com/AFNetworking/AFNetworking/wiki) +- Check out the [complete documentation](http://cocoadocs.org/docsets/AFNetworking/) for a comprehensive look at the APIs available in AFNetworking +- Watch the [NSScreencast episode about AFNetworking](http://nsscreencast.com/episodes/6-afnetworking) for a quick introduction to how to use it in your application +- Questions? [Stack Overflow](http://stackoverflow.com/questions/tagged/afnetworking) is the best place to find answers + +## Overview + +AFNetworking is architected to be as small and modular as possible, in order to make it simple to use and extend. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Core
AFURLConnectionOperationAn NSOperation that implements the NSURLConnection delegate methods.
HTTP Requests
AFHTTPRequestOperationA subclass of AFURLConnectionOperation for requests using the HTTP or HTTPS protocols. It encapsulates the concept of acceptable status codes and content types, which determine the success or failure of a request.
AFJSONRequestOperationA subclass of AFHTTPRequestOperation for downloading and working with JSON response data.
AFXMLRequestOperationA subclass of AFHTTPRequestOperation for downloading and working with XML response data.
AFPropertyListRequestOperationA subclass of AFHTTPRequestOperation for downloading and deserializing objects with property list response data.
HTTP Client
AFHTTPClient + Captures the common patterns of communicating with an web application over HTTP, including: + +
    +
  • Making requests from relative paths of a base URL
  • +
  • Setting HTTP headers to be added automatically to requests
  • +
  • Authenticating requests with HTTP Basic credentials or an OAuth token
  • +
  • Managing an NSOperationQueue for requests made by the client
  • +
  • Generating query strings or HTTP bodies from an NSDictionary
  • +
  • Constructing multipart form requests
  • +
  • Automatically parsing HTTP response data into its corresponding object representation
  • +
  • Monitoring and responding to changes in network reachability
  • +
+
Images
AFImageRequestOperationA subclass of AFHTTPRequestOperation for downloading and processing images.
UIImageView+AFNetworkingAdds methods to UIImageView for loading remote images asynchronously from a URL.
+ +## Example Usage + +### XML Request + +```objective-c +NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://api.flickr.com/services/rest/?method=flickr.groups.browse&api_key=b6300e17ad3c506e706cb0072175d047&cat_id=34427469792%40N01&format=rest"]]; +AFXMLRequestOperation *operation = [AFXMLRequestOperation XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) { + XMLParser.delegate = self; + [XMLParser parse]; +} failure:nil]; +[operation start]; +``` + +### Image Request + +```objective-c +UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)]; +[imageView setImageWithURL:[NSURL URLWithString:@"http://i.imgur.com/r4uwx.jpg"] placeholderImage:[UIImage imageNamed:@"placeholder-avatar"]]; +``` + +### API Client Request + +```objective-c +// AFAppDotNetAPIClient is a subclass of AFHTTPClient, which defines the base URL and default HTTP headers for NSURLRequests it creates +[[AFAppDotNetAPIClient sharedClient] getPath:@"stream/0/posts/stream/global" parameters:nil success:^(AFHTTPRequestOperation *operation, id JSON) { + NSLog(@"App.net Global Stream: %@", JSON); +} failure:nil]; +``` + +### File Upload with Progress Callback + +```objective-c +NSURL *url = [NSURL URLWithString:@"http://api-base-url.com"]; +AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url]; +NSData *imageData = UIImageJPEGRepresentation([UIImage imageNamed:@"avatar.jpg"], 0.5); +NSMutableURLRequest *request = [httpClient multipartFormRequestWithMethod:@"POST" path:@"/upload" parameters:nil constructingBodyWithBlock: ^(id formData) { + [formData appendPartWithFileData:imageData name:@"avatar" fileName:@"avatar.jpg" mimeType:@"image/jpeg"]; +}]; + +AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; +[operation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) { + NSLog(@"Sent %lld of %lld bytes", totalBytesWritten, totalBytesExpectedToWrite); +}]; +[httpClient enqueueHTTPRequestOperation:operation]; +``` + +### Streaming Request + +```objective-c +NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080/encode"]]; + +AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; +operation.inputStream = [NSInputStream inputStreamWithFileAtPath:[[NSBundle mainBundle] pathForResource:@"large-image" ofType:@"tiff"]]; +operation.outputStream = [NSOutputStream outputStreamToMemory]; +[operation start]; +``` + +## Requirements + +AFNetworking 1.0 and higher requires either [iOS 5.0](http://developer.apple.com/library/ios/#releasenotes/General/WhatsNewIniPhoneOS/Articles/iPhoneOS4.html) and above, or [Mac OS 10.7](http://developer.apple.com/library/mac/#releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_6.html#//apple_ref/doc/uid/TP40008898-SW7) ([64-bit with modern Cocoa runtime](https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtVersionsPlatforms.html)) and above. + +For compatibility with iOS 4.3, use the latest 0.10.x release. + +### ARC + +AFNetworking uses ARC as of its 1.0 release. + +If you are using AFNetworking 1.0 in your non-arc project, you will need to set a `-fobjc-arc` compiler flag on all of the AFNetworking source files. Conversely, if you are adding a pre-1.0 version of AFNetworking, you will need to set a `-fno-objc-arc` compiler flag. + +To set a compiler flag in Xcode, go to your active target and select the "Build Phases" tab. Now select all AFNetworking source files, press Enter, insert `-fobjc-arc` or `-fno-objc-arc` and then "Done" to enable or disable ARC for AFNetworking. + +## Unit Tests + +AFNetworking includes a suite of unit tests within the Tests subdirectory. In order to run the unit tests, you must install the testing dependencies via CocoaPods. To do so: + + $ gem install cocoapods # If necessary + $ cd Tests + $ pod install + +Once CocoaPods has finished the installation, you can execute the test suite via the 'iOS Tests' and 'OS X Tests' schemes within Xcode. + +### Test Logging + +By default, the unit tests do not emit any output during execution. For debugging purposes, it can be useful to enable logging of the requests and responses. Logging support is provided by the [AFHTTPRequestOperationLogger](https://github.com/AFNetworking/AFHTTPRequestOperationLogger) extension, which is installed via CocoaPods into the test targets. To enable logging, edit the test Scheme and add an environment variable named `AFTestsLoggingEnabled` with a value of `YES`. + +### Using xctool + +If you wish to execute the tests from the command line or within a continuous integration environment, you will need to install [xctool](https://github.com/facebook/xctool). The recommended installation method is [Homebrew](http://mxcl.github.io/homebrew/). + +To install the commandline testing support via Homebrew: + + $ brew update + $ brew install xctool --HEAD + +Once xctool is installed, you can execute the suite via `rake test`. + +## Credits + +AFNetworking was created by [Scott Raymond](https://github.com/sco/) and [Mattt Thompson](https://github.com/mattt/) in the development of [Gowalla for iPhone](http://en.wikipedia.org/wiki/Gowalla). + +AFNetworking's logo was designed by [Alan Defibaugh](http://www.alandefibaugh.com/). + +And most of all, thanks to AFNetworking's [growing list of contributors](https://github.com/AFNetworking/AFNetworking/contributors). + +## Contact + +Follow AFNetworking on Twitter ([@AFNetworking](https://twitter.com/AFNetworking)) + +### Creators + +[Mattt Thompson](http://github.com/mattt) +[@mattt](https://twitter.com/mattt) + +[Scott Raymond](http://github.com/sco) +[@sco](https://twitter.com/sco) + +## License + +AFNetworking is available under the MIT license. See the LICENSE file for more info. diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h new file mode 120000 index 00000000000..a88168d71da --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPClient.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFHTTPClient.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h new file mode 120000 index 00000000000..d51daed27c1 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFHTTPRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h new file mode 120000 index 00000000000..f7c5e913d35 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFImageRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFImageRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h new file mode 120000 index 00000000000..4dd9622727f --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFJSONRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFJSONRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 120000 index 00000000000..a09102c76d0 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h new file mode 120000 index 00000000000..83dd518f7b2 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFNetworking.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h new file mode 120000 index 00000000000..fb82b5c5706 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFPropertyListRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h new file mode 120000 index 00000000000..360459d4c03 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFURLConnectionOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h new file mode 120000 index 00000000000..c5c354bbcb2 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/AFXMLRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFXMLRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h new file mode 120000 index 00000000000..7c7e6c38e96 --- /dev/null +++ b/samples/client/petstore/objc/Pods/BuildHeaders/AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h new file mode 120000 index 00000000000..a88168d71da --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPClient.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFHTTPClient.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h new file mode 120000 index 00000000000..d51daed27c1 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFHTTPRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFHTTPRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h new file mode 120000 index 00000000000..f7c5e913d35 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFImageRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFImageRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h new file mode 120000 index 00000000000..4dd9622727f --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFJSONRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFJSONRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h new file mode 120000 index 00000000000..a09102c76d0 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworkActivityIndicatorManager.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFNetworkActivityIndicatorManager.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h new file mode 120000 index 00000000000..83dd518f7b2 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFNetworking.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h new file mode 120000 index 00000000000..fb82b5c5706 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFPropertyListRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFPropertyListRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h new file mode 120000 index 00000000000..360459d4c03 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFURLConnectionOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFURLConnectionOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h new file mode 120000 index 00000000000..c5c354bbcb2 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/AFXMLRequestOperation.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/AFXMLRequestOperation.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h b/samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h new file mode 120000 index 00000000000..7c7e6c38e96 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Headers/AFNetworking/UIImageView+AFNetworking.h @@ -0,0 +1 @@ +../../AFNetworking/AFNetworking/UIImageView+AFNetworking.h \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Manifest.lock b/samples/client/petstore/objc/Pods/Manifest.lock new file mode 100644 index 00000000000..f52a69324db --- /dev/null +++ b/samples/client/petstore/objc/Pods/Manifest.lock @@ -0,0 +1,10 @@ +PODS: + - AFNetworking (1.3.3) + +DEPENDENCIES: + - AFNetworking (~> 1.0) + +SPEC CHECKSUMS: + AFNetworking: 0700ec7a58c36ad217173e167f6e4df7270df66b + +COCOAPODS: 0.25.0 diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig b/samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig new file mode 100644 index 00000000000..af8cfd47a49 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-AFNetworking-Private.xcconfig @@ -0,0 +1,5 @@ +#include "Pods-AFNetworking.xcconfig" +GCC_PREPROCESSOR_DEFINITIONS = COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/BuildHeaders" "${PODS_ROOT}/BuildHeaders/AFNetworking" "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking" +OTHER_LDFLAGS = -ObjC ${PODS_AFNETWORKING_OTHER_LDFLAGS} +PODS_ROOT = ${SRCROOT} \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m b/samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m new file mode 100644 index 00000000000..c50a8c61689 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-AFNetworking-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods_AFNetworking : NSObject +@end +@implementation PodsDummy_Pods_AFNetworking +@end diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch b/samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch new file mode 100644 index 00000000000..133fd577e8e --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-AFNetworking-prefix.pch @@ -0,0 +1,19 @@ +#ifdef __OBJC__ +#import +#endif + +#import "Pods-environment.h" +#import + +#define _AFNETWORKING_PIN_SSL_CERTIFICATES_ + +#if __IPHONE_OS_VERSION_MIN_REQUIRED + #import + #import + #import +#else + #import + #import + #import +#endif + diff --git a/samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig b/samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig new file mode 100644 index 00000000000..13e3dff0366 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-AFNetworking.xcconfig @@ -0,0 +1 @@ +PODS_AFNETWORKING_OTHER_LDFLAGS = -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown b/samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown new file mode 100644 index 00000000000..0a417941f21 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-acknowledgements.markdown @@ -0,0 +1,26 @@ +# Acknowledgements +This application makes use of the following third party libraries: + +## AFNetworking + +Copyright (c) 2011 Gowalla (http://gowalla.com/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +Generated by CocoaPods - http://cocoapods.org diff --git a/samples/client/petstore/objc/Pods/Pods-acknowledgements.plist b/samples/client/petstore/objc/Pods/Pods-acknowledgements.plist new file mode 100644 index 00000000000..0c9d23f5fad --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-acknowledgements.plist @@ -0,0 +1,56 @@ + + + + + PreferenceSpecifiers + + + FooterText + This application makes use of the following third party libraries: + Title + Acknowledgements + Type + PSGroupSpecifier + + + FooterText + Copyright (c) 2011 Gowalla (http://gowalla.com/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + Title + AFNetworking + Type + PSGroupSpecifier + + + FooterText + Generated by CocoaPods - http://cocoapods.org + Title + + Type + PSGroupSpecifier + + + StringsTable + Acknowledgements + Title + Acknowledgements + + diff --git a/samples/client/petstore/objc/Pods/Pods-dummy.m b/samples/client/petstore/objc/Pods/Pods-dummy.m new file mode 100644 index 00000000000..ade64bd1a9b --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-dummy.m @@ -0,0 +1,5 @@ +#import +@interface PodsDummy_Pods : NSObject +@end +@implementation PodsDummy_Pods +@end diff --git a/samples/client/petstore/objc/Pods/Pods-environment.h b/samples/client/petstore/objc/Pods/Pods-environment.h new file mode 100644 index 00000000000..17dfbefd837 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-environment.h @@ -0,0 +1,14 @@ + +// To check if a library is compiled with CocoaPods you +// can use the `COCOAPODS` macro definition which is +// defined in the xcconfigs so it is available in +// headers also when they are imported in the client +// project. + + +// AFNetworking +#define COCOAPODS_POD_AVAILABLE_AFNetworking +#define COCOAPODS_VERSION_MAJOR_AFNetworking 1 +#define COCOAPODS_VERSION_MINOR_AFNetworking 3 +#define COCOAPODS_VERSION_PATCH_AFNetworking 3 + diff --git a/samples/client/petstore/objc/Pods/Pods-resources.sh b/samples/client/petstore/objc/Pods/Pods-resources.sh new file mode 100755 index 00000000000..d6513b83d87 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods-resources.sh @@ -0,0 +1,47 @@ +#!/bin/sh +set -e + +RESOURCES_TO_COPY=${PODS_ROOT}/resources-to-copy-${TARGETNAME}.txt +> "$RESOURCES_TO_COPY" + +install_resource() +{ + case $1 in + *.storyboard) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc ${PODS_ROOT}/$1 --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .storyboard`.storyboardc" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" + ;; + *.xib) + echo "ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile ${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib ${PODS_ROOT}/$1 --sdk ${SDKROOT}" + ibtool --reference-external-strings-file --errors --warnings --notices --output-format human-readable-text --compile "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename \"$1\" .xib`.nib" "${PODS_ROOT}/$1" --sdk "${SDKROOT}" + ;; + *.framework) + echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + echo "rsync -av ${PODS_ROOT}/$1 ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + rsync -av "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}" + ;; + *.xcdatamodel) + echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1"`.mom\"" + xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodel`.mom" + ;; + *.xcdatamodeld) + echo "xcrun momc \"${PODS_ROOT}/$1\" \"${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd\"" + xcrun momc "${PODS_ROOT}/$1" "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}/`basename "$1" .xcdatamodeld`.momd" + ;; + /*) + echo "$1" + echo "$1" >> "$RESOURCES_TO_COPY" + ;; + *) + echo "${PODS_ROOT}/$1" + echo "${PODS_ROOT}/$1" >> "$RESOURCES_TO_COPY" + ;; + esac +} + +rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${CONFIGURATION_BUILD_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +if [[ "${ACTION}" == "install" ]]; then + rsync -avr --copy-links --no-relative --exclude '*/.svn/*' --files-from="$RESOURCES_TO_COPY" / "${INSTALL_DIR}/${UNLOCALIZED_RESOURCES_FOLDER_PATH}" +fi +rm -f "$RESOURCES_TO_COPY" diff --git a/samples/client/petstore/objc/Pods/Pods.xcconfig b/samples/client/petstore/objc/Pods/Pods.xcconfig new file mode 100644 index 00000000000..c06def56661 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods.xcconfig @@ -0,0 +1,4 @@ +GCC_PREPROCESSOR_DEFINITIONS = $(inherited) COCOAPODS=1 +HEADER_SEARCH_PATHS = "${PODS_ROOT}/Headers" "${PODS_ROOT}/Headers/AFNetworking" +OTHER_LDFLAGS = -ObjC -framework CoreGraphics -framework MobileCoreServices -framework Security -framework SystemConfiguration +PODS_ROOT = ${SRCROOT}/../Pods \ No newline at end of file diff --git a/samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj b/samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj new file mode 100644 index 00000000000..1a2a2a848a2 --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods.xcodeproj/project.pbxproj @@ -0,0 +1,1419 @@ + + + + + archiveVersion + 1 + classes + + objectVersion + 46 + objects + + 08AD1E7714834BA097149FFC + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFURLConnectionOperation.m + path + AFNetworking/AFURLConnectionOperation.m + sourceTree + <group> + + 0A30FD7007D548689A8CFA96 + + buildConfigurationList + D83638CD2B874305B4E2B366 + buildPhases + + CAF06F18CAB044D582844864 + EB343EA5DF6345D7867FC8B7 + + buildRules + + dependencies + + 36E14D068FBE423684F46265 + + isa + PBXNativeTarget + name + Pods + productName + Pods + productReference + 4C14728A19A84EAA9AFA4921 + productType + com.apple.product-type.library.static + + 117F23A7BDB2475BB504D0F5 + + fileRef + 4BF878DF59B546788943B1C4 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + 13106AAC07724E9D97A8B49F + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text.xcconfig + path + Pods-AFNetworking.xcconfig + sourceTree + <group> + + 17722A4C9883485BB1BF1C34 + + isa + PBXFileReference + lastKnownFileType + wrapper.framework + name + CoreGraphics.framework + path + System/Library/Frameworks/CoreGraphics.framework + sourceTree + SDKROOT + + 184B9675055042D798F70DD4 + + fileRef + 41C954074E9C4774989EE939 + isa + PBXBuildFile + + 1A32B73F523240569574D287 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFHTTPRequestOperation.m + path + AFNetworking/AFHTTPRequestOperation.m + sourceTree + <group> + + 1C472D5A8E8A4F08954C4AA2 + + buildActionMask + 2147483647 + files + + 3BBDEC35F3194F569BC38755 + 4313834545D74DE3948659F0 + 7643E5EF1A9547E7876DE986 + 475DFF9ECD7746639003AD4A + F71E6F37CA9A4629AAC2CDCC + + isa + PBXFrameworksBuildPhase + runOnlyForDeploymentPostprocessing + 0 + + 1E15FB759FAE49F89C5CB65D + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFURLConnectionOperation.h + path + AFNetworking/AFURLConnectionOperation.h + sourceTree + <group> + + 1F5E1B3B5C2C40B8B5C0D3D1 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + path + Pods-AFNetworking-prefix.pch + sourceTree + <group> + + 2043689D5F07489597A49188 + + isa + PBXFileReference + lastKnownFileType + wrapper.framework + name + MobileCoreServices.framework + path + System/Library/Frameworks/MobileCoreServices.framework + sourceTree + SDKROOT + + 242B94135C604951BF12B255 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFNetworkActivityIndicatorManager.m + path + AFNetworking/AFNetworkActivityIndicatorManager.m + sourceTree + <group> + + 258C9862D1A340E494399953 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFNetworkActivityIndicatorManager.h + path + AFNetworking/AFNetworkActivityIndicatorManager.h + sourceTree + <group> + + 2B63AA5CB8434020B521167B + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text.plist.xml + path + Pods-acknowledgements.plist + sourceTree + <group> + + 2C21BED5C48B4FE187F91AAF + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text + path + Pods-acknowledgements.markdown + sourceTree + <group> + + 2D0AD3E49325490CBCD844E7 + + attributes + + LastUpgradeCheck + 0500 + + buildConfigurationList + 9C1681924E934108AE569B3B + compatibilityVersion + Xcode 3.2 + developmentRegion + English + hasScannedForEncodings + 0 + isa + PBXProject + knownRegions + + en + + mainGroup + 40736C2ECA4D41A1B8D721AA + productRefGroup + 669C06BC945D42D2B942A283 + projectDirPath + + projectReferences + + projectRoot + + targets + + 0A30FD7007D548689A8CFA96 + ADDE8DBB9F9E475B90FBC797 + + + 2E34FB5F1E3748149252B6AD + + fileRef + CF4689A092504584B06A11F7 + isa + PBXBuildFile + + 2F2767F66C604065872045DE + + buildConfigurations + + 44F295FD071343108C2F4714 + 7351BEBB632E4B1380FD70CC + + defaultConfigurationIsVisible + 0 + defaultConfigurationName + Release + isa + XCConfigurationList + + 3396677D4F7D47ACAFB45EA3 + + children + + 17722A4C9883485BB1BF1C34 + 41C954074E9C4774989EE939 + 2043689D5F07489597A49188 + 6D512D4B085A466E829659CB + D69A248065874CCE8D755FFC + + isa + PBXGroup + name + Frameworks + sourceTree + <group> + + 363F02FE962C4D5084685024 + + fileRef + 928DF5ECB0344C82B94E8F18 + isa + PBXBuildFile + + 36675631701345F4AEAB7DBF + + children + + 928DF5ECB0344C82B94E8F18 + + isa + PBXGroup + name + Products + sourceTree + <group> + + 36E14D068FBE423684F46265 + + isa + PBXTargetDependency + target + ADDE8DBB9F9E475B90FBC797 + targetProxy + C9B8CD7C05314612A2434792 + + 37D3C638E91F452899FE87C7 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text + name + Podfile + path + ../Podfile + sourceTree + SOURCE_ROOT + xcLanguageSpecificationIdentifier + xcode.lang.ruby + + 39B010F2F8A5405DB8788FA9 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFJSONRequestOperation.m + path + AFNetworking/AFJSONRequestOperation.m + sourceTree + <group> + + 3BBDEC35F3194F569BC38755 + + fileRef + 17722A4C9883485BB1BF1C34 + isa + PBXBuildFile + + 40736C2ECA4D41A1B8D721AA + + children + + 3396677D4F7D47ACAFB45EA3 + C22DD5E647C44918AAD0EC67 + 669C06BC945D42D2B942A283 + F9B38E093C8243CBB847A0CE + 37D3C638E91F452899FE87C7 + + isa + PBXGroup + sourceTree + <group> + + 41C954074E9C4774989EE939 + + isa + PBXFileReference + lastKnownFileType + wrapper.framework + name + Foundation.framework + path + System/Library/Frameworks/Foundation.framework + sourceTree + SDKROOT + + 4313834545D74DE3948659F0 + + fileRef + 41C954074E9C4774989EE939 + isa + PBXBuildFile + + 44F295FD071343108C2F4714 + + baseConfigurationReference + E2A06AE6E23349F7834ED6E7 + buildSettings + + ALWAYS_SEARCH_USER_PATHS + NO + COPY_PHASE_STRIP + NO + DSTROOT + /tmp/xcodeproj.dst + GCC_C_LANGUAGE_STANDARD + gnu99 + GCC_DYNAMIC_NO_PIC + NO + GCC_OPTIMIZATION_LEVEL + 0 + GCC_PRECOMPILE_PREFIX_HEADER + YES + GCC_PREFIX_HEADER + Pods-AFNetworking-prefix.pch + GCC_PREPROCESSOR_DEFINITIONS + + DEBUG=1 + $(inherited) + + GCC_SYMBOLS_PRIVATE_EXTERN + NO + GCC_VERSION + com.apple.compilers.llvm.clang.1_0 + INSTALL_PATH + $(BUILT_PRODUCTS_DIR) + IPHONEOS_DEPLOYMENT_TARGET + 6.0 + OTHER_LDFLAGS + + PRODUCT_NAME + $(TARGET_NAME) + PUBLIC_HEADERS_FOLDER_PATH + $(TARGET_NAME) + SDKROOT + iphoneos + SKIP_INSTALL + YES + + isa + XCBuildConfiguration + name + Debug + + 4575990AE6344B769BEE7053 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text.xcconfig + path + Pods.xcconfig + sourceTree + <group> + + 475DFF9ECD7746639003AD4A + + fileRef + 6D512D4B085A466E829659CB + isa + PBXBuildFile + + 4ADFF8D90E254C66B692F502 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFImageRequestOperation.h + path + AFNetworking/AFImageRequestOperation.h + sourceTree + <group> + + 4BF878DF59B546788943B1C4 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFPropertyListRequestOperation.m + path + AFNetworking/AFPropertyListRequestOperation.m + sourceTree + <group> + + 4C14728A19A84EAA9AFA4921 + + explicitFileType + archive.ar + includeInIndex + 0 + isa + PBXFileReference + path + libPods.a + sourceTree + BUILT_PRODUCTS_DIR + + 4C2A6ED1A9944D5DA6403F09 + + fileRef + E2E82489B82D4CC180AA87F7 + isa + PBXBuildFile + + 5125B97E5E154A638B6A2552 + + fileRef + D7AB04599CF5422B80CC2E77 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + 520A1437FB9D4C82B7F0BFE8 + + children + + 53995F8949DE49F9935BF848 + 9450661AED894042BEE72962 + 2C21BED5C48B4FE187F91AAF + 2B63AA5CB8434020B521167B + 732EB3FD102147BAB5999C96 + 4575990AE6344B769BEE7053 + + isa + PBXGroup + name + Pods + sourceTree + <group> + + 53995F8949DE49F9935BF848 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + path + Pods-environment.h + sourceTree + <group> + + 553E8882F7CB4F5FAE46BCBE + + fileRef + 39B010F2F8A5405DB8788FA9 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + 5AE42FF5353741FF83A9C702 + + fileRef + C74FC79D37F443A7A9A6F8EC + isa + PBXBuildFile + + 5E9724BBAAB74732BA412FFA + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFNetworking.h + path + AFNetworking/AFNetworking.h + sourceTree + <group> + + 5FB77F13243D47D8B82A47A7 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFHTTPClient.m + path + AFNetworking/AFHTTPClient.m + sourceTree + <group> + + 669C06BC945D42D2B942A283 + + children + + 4C14728A19A84EAA9AFA4921 + + isa + PBXGroup + name + Products + sourceTree + <group> + + 6D512D4B085A466E829659CB + + isa + PBXFileReference + lastKnownFileType + wrapper.framework + name + Security.framework + path + System/Library/Frameworks/Security.framework + sourceTree + SDKROOT + + 6EBE2C14A7FC4379A222F0B0 + + fileRef + F764EA36EAEF4A908B23E10A + isa + PBXBuildFile + + 732EB3FD102147BAB5999C96 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text.script.sh + path + Pods-resources.sh + sourceTree + <group> + + 7351BEBB632E4B1380FD70CC + + baseConfigurationReference + E2A06AE6E23349F7834ED6E7 + buildSettings + + ALWAYS_SEARCH_USER_PATHS + NO + COPY_PHASE_STRIP + YES + DSTROOT + /tmp/xcodeproj.dst + GCC_C_LANGUAGE_STANDARD + gnu99 + GCC_PRECOMPILE_PREFIX_HEADER + YES + GCC_PREFIX_HEADER + Pods-AFNetworking-prefix.pch + GCC_VERSION + com.apple.compilers.llvm.clang.1_0 + INSTALL_PATH + $(BUILT_PRODUCTS_DIR) + IPHONEOS_DEPLOYMENT_TARGET + 6.0 + OTHER_CFLAGS + + -DNS_BLOCK_ASSERTIONS=1 + $(inherited) + + OTHER_CPLUSPLUSFLAGS + + -DNS_BLOCK_ASSERTIONS=1 + $(inherited) + + OTHER_LDFLAGS + + PRODUCT_NAME + $(TARGET_NAME) + PUBLIC_HEADERS_FOLDER_PATH + $(TARGET_NAME) + SDKROOT + iphoneos + SKIP_INSTALL + YES + VALIDATE_PRODUCT + YES + + isa + XCBuildConfiguration + name + Release + + 75F8D108CCAC46C8B9525E88 + + fileRef + A2C8A7C8FD9947F28CB5D942 + isa + PBXBuildFile + + 7643E5EF1A9547E7876DE986 + + fileRef + 2043689D5F07489597A49188 + isa + PBXBuildFile + + 7A30533345E2474FB6048F84 + + buildSettings + + IPHONEOS_DEPLOYMENT_TARGET + 6.0 + ONLY_ACTIVE_ARCH + YES + STRIP_INSTALLED_PRODUCT + NO + + isa + XCBuildConfiguration + name + Debug + + 7EA9C38B88DC4FA69AA264D3 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + UIImageView+AFNetworking.m + path + AFNetworking/UIImageView+AFNetworking.m + sourceTree + <group> + + 928DF5ECB0344C82B94E8F18 + + explicitFileType + archive.ar + includeInIndex + 0 + isa + PBXFileReference + path + libPods-AFNetworking.a + sourceTree + BUILT_PRODUCTS_DIR + + 9385A49D20E44B1A9EC05A78 + + fileRef + 242B94135C604951BF12B255 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + 9450661AED894042BEE72962 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + path + Pods-dummy.m + sourceTree + <group> + + 95229B59E0E7458CA7C4F379 + + children + + FC62B60F07924F33B461AFCC + A2C8A7C8FD9947F28CB5D942 + 4ADFF8D90E254C66B692F502 + CEBCBBA20E674D4DB370177B + 258C9862D1A340E494399953 + 5E9724BBAAB74732BA412FFA + CF4689A092504584B06A11F7 + 1E15FB759FAE49F89C5CB65D + F764EA36EAEF4A908B23E10A + C74FC79D37F443A7A9A6F8EC + 5FB77F13243D47D8B82A47A7 + 1A32B73F523240569574D287 + D7AB04599CF5422B80CC2E77 + 39B010F2F8A5405DB8788FA9 + 242B94135C604951BF12B255 + 4BF878DF59B546788943B1C4 + 08AD1E7714834BA097149FFC + FE5CE872AE5949968454923E + 7EA9C38B88DC4FA69AA264D3 + + isa + PBXGroup + name + Source Files + sourceTree + <group> + + 9570A7F385264CD5BBFCB900 + + buildActionMask + 2147483647 + files + + FE725C0AF8A24B2FBE3B510E + 75F8D108CCAC46C8B9525E88 + F72BC8DDF894435AB6A2594D + AADF91BF4793404E94659CE8 + B872082AE7E8478693E0925F + E9273D887ADF4EFDAB3887D8 + 2E34FB5F1E3748149252B6AD + E53598F917C7429A8ABEA931 + 6EBE2C14A7FC4379A222F0B0 + 5AE42FF5353741FF83A9C702 + + isa + PBXHeadersBuildPhase + runOnlyForDeploymentPostprocessing + 0 + + 9669D77043994416864E2267 + + fileRef + 1A32B73F523240569574D287 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + 9C1681924E934108AE569B3B + + buildConfigurations + + 7A30533345E2474FB6048F84 + FDD7D8C57FA6489A895DCBF6 + + defaultConfigurationIsVisible + 0 + defaultConfigurationName + Release + isa + XCConfigurationList + + A2C8A7C8FD9947F28CB5D942 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFHTTPRequestOperation.h + path + AFNetworking/AFHTTPRequestOperation.h + sourceTree + <group> + + A2D09F3EF81D4BECB3B8C3AA + + fileRef + 9450661AED894042BEE72962 + isa + PBXBuildFile + + AADF91BF4793404E94659CE8 + + fileRef + CEBCBBA20E674D4DB370177B + isa + PBXBuildFile + + ADDE8DBB9F9E475B90FBC797 + + buildConfigurationList + 2F2767F66C604065872045DE + buildPhases + + D83F3CF6DA96433B972AA62D + 1C472D5A8E8A4F08954C4AA2 + 9570A7F385264CD5BBFCB900 + + buildRules + + dependencies + + isa + PBXNativeTarget + name + Pods-AFNetworking + productName + Pods-AFNetworking + productReference + 928DF5ECB0344C82B94E8F18 + productType + com.apple.product-type.library.static + + B872082AE7E8478693E0925F + + fileRef + 258C9862D1A340E494399953 + isa + PBXBuildFile + + C22DD5E647C44918AAD0EC67 + + children + + F603B69EEFF14170BE6FA566 + + isa + PBXGroup + name + Pods + sourceTree + <group> + + C74FC79D37F443A7A9A6F8EC + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + UIImageView+AFNetworking.h + path + AFNetworking/UIImageView+AFNetworking.h + sourceTree + <group> + + C9B8CD7C05314612A2434792 + + containerPortal + 2D0AD3E49325490CBCD844E7 + isa + PBXContainerItemProxy + proxyType + 1 + remoteGlobalIDString + ADDE8DBB9F9E475B90FBC797 + remoteInfo + Pods-AFNetworking + + CAC922C847194DC5A4F3E024 + + fileRef + 7EA9C38B88DC4FA69AA264D3 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + CAF06F18CAB044D582844864 + + buildActionMask + 2147483647 + files + + A2D09F3EF81D4BECB3B8C3AA + + isa + PBXSourcesBuildPhase + runOnlyForDeploymentPostprocessing + 0 + + CEBCBBA20E674D4DB370177B + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFJSONRequestOperation.h + path + AFNetworking/AFJSONRequestOperation.h + sourceTree + <group> + + CF4689A092504584B06A11F7 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFPropertyListRequestOperation.h + path + AFNetworking/AFPropertyListRequestOperation.h + sourceTree + <group> + + D191D66EE1F84CAA93702591 + + baseConfigurationReference + 4575990AE6344B769BEE7053 + buildSettings + + ALWAYS_SEARCH_USER_PATHS + NO + COPY_PHASE_STRIP + YES + DSTROOT + /tmp/xcodeproj.dst + GCC_C_LANGUAGE_STANDARD + gnu99 + GCC_PRECOMPILE_PREFIX_HEADER + YES + GCC_VERSION + com.apple.compilers.llvm.clang.1_0 + INSTALL_PATH + $(BUILT_PRODUCTS_DIR) + IPHONEOS_DEPLOYMENT_TARGET + 6.0 + OTHER_CFLAGS + + -DNS_BLOCK_ASSERTIONS=1 + $(inherited) + + OTHER_CPLUSPLUSFLAGS + + -DNS_BLOCK_ASSERTIONS=1 + $(inherited) + + OTHER_LDFLAGS + + PRODUCT_NAME + $(TARGET_NAME) + PUBLIC_HEADERS_FOLDER_PATH + $(TARGET_NAME) + SDKROOT + iphoneos + SKIP_INSTALL + YES + VALIDATE_PRODUCT + YES + + isa + XCBuildConfiguration + name + Release + + D1ED042E2078427081658CEA + + fileRef + FE5CE872AE5949968454923E + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + D66C6AC4368F47599EC35DE2 + + fileRef + 08AD1E7714834BA097149FFC + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + D69A248065874CCE8D755FFC + + isa + PBXFileReference + lastKnownFileType + wrapper.framework + name + SystemConfiguration.framework + path + System/Library/Frameworks/SystemConfiguration.framework + sourceTree + SDKROOT + + D7AB04599CF5422B80CC2E77 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFImageRequestOperation.m + path + AFNetworking/AFImageRequestOperation.m + sourceTree + <group> + + D83638CD2B874305B4E2B366 + + buildConfigurations + + D9038D6BC9504E39A8279073 + D191D66EE1F84CAA93702591 + + defaultConfigurationIsVisible + 0 + defaultConfigurationName + Release + isa + XCConfigurationList + + D83F3CF6DA96433B972AA62D + + buildActionMask + 2147483647 + files + + DB224BFAF42D46A692A571E5 + 9669D77043994416864E2267 + 5125B97E5E154A638B6A2552 + 553E8882F7CB4F5FAE46BCBE + 9385A49D20E44B1A9EC05A78 + 117F23A7BDB2475BB504D0F5 + D66C6AC4368F47599EC35DE2 + D1ED042E2078427081658CEA + 4C2A6ED1A9944D5DA6403F09 + CAC922C847194DC5A4F3E024 + + isa + PBXSourcesBuildPhase + runOnlyForDeploymentPostprocessing + 0 + + D9038D6BC9504E39A8279073 + + baseConfigurationReference + 4575990AE6344B769BEE7053 + buildSettings + + ALWAYS_SEARCH_USER_PATHS + NO + COPY_PHASE_STRIP + NO + DSTROOT + /tmp/xcodeproj.dst + GCC_C_LANGUAGE_STANDARD + gnu99 + GCC_DYNAMIC_NO_PIC + NO + GCC_OPTIMIZATION_LEVEL + 0 + GCC_PRECOMPILE_PREFIX_HEADER + YES + GCC_PREPROCESSOR_DEFINITIONS + + DEBUG=1 + $(inherited) + + GCC_SYMBOLS_PRIVATE_EXTERN + NO + GCC_VERSION + com.apple.compilers.llvm.clang.1_0 + INSTALL_PATH + $(BUILT_PRODUCTS_DIR) + IPHONEOS_DEPLOYMENT_TARGET + 6.0 + OTHER_LDFLAGS + + PRODUCT_NAME + $(TARGET_NAME) + PUBLIC_HEADERS_FOLDER_PATH + $(TARGET_NAME) + SDKROOT + iphoneos + SKIP_INSTALL + YES + + isa + XCBuildConfiguration + name + Debug + + DB224BFAF42D46A692A571E5 + + fileRef + 5FB77F13243D47D8B82A47A7 + isa + PBXBuildFile + settings + + COMPILER_FLAGS + -fobjc-arc -DOS_OBJECT_USE_OBJC=0 + + + DC92641749314F3CB6204D69 + + children + + E2E82489B82D4CC180AA87F7 + 1F5E1B3B5C2C40B8B5C0D3D1 + 13106AAC07724E9D97A8B49F + E2A06AE6E23349F7834ED6E7 + + isa + PBXGroup + name + Support Files + sourceTree + SOURCE_ROOT + + E2A06AE6E23349F7834ED6E7 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + text.xcconfig + path + Pods-AFNetworking-Private.xcconfig + sourceTree + <group> + + E2E82489B82D4CC180AA87F7 + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + path + Pods-AFNetworking-dummy.m + sourceTree + <group> + + E53598F917C7429A8ABEA931 + + fileRef + 1E15FB759FAE49F89C5CB65D + isa + PBXBuildFile + + E9273D887ADF4EFDAB3887D8 + + fileRef + 5E9724BBAAB74732BA412FFA + isa + PBXBuildFile + + EB343EA5DF6345D7867FC8B7 + + buildActionMask + 2147483647 + files + + 184B9675055042D798F70DD4 + 363F02FE962C4D5084685024 + + isa + PBXFrameworksBuildPhase + runOnlyForDeploymentPostprocessing + 0 + + F603B69EEFF14170BE6FA566 + + children + + 36675631701345F4AEAB7DBF + 95229B59E0E7458CA7C4F379 + DC92641749314F3CB6204D69 + + isa + PBXGroup + name + AFNetworking + path + AFNetworking + sourceTree + <group> + + F71E6F37CA9A4629AAC2CDCC + + fileRef + D69A248065874CCE8D755FFC + isa + PBXBuildFile + + F72BC8DDF894435AB6A2594D + + fileRef + 4ADFF8D90E254C66B692F502 + isa + PBXBuildFile + + F764EA36EAEF4A908B23E10A + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFXMLRequestOperation.h + path + AFNetworking/AFXMLRequestOperation.h + sourceTree + <group> + + F9B38E093C8243CBB847A0CE + + children + + 520A1437FB9D4C82B7F0BFE8 + + isa + PBXGroup + name + Targets Support Files + sourceTree + <group> + + FC62B60F07924F33B461AFCC + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.h + name + AFHTTPClient.h + path + AFNetworking/AFHTTPClient.h + sourceTree + <group> + + FDD7D8C57FA6489A895DCBF6 + + buildSettings + + IPHONEOS_DEPLOYMENT_TARGET + 6.0 + STRIP_INSTALLED_PRODUCT + NO + + isa + XCBuildConfiguration + name + Release + + FE5CE872AE5949968454923E + + includeInIndex + 1 + isa + PBXFileReference + lastKnownFileType + sourcecode.c.objc + name + AFXMLRequestOperation.m + path + AFNetworking/AFXMLRequestOperation.m + sourceTree + <group> + + FE725C0AF8A24B2FBE3B510E + + fileRef + FC62B60F07924F33B461AFCC + isa + PBXBuildFile + + + rootObject + 2D0AD3E49325490CBCD844E7 + + diff --git a/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme new file mode 100644 index 00000000000..04cc49a93cc --- /dev/null +++ b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods-AFNetworking.xcscheme @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClientTests.xcscheme b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme similarity index 73% rename from samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClientTests.xcscheme rename to samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme index fd2d6103823..802886807fb 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClientTests.xcscheme +++ b/samples/client/petstore/objc/Pods/Pods.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/Pods.xcscheme @@ -1,10 +1,26 @@ + + + + + + - - - - + + + + SchemeUserState + + Pods-AFNetworking.xcscheme + + orderHint + 3 + + Pods.xcscheme + + orderHint + 2 + + + SuppressBuildableAutocreation + + 0A30FD7007D548689A8CFA96 + + primary + + + 7934141CDD144029B68BBCCA + + primary + + + 9DF4A09206094F4EB8B7F841 + + primary + + + ADDE8DBB9F9E475B90FBC797 + + primary + + + B044D459E2CB44439DF863F1 + + primary + + + FEFF1D6E156342BEA878F340 + + primary + + + + + diff --git a/samples/client/petstore/objc/client/NIKApiInvoker.h b/samples/client/petstore/objc/client/NIKApiInvoker.h deleted file mode 100644 index 2d6977eadcc..00000000000 --- a/samples/client/petstore/objc/client/NIKApiInvoker.h +++ /dev/null @@ -1,40 +0,0 @@ -#import - -@interface NIKApiInvoker : NSObject { - -@private - NSOperationQueue *_queue; - NSMutableDictionary * _defaultHeaders; -} -@property(nonatomic, readonly) NSOperationQueue* queue; -@property(nonatomic, readonly) NSMutableDictionary * defaultHeaders; -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; - -+ (NIKApiInvoker*)sharedInstance; - -- (void)updateLoadCountWithDelta:(NSInteger)countDelta; -- (void)startLoad; -- (void)stopLoad; - - --(void) addHeader:(NSString*)value forKey:(NSString*)key; - --(NSString*) escapeString:(NSString*) string; - --(void) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id)body - headerParams: (NSDictionary*) headerParams - contentType: contentType - completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock; - --(void) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id)body - headerParams: (NSDictionary*) headerParams - contentType: contentType - completionBlock: (void (^)(NSString*, NSError *))completionBlock; - -@end diff --git a/samples/client/petstore/objc/client/NIKApiInvoker.m b/samples/client/petstore/objc/client/NIKApiInvoker.m deleted file mode 100644 index 819930ef66f..00000000000 --- a/samples/client/petstore/objc/client/NIKApiInvoker.m +++ /dev/null @@ -1,336 +0,0 @@ -#import "NIKApiInvoker.h" -#import "NIKFile.h" - -@implementation NIKApiInvoker - -@synthesize queue = _queue; -@synthesize defaultHeaders = _defaultHeaders; - - -static NSInteger __LoadingObjectsCount = 0; - -+ (NIKApiInvoker*)sharedInstance { - static NIKApiInvoker *_sharedInstance = nil; - if (!_sharedInstance) { - _sharedInstance = [[NIKApiInvoker alloc] init]; - } - return _sharedInstance; -} - -- (void)updateLoadCountWithDelta:(NSInteger)countDelta { - @synchronized(self) { - __LoadingObjectsCount += countDelta; - __LoadingObjectsCount = (__LoadingObjectsCount < 0) ? 0 : __LoadingObjectsCount ; - -#if TARGET_OS_IPHONE - [UIApplication sharedApplication].networkActivityIndicatorVisible = __LoadingObjectsCount > 0; -#endif - } -} - -- (void)startLoad { - [self updateLoadCountWithDelta:1]; -} - -- (void)stopLoad { - [self updateLoadCountWithDelta:-1]; -} - - -- (id) init { - self = [super init]; - _queue = [[NSOperationQueue alloc] init]; - _defaultHeaders = [[NSMutableDictionary alloc] init]; - _cachePolicy = NSURLRequestUseProtocolCachePolicy; - return self; -} - --(void) addHeader:(NSString*) value - forKey:(NSString*)key { - [_defaultHeaders setValue:value forKey:key]; -} - --(NSString*) escapeString:(NSString *)unescaped { - return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); -} - --(void) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - contentType: (NSString*) contentType - completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock -{ - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - NSString * separator = nil; - int counter = 0; - if(queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; - else separator = @"&"; - NSString * value; - if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ - value = [self escapeString:[queryParams valueForKey:key]]; - } - else { - value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; - } - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [self escapeString:key], value]]; - counter += 1; - } - } - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"request url: %@", requestUrl); - } - - NSURL* URL = [NSURL URLWithString:requestUrl]; - - NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init]; - [request setURL:URL]; - [request setCachePolicy:self.cachePolicy]; - [request setTimeoutInterval:30]; - - for(NSString * key in [_defaultHeaders keyEnumerator]){ - [request setValue:[_defaultHeaders valueForKey:key] forHTTPHeaderField:key]; - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [request setHTTPMethod:method]; - if(body != nil) { - NSError * error = [NSError new]; - NSData * data = nil; - if([body isKindOfClass:[NSDictionary class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else if ([body isKindOfClass:[NIKFile class]]){ - NIKFile * file = (NIKFile*) body; - - NSString *boundary = @"Fo0+BAr"; - contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; - - // add the body - NSMutableData *postBody = [NSMutableData data]; - [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[@"Content-Disposition: form-data; name= \"some_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", file] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", file.mimeType] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData: file.data]; - [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - } - else if ([body isKindOfClass:[NSArray class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else { - data = [body dataUsingEncoding:NSUTF8StringEncoding]; - } - NSString *postLength = [NSString stringWithFormat:@"%d", [data length]]; - [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; - [request setHTTPBody:data]; - - [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; - } - - // Handle caching on GET requests - if ((_cachePolicy == NSURLRequestReturnCacheDataElseLoad || _cachePolicy == NSURLRequestReturnCacheDataDontLoad) && [method isEqualToString:@"GET"]) { - NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; - NSData *data = [cacheResponse data]; - if (data) { - NSError *error = nil; - NSDictionary* results = [NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]; - completionBlock(results, nil); - } - } - - if (_cachePolicy == NSURLRequestReturnCacheDataDontLoad) - return; - - [self startLoad]; - NSDate *date = [NSDate date]; - [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler: - ^(NSURLResponse *response, NSData *data, NSError *error) { - long statusCode = [(NSHTTPURLResponse*)response statusCode]; - - if (error) { - completionBlock(nil, error); - return; - } - else if (!NSLocationInRange(statusCode, NSMakeRange(200, 99))){ - error = [NSError errorWithDomain:@"swagger" - code:statusCode - userInfo:[NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]]; - completionBlock(nil, error); - return; - } - else { - NSDictionary* results = [NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]; - completionBlock(results, nil); - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"fetched results (%f seconds): %@", [[NSDate date] timeIntervalSinceDate:date], results); - } - } - - [self stopLoad]; - }]; -} - --(void) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - contentType: (NSString*) contentType - completionBlock: (void (^)(NSString*, NSError *))completionBlock -{ - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - NSString * separator = nil; - int counter = 0; - if(queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; - else separator = @"&"; - NSString * value; - if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ - value = [self escapeString:[queryParams valueForKey:key]]; - } - else { - value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; - } - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [self escapeString:key], value]]; - counter += 1; - } - } - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"request url: %@", requestUrl); - } - - NSURL* URL = [NSURL URLWithString:requestUrl]; - - NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init]; - [request setURL:URL]; - [request setCachePolicy:self.cachePolicy]; - [request setTimeoutInterval:30]; - - for(NSString * key in [_defaultHeaders keyEnumerator]){ - [request setValue:[_defaultHeaders valueForKey:key] forHTTPHeaderField:key]; - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [request setHTTPMethod:method]; - if(body != nil) { - NSError * error = [NSError new]; - NSData * data = nil; - if([body isKindOfClass:[NSDictionary class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else if ([body isKindOfClass:[NIKFile class]]){ - NIKFile * file = (NIKFile*) body; - - NSString *boundary = @"Fo0+BAr"; - contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; - - // add the body - NSMutableData *postBody = [NSMutableData data]; - [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[@"Content-Disposition: form-data; name= \"some_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", file] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", file.mimeType] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData: file.data]; - [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - } - else if ([body isKindOfClass:[NSArray class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else { - data = [body dataUsingEncoding:NSUTF8StringEncoding]; - } - NSString *postLength = [NSString stringWithFormat:@"%d", [data length]]; - [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; - [request setHTTPBody:data]; - - [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; - } - - - // Handle caching on GET requests - if ((_cachePolicy == NSURLRequestReturnCacheDataElseLoad || _cachePolicy == NSURLRequestReturnCacheDataDontLoad) && [method isEqualToString:@"GET"]) { - NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; - NSData *data = [cacheResponse data]; - if (data) { - NSString* results = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - - if(results && [results length] >= 2) { - if(([results characterAtIndex:0] == '\"') && ([results characterAtIndex:([results length] - 1) == '\"'])){ - results = [results substringWithRange:NSMakeRange(1, [results length] -2)]; - } - } - completionBlock(results, nil); - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - // NSLog(@"cached results: %@", results); - } - } - - } - - if (_cachePolicy == NSURLRequestReturnCacheDataDontLoad) - return; - - [self startLoad]; - NSDate *date = [NSDate date]; - [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler: - ^(NSURLResponse *response, NSData *data, NSError *error) { - int statusCode = [(NSHTTPURLResponse*)response statusCode]; - if (error) { - completionBlock(nil, error); - return; - } - else if (!NSLocationInRange(statusCode, NSMakeRange(200, 99))){ - error = [NSError errorWithDomain:@"swagger" - code:statusCode - userInfo:[NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]]; - completionBlock(nil, error); - return; - } - else { - NSString* results = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - - if(results && [results length] >= 2) { - if(([results characterAtIndex:0] == '\"') && ([results characterAtIndex:([results length] - 1) == '\"'])){ - results = [results substringWithRange:NSMakeRange(1, [results length] -2)]; - } - - } - completionBlock(results, nil); - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"fetched results (%f seconds): %@", [[NSDate date] timeIntervalSinceDate:date], results); - } - } - [self stopLoad]; - }]; -} -@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/NIKSwaggerObject.h b/samples/client/petstore/objc/client/NIKSwaggerObject.h deleted file mode 100644 index 18f95663de1..00000000000 --- a/samples/client/petstore/objc/client/NIKSwaggerObject.h +++ /dev/null @@ -1,6 +0,0 @@ -#import - -@interface NIKSwaggerObject : NSObject -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; -@end diff --git a/samples/client/petstore/objc/client/NIKSwaggerObject.m b/samples/client/petstore/objc/client/NIKSwaggerObject.m deleted file mode 100644 index 2467ce13ca8..00000000000 --- a/samples/client/petstore/objc/client/NIKSwaggerObject.m +++ /dev/null @@ -1,10 +0,0 @@ -#import "NIKSwaggerObject.h" - -@implementation NIKSwaggerObject -- (id) initWithValues: (NSDictionary*)dict { - return self; -} -- (NSDictionary*) asDictionary{ - return [NSDictionary init]; -} -@end diff --git a/samples/client/petstore/objc/client/RVBCategory.h b/samples/client/petstore/objc/client/RVBCategory.h deleted file mode 100644 index 6d5d56ce999..00000000000 --- a/samples/client/petstore/objc/client/RVBCategory.h +++ /dev/null @@ -1,16 +0,0 @@ -#import -#import "NIKSwaggerObject.h" - -@interface RVBCategory : NIKSwaggerObject - -@property(nonatomic) NSString* name; -@property(nonatomic) NSNumber* _id; -- (id) name: (NSString*) name - _id: (NSNumber*) _id; - -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; - - -@end - diff --git a/samples/client/petstore/objc/client/RVBOrder.h b/samples/client/petstore/objc/client/RVBOrder.h deleted file mode 100644 index f1d39244a30..00000000000 --- a/samples/client/petstore/objc/client/RVBOrder.h +++ /dev/null @@ -1,23 +0,0 @@ -#import -#import "NIKSwaggerObject.h" -#import "NIKDate.h" - -@interface RVBOrder : NIKSwaggerObject - -@property(nonatomic) NSNumber* _id; -@property(nonatomic) NSString* status; -@property(nonatomic) NSNumber* petId; -@property(nonatomic) NSNumber* quantity; -@property(nonatomic) NIKDate* shipDate; -- (id) _id: (NSNumber*) _id - status: (NSString*) status - petId: (NSNumber*) petId - quantity: (NSNumber*) quantity - shipDate: (NIKDate*) shipDate; - -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; - - -@end - diff --git a/samples/client/petstore/objc/client/RVBPet.h b/samples/client/petstore/objc/client/RVBPet.h deleted file mode 100644 index 84cf42ce1ca..00000000000 --- a/samples/client/petstore/objc/client/RVBPet.h +++ /dev/null @@ -1,26 +0,0 @@ -#import -#import "NIKSwaggerObject.h" -#import "RVBCategory.h" -#import "RVBTag.h" - -@interface RVBPet : NIKSwaggerObject - -@property(nonatomic) NSString* name; -@property(nonatomic) NSNumber* _id; -@property(nonatomic) NSArray* tags; -@property(nonatomic) NSString* status; -@property(nonatomic) NSArray* photoUrls; -@property(nonatomic) RVBCategory* category; -- (id) name: (NSString*) name - _id: (NSNumber*) _id - tags: (NSArray*) tags - status: (NSString*) status - photoUrls: (NSArray*) photoUrls - category: (RVBCategory*) category; - -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; - - -@end - diff --git a/samples/client/petstore/objc/client/RVBPetApi.h b/samples/client/petstore/objc/client/RVBPetApi.h deleted file mode 100644 index a543a4bbde2..00000000000 --- a/samples/client/petstore/objc/client/RVBPetApi.h +++ /dev/null @@ -1,71 +0,0 @@ -#import -#import "NIKApiInvoker.h" -#import "RVBPet.h" - - -@interface RVBPetApi: NSObject { - -@private - NSOperationQueue *_queue; - NIKApiInvoker * _api; -} -@property(nonatomic, readonly) NSOperationQueue* queue; -@property(nonatomic, readonly) NIKApiInvoker* api; - --(void) addHeader:(NSString*)value forKey:(NSString*)key; - -/** - - Find pet by ID - Returns a pet based on ID - @param petId ID of pet that needs to be fetched - */ --(void) getPetByIdWithCompletionBlock :(NSString*) petId - completionHandler: (void (^)(RVBPet* output, NSError* error))completionBlock; - -/** - - Deletes a pet - - @param petId Pet id to delete - */ --(void) deletePetWithCompletionBlock :(NSString*) petId - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - Add a new pet to the store - - @param body Pet object that needs to be added to the store - */ --(void) addPetWithCompletionBlock :(RVBPet*) body - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - Update an existing pet - - @param body Pet object that needs to be updated in the store - */ --(void) updatePetWithCompletionBlock :(RVBPet*) body - completionHandler: (void (^)(NSError* error))completionBlock; - -/** - - Finds Pets by status - Multiple status values can be provided with comma seperated strings - @param status Status values that need to be considered for filter - */ --(void) findPetsByStatusWithCompletionBlock :(NSString*) status - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; - -/** - - Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - @param tags Tags to filter by - */ --(void) findPetsByTagsWithCompletionBlock :(NSString*) tags - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; - -@end diff --git a/samples/client/petstore/objc/client/RVBPetApi.m b/samples/client/petstore/objc/client/RVBPetApi.m deleted file mode 100644 index e695f8ed0a8..00000000000 --- a/samples/client/petstore/objc/client/RVBPetApi.m +++ /dev/null @@ -1,617 +0,0 @@ -#import "RVBPetApi.h" -#import "NIKFile.h" -#import "RVBPet.h" - - - -@implementation RVBPetApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; - -@synthesize queue = _queue; -@synthesize api = _api; - -+(RVBPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static RVBPetApi* singletonAPI = nil; - - if (singletonAPI == nil) { - singletonAPI = [[RVBPetApi alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; -} - --(id) init { - self = [super init]; - _queue = [[NSOperationQueue alloc] init]; - _api = [NIKApiInvoker sharedInstance]; - - return self; -} - --(void) addHeader:(NSString*) value - forKey:(NSString*)key { - [_api addHeader:value forKey:key]; -} - --(void) getPetByIdWithCompletionBlock:(NSString*) petId - completionHandler: (void (^)(RVBPet* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [_api escapeString:petId]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - completionBlock( [[RVBPet alloc]initWithValues: data], nil);}]; - - -} - --(void) deletePetWithCompletionBlock:(NSString*) petId - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [_api escapeString:petId]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) addPetWithCompletionBlock:(RVBPet*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) updatePetWithCompletionBlock:(RVBPet*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"PUT" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) findPetsByStatusWithCompletionBlock:(NSString*) status - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(status != nil) - queryParams[@"status"] = status; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(status == nil) { - // error - } - [_api dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - contentType: contentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - RVBPet* d = [[RVBPet alloc]initWithValues: dict]; - [objs addObject:d]; - } - completionBlock(objs, nil); - } - }]; - - -} - --(void) findPetsByTagsWithCompletionBlock:(NSString*) tags - completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(tags != nil) - queryParams[@"tags"] = tags; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(tags == nil) { - // error - } - [_api dictionary: requestUrl - method: @"GET" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - contentType: contentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - RVBPet* d = [[RVBPet alloc]initWithValues: dict]; - [objs addObject:d]; - } - completionBlock(objs, nil); - } - }]; - - -} - --(void) getPetByIdAsJsonWithCompletionBlock :(NSString*) petId - - completionHandler:(void (^)(NSString*, NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [_api escapeString:petId]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - - - }]; - - -} - --(void) deletePetAsJsonWithCompletionBlock :(NSString*) petId - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [_api escapeString:petId]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(petId == nil) { - // error - } - [_api dictionary:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) addPetAsJsonWithCompletionBlock :(RVBPet*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) updatePetAsJsonWithCompletionBlock :(RVBPet*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"PUT" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) findPetsByStatusAsJsonWithCompletionBlock :(NSString*) status - - completionHandler:(void (^)(NSString*, NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(status != nil) - queryParams[@"status"] = status; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(status == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - - - }]; - - -} - --(void) findPetsByTagsAsJsonWithCompletionBlock :(NSString*) tags - - completionHandler:(void (^)(NSString*, NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(tags != nil) - queryParams[@"tags"] = tags; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(tags == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - - - }]; - - -} - - -@end diff --git a/samples/client/petstore/objc/client/RVBStoreApi.m b/samples/client/petstore/objc/client/RVBStoreApi.m deleted file mode 100644 index 4eeee9471dd..00000000000 --- a/samples/client/petstore/objc/client/RVBStoreApi.m +++ /dev/null @@ -1,312 +0,0 @@ -#import "RVBStoreApi.h" -#import "NIKFile.h" -#import "RVBOrder.h" - - - -@implementation RVBStoreApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; - -@synthesize queue = _queue; -@synthesize api = _api; - -+(RVBStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static RVBStoreApi* singletonAPI = nil; - - if (singletonAPI == nil) { - singletonAPI = [[RVBStoreApi alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; -} - --(id) init { - self = [super init]; - _queue = [[NSOperationQueue alloc] init]; - _api = [NIKApiInvoker sharedInstance]; - - return self; -} - --(void) addHeader:(NSString*) value - forKey:(NSString*)key { - [_api addHeader:value forKey:key]; -} - --(void) getOrderByIdWithCompletionBlock:(NSString*) orderId - completionHandler: (void (^)(RVBOrder* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [_api escapeString:orderId]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(orderId == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - completionBlock( [[RVBOrder alloc]initWithValues: data], nil);}]; - - -} - --(void) deleteOrderWithCompletionBlock:(NSString*) orderId - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [_api escapeString:orderId]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(orderId == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) placeOrderWithCompletionBlock:(RVBOrder*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) getOrderByIdAsJsonWithCompletionBlock :(NSString*) orderId - - completionHandler:(void (^)(NSString*, NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [_api escapeString:orderId]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(orderId == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - - - }]; - - -} - --(void) deleteOrderAsJsonWithCompletionBlock :(NSString*) orderId - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [_api escapeString:orderId]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(orderId == nil) { - // error - } - [_api dictionary:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) placeOrderAsJsonWithCompletionBlock :(RVBOrder*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - - -@end diff --git a/samples/client/petstore/objc/client/RVBTag.h b/samples/client/petstore/objc/client/RVBTag.h deleted file mode 100644 index 16eeeffa21d..00000000000 --- a/samples/client/petstore/objc/client/RVBTag.h +++ /dev/null @@ -1,16 +0,0 @@ -#import -#import "NIKSwaggerObject.h" - -@interface RVBTag : NIKSwaggerObject - -@property(nonatomic) NSString* name; -@property(nonatomic) NSNumber* _id; -- (id) name: (NSString*) name - _id: (NSNumber*) _id; - -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; - - -@end - diff --git a/samples/client/petstore/objc/client/RVBUser.h b/samples/client/petstore/objc/client/RVBUser.h deleted file mode 100644 index ef789dfe4e4..00000000000 --- a/samples/client/petstore/objc/client/RVBUser.h +++ /dev/null @@ -1,28 +0,0 @@ -#import -#import "NIKSwaggerObject.h" - -@interface RVBUser : NIKSwaggerObject - -@property(nonatomic) NSNumber* _id; -@property(nonatomic) NSString* firstName; -@property(nonatomic) NSString* username; -@property(nonatomic) NSString* lastName; -@property(nonatomic) NSString* email; -@property(nonatomic) NSString* password; -@property(nonatomic) NSString* phone; -@property(nonatomic) NSNumber* userStatus; -- (id) _id: (NSNumber*) _id - firstName: (NSString*) firstName - username: (NSString*) username - lastName: (NSString*) lastName - email: (NSString*) email - password: (NSString*) password - phone: (NSString*) phone - userStatus: (NSNumber*) userStatus; - -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; - - -@end - diff --git a/samples/client/petstore/objc/client/RVBUserApi.m b/samples/client/petstore/objc/client/RVBUserApi.m deleted file mode 100644 index 790b90d6095..00000000000 --- a/samples/client/petstore/objc/client/RVBUserApi.m +++ /dev/null @@ -1,842 +0,0 @@ -#import "RVBUserApi.h" -#import "NIKFile.h" -#import "RVBUser.h" - - - -@implementation RVBUserApi -static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; - -@synthesize queue = _queue; -@synthesize api = _api; - -+(RVBUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { - static RVBUserApi* singletonAPI = nil; - - if (singletonAPI == nil) { - singletonAPI = [[RVBUserApi alloc] init]; - [singletonAPI addHeader:headerValue forKey:key]; - } - return singletonAPI; -} - --(id) init { - self = [super init]; - _queue = [[NSOperationQueue alloc] init]; - _api = [NIKApiInvoker sharedInstance]; - - return self; -} - --(void) addHeader:(NSString*) value - forKey:(NSString*)key { - [_api addHeader:value forKey:key]; -} - --(void) createUserWithCompletionBlock:(RVBUser*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) createUsersWithArrayInputWithCompletionBlock:(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) createUsersWithListInputWithCompletionBlock:(NSArray*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) updateUserWithCompletionBlock:(NSString*) username - body:(RVBUser*) body - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [_api escapeString:username]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(username == nil) { - // error - } - if(body == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"PUT" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) deleteUserWithCompletionBlock:(NSString*) username - completionHandler: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [_api escapeString:username]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) getUserByNameWithCompletionBlock:(NSString*) username - completionHandler: (void (^)(RVBUser* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [_api escapeString:username]]; - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - completionBlock( [[RVBUser alloc]initWithValues: data], nil);}]; - - -} - --(void) loginUserWithCompletionBlock:(NSString*) username - password:(NSString*) password - completionHandler: (void (^)(NSString* output, NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(username != nil) - queryParams[@"username"] = username; - if(password != nil) - queryParams[@"password"] = password; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - if(password == nil) { - // error - } - [_api stringWithCompletionBlock:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - - completionBlock( [[NSString alloc]initWithString: data], nil); - }]; - - -} - --(void) logoutUserWithCompletionBlock: (void (^)(NSError* error))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - - NSString* contentType = @"application/json"; - - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - [_api stringWithCompletionBlock:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; - - -} - --(void) createUserAsJsonWithCompletionBlock :(RVBUser*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) createUsersWithArrayInputAsJsonWithCompletionBlock :(NSArray*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) createUsersWithListInputAsJsonWithCompletionBlock :(NSArray*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"POST" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) updateUserAsJsonWithCompletionBlock :(NSString*) username -body:(RVBUser*) body - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [_api escapeString:username]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - if(username == nil) { - // error - } - if(body == nil) { - // error - } - [_api dictionary:requestUrl - method:@"PUT" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) deleteUserAsJsonWithCompletionBlock :(NSString*) username - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [_api escapeString:username]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - [_api dictionary:requestUrl - method:@"DELETE" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - --(void) getUserByNameAsJsonWithCompletionBlock :(NSString*) username - - completionHandler:(void (^)(NSString*, NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [_api escapeString:username]]; - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - - - }]; - - -} - --(void) loginUserAsJsonWithCompletionBlock :(NSString*) username -password:(NSString*) password - - completionHandler:(void (^)(NSString*, NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - if(username != nil) - queryParams[@"username"] = username; - if(password != nil) - queryParams[@"password"] = password; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - if(username == nil) { - // error - } - if(password == nil) { - // error - } - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(nil, error);return; - } - - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - - - }]; - - -} - --(void) logoutUserAsJsonWithCompletionBlock : - - completionHandler:(void (^)(NSError *))completionBlock{ - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - id bodyDictionary = nil; - [_api dictionary:requestUrl - method:@"GET" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - completionBlock(error);return; - } - - completionBlock(nil); - - }]; - - -} - - -@end diff --git a/samples/client/petstore/objc/client/SWGApiClient.h b/samples/client/petstore/objc/client/SWGApiClient.h new file mode 100644 index 00000000000..aab60cd0595 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGApiClient.h @@ -0,0 +1,64 @@ +#import +#import "AFHTTPClient.h" + +@interface SWGApiClient : AFHTTPClient + +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, assign) BOOL logRequests; +@property(nonatomic, assign) BOOL logCacheHits; +@property(nonatomic, assign) BOOL logServerResponses; +@property(nonatomic, assign) BOOL logJSON; +@property(nonatomic, assign) BOOL logHTTP; +@property(nonatomic, readonly) NSOperationQueue* queue; + ++(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; + ++(NSOperationQueue*) sharedQueue; + ++(void)setLoggingEnabled:(bool) state; + ++(void)clearCache; + ++(void)setCacheEnabled:(BOOL) enabled; + ++(unsigned long)requestQueueSize; + ++(void) setOfflineState:(BOOL) state; + ++(AFNetworkReachabilityStatus) getReachabilityStatus; + ++(NSNumber*) nextRequestId; + ++(NSNumber*) queueRequest; + ++(void) cancelRequest:(NSNumber*)requestId; + ++(NSString*) escape:(id)unescaped; + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; + ++(void) configureCacheReachibilityForHost:(NSString*)host; + +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey; + +-(NSNumber*) dictionary:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; + +-(NSNumber*) stringWithCompletionBlock:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + 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 new file mode 100644 index 00000000000..669fd4d570b --- /dev/null +++ b/samples/client/petstore/objc/client/SWGApiClient.m @@ -0,0 +1,419 @@ +#import "SWGApiClient.h" +#import "SWGFile.h" + +#import "AFJSONRequestOperation.h" + +@implementation SWGApiClient + +static long requestId = 0; +static bool offlineState = true; +static NSMutableSet * queuedRequests = nil; +static bool cacheEnabled = false; +static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; +static NSOperationQueue* sharedQueue; +static void (^reachabilityChangeBlock)(int); +static bool loggingEnabled = false; + ++(void)setLoggingEnabled:(bool) state { + loggingEnabled = state; +} + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(void)configureCacheWithMemoryAndDiskCapacity:(unsigned long) memorySize + diskSize:(unsigned long) diskSize { + NSAssert(memorySize > 0, @"invalid in-memory cache size"); + NSAssert(diskSize >= 0, @"invalid disk cache size"); + + NSURLCache *cache = + [[NSURLCache alloc] + initWithMemoryCapacity:memorySize + diskCapacity:diskSize + diskPath:@"swagger_url_cache"]; + + [NSURLCache setSharedURLCache:cache]; +} + ++(NSOperationQueue*) sharedQueue { + return sharedQueue; +} + ++(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl { + static NSMutableDictionary *_pool = nil; + if (queuedRequests == nil) { + queuedRequests = [[NSMutableSet alloc]init]; + } + if(_pool == nil) { + // setup static vars + // create queue + sharedQueue = [[NSOperationQueue alloc] init]; + + // create pool + _pool = [[NSMutableDictionary alloc] init]; + + // initialize URL cache + [SWGApiClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + + // configure reachability + [SWGApiClient configureCacheReachibilityForHost:baseUrl]; + } + + @synchronized(self) { + SWGApiClient * client = [_pool objectForKey:baseUrl]; + if (client == nil) { + client = [[SWGApiClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; + [client registerHTTPOperationClass:[AFJSONRequestOperation class]]; + client.parameterEncoding = AFJSONParameterEncoding; + [_pool setValue:client forKey:baseUrl ]; + if(loggingEnabled) + NSLog(@"new client for path %@", baseUrl); + } + if(loggingEnabled) + NSLog(@"returning client for path %@", baseUrl); + return client; + } +} + +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey { + [self setDefaultHeader:forKey value:value]; +} + ++(unsigned long)requestQueueSize { + return [queuedRequests count]; +} + ++(NSNumber*) nextRequestId { + long nextId = ++requestId; + if(loggingEnabled) + NSLog(@"got id %ld", nextId); + return [NSNumber numberWithLong:nextId]; +} + ++(NSNumber*) queueRequest { + NSNumber* requestId = [SWGApiClient nextRequestId]; + if(loggingEnabled) + NSLog(@"added %@ to request queue", requestId); + [queuedRequests addObject:requestId]; + return requestId; +} + ++(void) cancelRequest:(NSNumber*)requestId { + [queuedRequests removeObject:requestId]; +} + ++(NSString*) escape:(id)unescaped { + if([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } +} + +-(Boolean) executeRequestWithId:(NSNumber*) requestId { + NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { + if([obj intValue] == [requestId intValue]) + return TRUE; + else return FALSE; + }]; + + if(matchingItems.count == 1) { + if(loggingEnabled) + NSLog(@"removing request id %@", requestId); + [queuedRequests removeObject:requestId]; + return true; + } + else + return false; +} + +-(id)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + if (!self) + return nil; + return self; +} + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + ++(void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++(void) configureCacheReachibilityForHost:(NSString*)host { + [[SWGApiClient sharedClientFromPool:host ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + switch (status) { + case AFNetworkReachabilityStatusUnknown: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + [SWGApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusNotReachable: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + [SWGApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusReachableViaWWAN: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + [SWGApiClient setOfflineState:false]; + break; + + case AFNetworkReachabilityStatusReachableViaWiFi: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + [SWGApiClient setOfflineState:false]; + break; + default: + break; + } + // call the reachability block, if configured + if(reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; +} + +-(NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + NSString * separator = nil; + int counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + if(queryParams != nil){ + for(NSString * key in [queryParams keyEnumerator]){ + if(counter == 0) separator = @"?"; + else separator = @"&"; + NSString * value; + if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ + value = [SWGApiClient escape:[queryParams valueForKey:key]]; + } + else { + value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; + } + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [SWGApiClient escape:key], value]]; + counter += 1; + } + } + return requestUrl; +} + +- (NSString*)descriptionForRequest:(NSURLRequest*)request { + return [[request URL] absoluteString]; +} + +- (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 ); +} + + +-(NSNumber*) dictionary:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock { + + NSMutableURLRequest * request = nil; + + if ([body isKindOfClass:[SWGFile class]]){ + SWGFile * file = (SWGFile*) body; + + request = [self multipartFormRequestWithMethod:@"POST" + path:path + parameters:nil + constructingBodyWithBlock: ^(id formData) { + [formData appendPartWithFileData:[file data] + name:@"image" + fileName:[file name] + mimeType:[file mimeType]]; + }]; + } + else { + request = [self requestWithMethod:method + path:[self pathWithQueryParamsToString:path queryParams:queryParams] + parameters:body]; + } + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) + hasHeaderParams = true; + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(body != nil) { + if([body isKindOfClass:[NSDictionary class]]){ + [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + } + else if ([body isKindOfClass:[SWGFile class]]) {} + else { + NSAssert(false, @"unsupported post type!"); + } + } + if(headerParams != nil){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"]; + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + + if (self.logRequests) { + [self logRequest:request]; + } + + NSNumber* requestId = [SWGApiClient queueRequest]; + AFJSONRequestOperation *op = + [AFJSONRequestOperation + JSONRequestOperationWithRequest:request + success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:JSON forRequest:request error:nil]; + completionBlock(JSON, nil); + } + } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:nil forRequest:request error:error]; + completionBlock(nil, error); + } + } + ]; + + [self enqueueHTTPRequestOperation:op]; + return requestId; +} + +-(NSNumber*) stringWithCompletionBlock:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSString*, NSError *))completionBlock { + AFHTTPClient *client = self; + client.parameterEncoding = AFJSONParameterEncoding; + + NSMutableURLRequest * request = nil; + + if ([body isKindOfClass:[SWGFile class]]){ + SWGFile * file = (SWGFile*) body; + + request = [self multipartFormRequestWithMethod:@"POST" + path:path + parameters:nil + constructingBodyWithBlock: ^(id formData) { + [formData appendPartWithFileData:[file data] + name:@"image" + fileName:[file name] + mimeType:[file mimeType]]; + }]; + } + else { + request = [self requestWithMethod:method + path:[self pathWithQueryParamsToString:path queryParams:queryParams] + parameters:body]; + } + + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) + hasHeaderParams = true; + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(body != nil) { + if([body isKindOfClass:[NSDictionary class]]){ + [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + } + else if ([body isKindOfClass:[SWGFile class]]){} + else { + NSAssert(false, @"unsupported post type!"); + } + } + if(headerParams != nil){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"]; + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSNumber* requestId = [SWGApiClient queueRequest]; + AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; + [op setCompletionBlockWithSuccess: + ^(AFHTTPRequestOperation *resp, + id responseObject) { + NSString *response = [resp responseString]; + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:responseObject forRequest:request error:nil]; + completionBlock(response, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:nil forRequest:request error:error]; + completionBlock(nil, error); + } + }]; + + [self enqueueHTTPRequestOperation:op]; + return requestId; +} + +@end diff --git a/samples/client/petstore/objc/client/SWGCategory.h b/samples/client/petstore/objc/client/SWGCategory.h new file mode 100644 index 00000000000..275d2cc32e2 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGCategory.h @@ -0,0 +1,18 @@ +#import +#import "SWGObject.h" + +@interface SWGCategory : SWGObject + +@property(nonatomic) NSNumber* _id; /* Category unique identifier [optional]*/ + +@property(nonatomic) NSString* name; /* Name of the category [optional]*/ + +- (id) _id: (NSNumber*) _id + name: (NSString*) name; + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + + +@end + diff --git a/samples/client/petstore/objc/client/RVBCategory.m b/samples/client/petstore/objc/client/SWGCategory.m similarity index 64% rename from samples/client/petstore/objc/client/RVBCategory.m rename to samples/client/petstore/objc/client/SWGCategory.m index 80223cf52ec..4058217c9e1 100644 --- a/samples/client/petstore/objc/client/RVBCategory.m +++ b/samples/client/petstore/objc/client/SWGCategory.m @@ -1,13 +1,13 @@ -#import "NIKDate.h" -#import "RVBCategory.h" +#import "SWGDate.h" +#import "SWGCategory.h" -@implementation RVBCategory +@implementation SWGCategory --(id)name: (NSString*) name - _id: (NSNumber*) _id +-(id)_id: (NSNumber*) _id + name: (NSString*) name { - _name = name; __id = _id; + _name = name; return self; } @@ -15,8 +15,8 @@ { self = [super init]; if(self) { - _name = dict[@"name"]; __id = dict[@"id"]; + _name = dict[@"name"]; } @@ -25,9 +25,9 @@ -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(_name != nil) dict[@"name"] = _name ; if(__id != nil) dict[@"id"] = __id ; - NSDictionary* output = [dict copy]; + if(_name != nil) dict[@"name"] = _name ; + NSDictionary* output = [dict copy]; return output; } diff --git a/samples/client/petstore/objc/client/NIKDate.h b/samples/client/petstore/objc/client/SWGDate.h similarity index 72% rename from samples/client/petstore/objc/client/NIKDate.h rename to samples/client/petstore/objc/client/SWGDate.h index 3af47f7e4fc..2c6c7cfe01b 100644 --- a/samples/client/petstore/objc/client/NIKDate.h +++ b/samples/client/petstore/objc/client/SWGDate.h @@ -1,7 +1,7 @@ #import -#import "NIKSwaggerObject.h" +#import "SWGObject.h" -@interface NIKDate : NIKSwaggerObject { +@interface SWGDate : SWGObject { @private NSDate *_date; } diff --git a/samples/client/petstore/objc/client/NIKDate.m b/samples/client/petstore/objc/client/SWGDate.m similarity index 95% rename from samples/client/petstore/objc/client/NIKDate.m rename to samples/client/petstore/objc/client/SWGDate.m index c1f9a163deb..07a1405626b 100644 --- a/samples/client/petstore/objc/client/NIKDate.m +++ b/samples/client/petstore/objc/client/SWGDate.m @@ -1,6 +1,6 @@ -#import "NIKDate.h" +#import "SWGDate.h" -@implementation NIKDate +@implementation SWGDate @synthesize date = _date; diff --git a/samples/client/petstore/objc/client/NIKFile.h b/samples/client/petstore/objc/client/SWGFile.h similarity index 75% rename from samples/client/petstore/objc/client/NIKFile.h rename to samples/client/petstore/objc/client/SWGFile.h index 03409257677..fe6e81c289d 100644 --- a/samples/client/petstore/objc/client/NIKFile.h +++ b/samples/client/petstore/objc/client/SWGFile.h @@ -1,11 +1,7 @@ #import -@interface NIKFile : NSObject { -@private - NSString* name; - NSString* mimeType; - NSData* data; -} +@interface SWGFile : NSObject + @property(nonatomic, readonly) NSString* name; @property(nonatomic, readonly) NSString* mimeType; @property(nonatomic, readonly) NSData* data; diff --git a/samples/client/petstore/objc/client/NIKFile.m b/samples/client/petstore/objc/client/SWGFile.m similarity index 90% rename from samples/client/petstore/objc/client/NIKFile.m rename to samples/client/petstore/objc/client/SWGFile.m index b743161a389..42552767af4 100644 --- a/samples/client/petstore/objc/client/NIKFile.m +++ b/samples/client/petstore/objc/client/SWGFile.m @@ -1,6 +1,6 @@ -#import "NIKFile.h" +#import "SWGFile.h" -@implementation NIKFile +@implementation SWGFile @synthesize name = _name; @synthesize mimeType = _mimeType; diff --git a/samples/client/petstore/objc/client/SWGObject.h b/samples/client/petstore/objc/client/SWGObject.h new file mode 100644 index 00000000000..031bae69279 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGObject.h @@ -0,0 +1,6 @@ +#import + +@interface SWGObject : NSObject +- (id) initWithValues:(NSDictionary*)dict; +- (NSDictionary*) asDictionary; +@end diff --git a/samples/client/petstore/objc/client/SWGObject.m b/samples/client/petstore/objc/client/SWGObject.m new file mode 100644 index 00000000000..9b37b3592b1 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGObject.m @@ -0,0 +1,17 @@ +#import "SWGObject.h" + +@implementation SWGObject + +- (id) initWithValues:(NSDictionary*)dict { + return self; +} + +- (NSDictionary*) asDictionary{ + return [NSDictionary init]; +} + +- (NSString*)description { + return [NSString stringWithFormat:@"%@ %@", [super description], [self asDictionary]]; +} + +@end diff --git a/samples/client/petstore/objc/client/SWGOrder.h b/samples/client/petstore/objc/client/SWGOrder.h new file mode 100644 index 00000000000..37ba0a29852 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGOrder.h @@ -0,0 +1,28 @@ +#import +#import "SWGObject.h" +#import "SWGDate.h" + +@interface SWGOrder : SWGObject + +@property(nonatomic) NSNumber* _id; /* Unique identifier for the order [optional]*/ + +@property(nonatomic) NSNumber* petId; /* ID of pet being ordered [optional]*/ + +@property(nonatomic) NSNumber* quantity; /* Number of pets ordered [optional]*/ + +@property(nonatomic) NSString* status; /* Status of the order [optional]*/ + +@property(nonatomic) SWGDate* shipDate; /* Date shipped, only if it has been [optional]*/ + +- (id) _id: (NSNumber*) _id + petId: (NSNumber*) petId + quantity: (NSNumber*) quantity + status: (NSString*) status + shipDate: (SWGDate*) shipDate; + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + + +@end + diff --git a/samples/client/petstore/objc/client/RVBOrder.m b/samples/client/petstore/objc/client/SWGOrder.m similarity index 57% rename from samples/client/petstore/objc/client/RVBOrder.m rename to samples/client/petstore/objc/client/SWGOrder.m index a195e2219c4..cdcf432bb88 100644 --- a/samples/client/petstore/objc/client/RVBOrder.m +++ b/samples/client/petstore/objc/client/SWGOrder.m @@ -1,18 +1,18 @@ -#import "NIKDate.h" -#import "RVBOrder.h" +#import "SWGDate.h" +#import "SWGOrder.h" -@implementation RVBOrder +@implementation SWGOrder -(id)_id: (NSNumber*) _id - status: (NSString*) status petId: (NSNumber*) petId quantity: (NSNumber*) quantity - shipDate: (NIKDate*) shipDate + status: (NSString*) status + shipDate: (SWGDate*) shipDate { __id = _id; - _status = status; _petId = petId; _quantity = quantity; + _status = status; _shipDate = shipDate; return self; } @@ -22,11 +22,12 @@ self = [super init]; if(self) { __id = dict[@"id"]; - _status = dict[@"status"]; _petId = dict[@"petId"]; _quantity = dict[@"quantity"]; + _status = dict[@"status"]; id shipDate_dict = dict[@"shipDate"]; - _shipDate = [[NIKDate alloc]initWithValues:shipDate_dict]; + if(shipDate_dict != nil) + _shipDate = [[SWGDate alloc]initWithValues:shipDate_dict]; } @@ -36,26 +37,26 @@ -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; if(__id != nil) dict[@"id"] = __id ; - if(_status != nil) dict[@"status"] = _status ; - if(_petId != nil) dict[@"petId"] = _petId ; - if(_quantity != nil) dict[@"quantity"] = _quantity ; - if(_shipDate != nil){ + if(_petId != nil) dict[@"petId"] = _petId ; + if(_quantity != nil) dict[@"quantity"] = _quantity ; + if(_status != nil) dict[@"status"] = _status ; + if(_shipDate != nil){ if([_shipDate isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; - for( NIKDate *shipDate in (NSArray*)_shipDate) { - [array addObject:[(NIKSwaggerObject*)shipDate asDictionary]]; + for( SWGDate *shipDate in (NSArray*)_shipDate) { + [array addObject:[(SWGObject*)shipDate asDictionary]]; } dict[@"shipDate"] = array; } - else if(_shipDate && [_shipDate isKindOfClass:[NIKDate class]]) { - NSString * dateString = [(NIKDate*)_shipDate toString]; + else if(_shipDate && [_shipDate isKindOfClass:[SWGDate class]]) { + NSString * dateString = [(SWGDate*)_shipDate toString]; if(dateString){ dict[@"shipDate"] = dateString; } } - } - else { - if(_shipDate != nil) dict[@"shipDate"] = [(NIKSwaggerObject*)_shipDate asDictionary]; + else { + if(_shipDate != nil) dict[@"shipDate"] = [(SWGObject*)_shipDate asDictionary]; + } } NSDictionary* output = [dict copy]; return output; diff --git a/samples/client/petstore/objc/client/SWGPet.h b/samples/client/petstore/objc/client/SWGPet.h new file mode 100644 index 00000000000..910bf4b7da4 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGPet.h @@ -0,0 +1,32 @@ +#import +#import "SWGObject.h" +#import "SWGCategory.h" +#import "SWGTag.h" + +@interface SWGPet : SWGObject + +@property(nonatomic) NSNumber* _id; /* Unique identifier for the Pet */ + +@property(nonatomic) SWGCategory* category; /* Category the pet is in [optional]*/ + +@property(nonatomic) NSString* name; /* Friendly name of the pet */ + +@property(nonatomic) NSArray* photoUrls; /* Image URLs [optional]*/ + +@property(nonatomic) NSArray* tags; /* Tags assigned to this pet [optional]*/ + +@property(nonatomic) NSString* status; /* pet status in the store [optional]*/ + +- (id) _id: (NSNumber*) _id + category: (SWGCategory*) category + name: (NSString*) name + photoUrls: (NSArray*) photoUrls + tags: (NSArray*) tags + status: (NSString*) status; + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + + +@end + diff --git a/samples/client/petstore/objc/client/RVBPet.m b/samples/client/petstore/objc/client/SWGPet.m similarity index 62% rename from samples/client/petstore/objc/client/RVBPet.m rename to samples/client/petstore/objc/client/SWGPet.m index f27fef44594..4bbfe48a8ea 100644 --- a/samples/client/petstore/objc/client/RVBPet.m +++ b/samples/client/petstore/objc/client/SWGPet.m @@ -1,21 +1,21 @@ -#import "NIKDate.h" -#import "RVBPet.h" +#import "SWGDate.h" +#import "SWGPet.h" -@implementation RVBPet +@implementation SWGPet --(id)name: (NSString*) name - _id: (NSNumber*) _id +-(id)_id: (NSNumber*) _id + category: (SWGCategory*) category + name: (NSString*) name + photoUrls: (NSArray*) photoUrls tags: (NSArray*) tags status: (NSString*) status - photoUrls: (NSArray*) photoUrls - category: (RVBCategory*) category { - _name = name; __id = _id; + _category = category; + _name = name; + _photoUrls = photoUrls; _tags = tags; _status = status; - _photoUrls = photoUrls; - _category = category; return self; } @@ -23,8 +23,12 @@ { self = [super init]; if(self) { - _name = dict[@"name"]; __id = dict[@"id"]; + id category_dict = dict[@"category"]; + if(category_dict != nil) + _category = [[SWGCategory alloc]initWithValues:category_dict]; + _name = dict[@"name"]; + _photoUrls = dict[@"photoUrls"]; id tags_dict = dict[@"tags"]; if([tags_dict isKindOfClass:[NSArray class]]) { @@ -32,7 +36,7 @@ if([(NSArray*)tags_dict count] > 0) { for (NSDictionary* dict in (NSArray*)tags_dict) { - RVBTag* d = [[RVBTag alloc] initWithValues:dict]; + SWGTag* d = [[SWGTag alloc] initWithValues:dict]; [objs addObject:d]; } @@ -46,9 +50,6 @@ _tags = [[NSArray alloc] init]; } _status = dict[@"status"]; - _photoUrls = dict[@"photoUrls"]; - id category_dict = dict[@"category"]; - _category = [[RVBCategory alloc]initWithValues:category_dict]; } @@ -57,47 +58,47 @@ -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(_name != nil) dict[@"name"] = _name ; if(__id != nil) dict[@"id"] = __id ; - if(_tags != nil){ - if([_tags isKindOfClass:[NSArray class]]){ - NSMutableArray * array = [[NSMutableArray alloc] init]; - for( RVBTag *tags in (NSArray*)_tags) { - [array addObject:[(NIKSwaggerObject*)tags asDictionary]]; - } - dict[@"tags"] = array; - } - else if(_tags && [_tags isKindOfClass:[NIKDate class]]) { - NSString * dateString = [(NIKDate*)_tags toString]; - if(dateString){ - dict[@"tags"] = dateString; - } - } - } - else { - if(_tags != nil) dict[@"tags"] = [(NIKSwaggerObject*)_tags asDictionary]; - } - if(_status != nil) dict[@"status"] = _status ; - if(_photoUrls != nil) dict[@"photoUrls"] = _photoUrls ; - if(_category != nil){ + if(_category != nil){ if([_category isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; - for( RVBCategory *category in (NSArray*)_category) { - [array addObject:[(NIKSwaggerObject*)category asDictionary]]; + for( SWGCategory *category in (NSArray*)_category) { + [array addObject:[(SWGObject*)category asDictionary]]; } dict[@"category"] = array; } - else if(_category && [_category isKindOfClass:[NIKDate class]]) { - NSString * dateString = [(NIKDate*)_category toString]; + else if(_category && [_category isKindOfClass:[SWGDate class]]) { + NSString * dateString = [(SWGDate*)_category toString]; if(dateString){ dict[@"category"] = dateString; } } + else { + if(_category != nil) dict[@"category"] = [(SWGObject*)_category asDictionary]; + } } - else { - if(_category != nil) dict[@"category"] = [(NIKSwaggerObject*)_category asDictionary]; + if(_name != nil) dict[@"name"] = _name ; + if(_photoUrls != nil) dict[@"photoUrls"] = _photoUrls ; + if(_tags != nil){ + if([_tags isKindOfClass:[NSArray class]]){ + NSMutableArray * array = [[NSMutableArray alloc] init]; + for( SWGTag *tags in (NSArray*)_tags) { + [array addObject:[(SWGObject*)tags asDictionary]]; + } + dict[@"tags"] = array; + } + else if(_tags && [_tags isKindOfClass:[SWGDate class]]) { + NSString * dateString = [(SWGDate*)_tags toString]; + if(dateString){ + dict[@"tags"] = dateString; + } + } + else { + if(_tags != nil) dict[@"tags"] = [(SWGObject*)_tags asDictionary]; + } } - NSDictionary* output = [dict copy]; + if(_status != nil) dict[@"status"] = _status ; + NSDictionary* output = [dict copy]; return output; } diff --git a/samples/client/petstore/objc/client/SWGPetApi.h b/samples/client/petstore/objc/client/SWGPetApi.h new file mode 100644 index 00000000000..d680f0f1a6c --- /dev/null +++ b/samples/client/petstore/objc/client/SWGPetApi.h @@ -0,0 +1,102 @@ +#import +#import "SWGPet.h" +#import "SWGFile.h" + + +@interface SWGPetApi: NSObject + +-(void) addHeader:(NSString*)value forKey:(NSString*)key; +-(unsigned long) requestQueueSize; ++(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(void) setBasePath:(NSString*)basePath; ++(NSString*) getBasePath; +/** + + Find pet by ID + Returns a pet based on ID + @param petId ID of pet that needs to be fetched + */ +-(NSNumber*) getPetByIdWithCompletionBlock :(NSNumber*) petId + completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock; + +/** + + Deletes a pet + + @param petId Pet id to delete + */ +-(NSNumber*) deletePetWithCompletionBlock :(NSString*) petId + completionHandler: (void (^)(NSError* error))completionBlock; + +/** + + partial updates to a pet + + @param petId ID of pet that needs to be fetched + @param body Pet object that needs to be added to the store + */ +-(NSNumber*) partialUpdateWithCompletionBlock :(NSString*) petId + body:(SWGPet*) body + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; + +/** + + Updates a pet in the store with form data + + @param petId ID of pet that needs to be updated + @param name Updated name of the pet + @param status Updated status of the pet + */ +-(NSNumber*) updatePetWithFormWithCompletionBlock :(NSString*) petId + name:(NSString*) name + status:(NSString*) status + completionHandler: (void (^)(NSError* error))completionBlock; + +/** + + uploads an image + + @param additionalMetadata Additional data to pass to server + @param body file to upload + */ +-(NSNumber*) uploadFileWithCompletionBlock :(NSString*) additionalMetadata + body:(SWGFile*) body + completionHandler: (void (^)(NSError* error))completionBlock; + +/** + + Add a new pet to the store + + @param body Pet object that needs to be added to the store + */ +-(NSNumber*) addPetWithCompletionBlock :(SWGPet*) body + completionHandler: (void (^)(NSError* error))completionBlock; + +/** + + Update an existing pet + + @param body Pet object that needs to be updated in the store + */ +-(NSNumber*) updatePetWithCompletionBlock :(SWGPet*) body + completionHandler: (void (^)(NSError* error))completionBlock; + +/** + + Finds Pets by status + Multiple status values can be provided with comma seperated strings + @param status Status values that need to be considered for filter + */ +-(NSNumber*) findPetsByStatusWithCompletionBlock :(NSString*) status + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; + +/** + + Finds Pets by tags + Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + @param tags Tags to filter by + */ +-(NSNumber*) findPetsByTagsWithCompletionBlock :(NSString*) tags + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock; + +@end diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m new file mode 100644 index 00000000000..5892bac787a --- /dev/null +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -0,0 +1,564 @@ +#import "SWGPetApi.h" +#import "SWGFile.h" +#import "SWGApiClient.h" +#import "SWGPet.h" +#import "SWGFile.h" + + + +@implementation SWGPetApi +static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; + ++(SWGPetApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { + static SWGPetApi* singletonAPI = nil; + + if (singletonAPI == nil) { + singletonAPI = [[SWGPetApi alloc] init]; + [singletonAPI addHeader:headerValue forKey:key]; + } + return singletonAPI; +} + ++(void) setBasePath:(NSString*)path { + basePath = path; +} + ++(NSString*) getBasePath { + return basePath; +} + +-(SWGApiClient*) apiClient { + return [SWGApiClient sharedClientFromPool:basePath]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(id) init { + self = [super init]; + [self apiClient]; + return self; +} + +-(void) setHeaderValue:(NSString*) value + forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(unsigned long) requestQueueSize { + return [SWGApiClient requestQueueSize]; +} + + +-(NSNumber*) getPetByIdWithCompletionBlock:(NSNumber*) petId + completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(petId == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client dictionary:requestUrl + method:@"GET" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType:requestContentType + responseContentType:responseContentType + completionBlock:^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error);return; + } + SWGPet *result = nil; + if (data) { + result = [[SWGPet alloc]initWithValues: data]; + } + completionBlock(result , nil);}]; + + +} + +-(NSNumber*) deletePetWithCompletionBlock:(NSString*) petId + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(petId == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"DELETE" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) partialUpdateWithCompletionBlock:(NSString*) petId + body:(SWGPet*) body + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(petId == nil) { + // error + } + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client dictionary: requestUrl + method: @"PATCH" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error);return; + } + + if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + [objs addObject:d]; + } + completionBlock(objs, nil); + } + }]; + + +} + +-(NSNumber*) updatePetWithFormWithCompletionBlock:(NSString*) petId + name:(NSString*) name + status:(NSString*) status + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(petId == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) uploadFileWithCompletionBlock:(NSString*) additionalMetadata + body:(SWGFile*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/uploadImage", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) addPetWithCompletionBlock:(SWGPet*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) updatePetWithCompletionBlock:(SWGPet*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"PUT" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) findPetsByStatusWithCompletionBlock:(NSString*) status + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + if(status != nil) + queryParams[@"status"] = status; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(status == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error);return; + } + + if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + [objs addObject:d]; + } + completionBlock(objs, nil); + } + }]; + + +} + +-(NSNumber*) findPetsByTagsWithCompletionBlock:(NSString*) tags + completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + if(tags != nil) + queryParams[@"tags"] = tags; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(tags == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client dictionary: requestUrl + method: @"GET" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error);return; + } + + if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + [objs addObject:d]; + } + completionBlock(objs, nil); + } + }]; + + +} + + +@end diff --git a/samples/client/petstore/objc/client/RVBStoreApi.h b/samples/client/petstore/objc/client/SWGStoreApi.h similarity index 60% rename from samples/client/petstore/objc/client/RVBStoreApi.h rename to samples/client/petstore/objc/client/SWGStoreApi.h index 3b5343d106d..190ef5ec09d 100644 --- a/samples/client/petstore/objc/client/RVBStoreApi.h +++ b/samples/client/petstore/objc/client/SWGStoreApi.h @@ -1,27 +1,22 @@ #import -#import "NIKApiInvoker.h" -#import "RVBOrder.h" +#import "SWGOrder.h" -@interface RVBStoreApi: NSObject { - -@private - NSOperationQueue *_queue; - NIKApiInvoker * _api; -} -@property(nonatomic, readonly) NSOperationQueue* queue; -@property(nonatomic, readonly) NIKApiInvoker* api; +@interface SWGStoreApi: NSObject -(void) addHeader:(NSString*)value forKey:(NSString*)key; - +-(unsigned long) requestQueueSize; ++(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(void) setBasePath:(NSString*)basePath; ++(NSString*) getBasePath; /** Find purchase order by ID For valid response try integer IDs with value <= 5. Anything above 5 or nonintegers will generate API errors @param orderId ID of pet that needs to be fetched */ --(void) getOrderByIdWithCompletionBlock :(NSString*) orderId - completionHandler: (void (^)(RVBOrder* output, NSError* error))completionBlock; +-(NSNumber*) getOrderByIdWithCompletionBlock :(NSString*) orderId + completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock; /** @@ -29,7 +24,7 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @param orderId ID of the order that needs to be deleted */ --(void) deleteOrderWithCompletionBlock :(NSString*) orderId +-(NSNumber*) deleteOrderWithCompletionBlock :(NSString*) orderId completionHandler: (void (^)(NSError* error))completionBlock; /** @@ -38,7 +33,7 @@ @param body order placed for purchasing the pet */ --(void) placeOrderWithCompletionBlock :(RVBOrder*) body +-(NSNumber*) placeOrderWithCompletionBlock :(SWGOrder*) body completionHandler: (void (^)(NSError* error))completionBlock; @end diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m new file mode 100644 index 00000000000..d9bda70646c --- /dev/null +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -0,0 +1,205 @@ +#import "SWGStoreApi.h" +#import "SWGFile.h" +#import "SWGApiClient.h" +#import "SWGOrder.h" + + + +@implementation SWGStoreApi +static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; + ++(SWGStoreApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { + static SWGStoreApi* singletonAPI = nil; + + if (singletonAPI == nil) { + singletonAPI = [[SWGStoreApi alloc] init]; + [singletonAPI addHeader:headerValue forKey:key]; + } + return singletonAPI; +} + ++(void) setBasePath:(NSString*)path { + basePath = path; +} + ++(NSString*) getBasePath { + return basePath; +} + +-(SWGApiClient*) apiClient { + return [SWGApiClient sharedClientFromPool:basePath]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(id) init { + self = [super init]; + [self apiClient]; + return self; +} + +-(void) setHeaderValue:(NSString*) value + forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(unsigned long) requestQueueSize { + return [SWGApiClient requestQueueSize]; +} + + +-(NSNumber*) getOrderByIdWithCompletionBlock:(NSString*) orderId + completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(orderId == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client dictionary:requestUrl + method:@"GET" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType:requestContentType + responseContentType:responseContentType + completionBlock:^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error);return; + } + SWGOrder *result = nil; + if (data) { + result = [[SWGOrder alloc]initWithValues: data]; + } + completionBlock(result , nil);}]; + + +} + +-(NSNumber*) deleteOrderWithCompletionBlock:(NSString*) orderId + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"orderId", @"}"]] withString: [SWGApiClient escape:orderId]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(orderId == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"DELETE" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) placeOrderWithCompletionBlock:(SWGOrder*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + + +@end diff --git a/samples/client/petstore/objc/client/SWGTag.h b/samples/client/petstore/objc/client/SWGTag.h new file mode 100644 index 00000000000..3a516dcf7df --- /dev/null +++ b/samples/client/petstore/objc/client/SWGTag.h @@ -0,0 +1,18 @@ +#import +#import "SWGObject.h" + +@interface SWGTag : SWGObject + +@property(nonatomic) NSNumber* _id; /* Unique identifier for the tag [optional]*/ + +@property(nonatomic) NSString* name; /* Friendly name for the tag [optional]*/ + +- (id) _id: (NSNumber*) _id + name: (NSString*) name; + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + + +@end + diff --git a/samples/client/petstore/objc/client/RVBTag.m b/samples/client/petstore/objc/client/SWGTag.m similarity index 65% rename from samples/client/petstore/objc/client/RVBTag.m rename to samples/client/petstore/objc/client/SWGTag.m index c93d8114719..0949e5eaa45 100644 --- a/samples/client/petstore/objc/client/RVBTag.m +++ b/samples/client/petstore/objc/client/SWGTag.m @@ -1,13 +1,13 @@ -#import "NIKDate.h" -#import "RVBTag.h" +#import "SWGDate.h" +#import "SWGTag.h" -@implementation RVBTag +@implementation SWGTag --(id)name: (NSString*) name - _id: (NSNumber*) _id +-(id)_id: (NSNumber*) _id + name: (NSString*) name { - _name = name; __id = _id; + _name = name; return self; } @@ -15,8 +15,8 @@ { self = [super init]; if(self) { - _name = dict[@"name"]; __id = dict[@"id"]; + _name = dict[@"name"]; } @@ -25,9 +25,9 @@ -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; - if(_name != nil) dict[@"name"] = _name ; if(__id != nil) dict[@"id"] = __id ; - NSDictionary* output = [dict copy]; + if(_name != nil) dict[@"name"] = _name ; + NSDictionary* output = [dict copy]; return output; } diff --git a/samples/client/petstore/objc/client/SWGUser.h b/samples/client/petstore/objc/client/SWGUser.h new file mode 100644 index 00000000000..608235475a0 --- /dev/null +++ b/samples/client/petstore/objc/client/SWGUser.h @@ -0,0 +1,36 @@ +#import +#import "SWGObject.h" + +@interface SWGUser : SWGObject + +@property(nonatomic) NSNumber* _id; /* Unique identifier for the user [optional]*/ + +@property(nonatomic) NSString* username; /* Unique username [optional]*/ + +@property(nonatomic) NSString* firstName; /* First name of the user [optional]*/ + +@property(nonatomic) NSString* lastName; /* Last name of the user [optional]*/ + +@property(nonatomic) NSString* email; /* Email address of the user [optional]*/ + +@property(nonatomic) NSString* password; /* Password name of the user [optional]*/ + +@property(nonatomic) NSString* phone; /* Phone number of the user [optional]*/ + +@property(nonatomic) NSNumber* userStatus; /* User Status [optional]*/ + +- (id) _id: (NSNumber*) _id + username: (NSString*) username + firstName: (NSString*) firstName + lastName: (NSString*) lastName + email: (NSString*) email + password: (NSString*) password + phone: (NSString*) phone + userStatus: (NSNumber*) userStatus; + +- (id) initWithValues: (NSDictionary*)dict; +- (NSDictionary*) asDictionary; + + +@end + diff --git a/samples/client/petstore/objc/client/RVBUser.m b/samples/client/petstore/objc/client/SWGUser.m similarity index 66% rename from samples/client/petstore/objc/client/RVBUser.m rename to samples/client/petstore/objc/client/SWGUser.m index b857f69c757..a84b2a91f55 100644 --- a/samples/client/petstore/objc/client/RVBUser.m +++ b/samples/client/petstore/objc/client/SWGUser.m @@ -1,11 +1,11 @@ -#import "NIKDate.h" -#import "RVBUser.h" +#import "SWGDate.h" +#import "SWGUser.h" -@implementation RVBUser +@implementation SWGUser -(id)_id: (NSNumber*) _id - firstName: (NSString*) firstName username: (NSString*) username + firstName: (NSString*) firstName lastName: (NSString*) lastName email: (NSString*) email password: (NSString*) password @@ -13,8 +13,8 @@ userStatus: (NSNumber*) userStatus { __id = _id; - _firstName = firstName; _username = username; + _firstName = firstName; _lastName = lastName; _email = email; _password = password; @@ -28,8 +28,8 @@ self = [super init]; if(self) { __id = dict[@"id"]; - _firstName = dict[@"firstName"]; _username = dict[@"username"]; + _firstName = dict[@"firstName"]; _lastName = dict[@"lastName"]; _email = dict[@"email"]; _password = dict[@"password"]; @@ -44,14 +44,14 @@ -(NSDictionary*) asDictionary { NSMutableDictionary* dict = [[NSMutableDictionary alloc] init]; if(__id != nil) dict[@"id"] = __id ; - if(_firstName != nil) dict[@"firstName"] = _firstName ; - if(_username != nil) dict[@"username"] = _username ; - if(_lastName != nil) dict[@"lastName"] = _lastName ; - if(_email != nil) dict[@"email"] = _email ; - if(_password != nil) dict[@"password"] = _password ; - if(_phone != nil) dict[@"phone"] = _phone ; - if(_userStatus != nil) dict[@"userStatus"] = _userStatus ; - NSDictionary* output = [dict copy]; + if(_username != nil) dict[@"username"] = _username ; + if(_firstName != nil) dict[@"firstName"] = _firstName ; + if(_lastName != nil) dict[@"lastName"] = _lastName ; + if(_email != nil) dict[@"email"] = _email ; + if(_password != nil) dict[@"password"] = _password ; + if(_phone != nil) dict[@"phone"] = _phone ; + if(_userStatus != nil) dict[@"userStatus"] = _userStatus ; + NSDictionary* output = [dict copy]; return output; } diff --git a/samples/client/petstore/objc/client/RVBUserApi.h b/samples/client/petstore/objc/client/SWGUserApi.h similarity index 62% rename from samples/client/petstore/objc/client/RVBUserApi.h rename to samples/client/petstore/objc/client/SWGUserApi.h index dd0fd5e047e..fa345b96165 100644 --- a/samples/client/petstore/objc/client/RVBUserApi.h +++ b/samples/client/petstore/objc/client/SWGUserApi.h @@ -1,26 +1,21 @@ #import -#import "NIKApiInvoker.h" -#import "RVBUser.h" +#import "SWGUser.h" -@interface RVBUserApi: NSObject { - -@private - NSOperationQueue *_queue; - NIKApiInvoker * _api; -} -@property(nonatomic, readonly) NSOperationQueue* queue; -@property(nonatomic, readonly) NIKApiInvoker* api; +@interface SWGUserApi: NSObject -(void) addHeader:(NSString*)value forKey:(NSString*)key; - +-(unsigned long) requestQueueSize; ++(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(void) setBasePath:(NSString*)basePath; ++(NSString*) getBasePath; /** Create user This can only be done by the logged in user. @param body Created user object */ --(void) createUserWithCompletionBlock :(RVBUser*) body +-(NSNumber*) createUserWithCompletionBlock :(SWGUser*) body completionHandler: (void (^)(NSError* error))completionBlock; /** @@ -29,7 +24,7 @@ @param body List of user object */ --(void) createUsersWithArrayInputWithCompletionBlock :(NSArray*) body +-(NSNumber*) createUsersWithArrayInputWithCompletionBlock :(NSArray*) body completionHandler: (void (^)(NSError* error))completionBlock; /** @@ -38,7 +33,7 @@ @param body List of user object */ --(void) createUsersWithListInputWithCompletionBlock :(NSArray*) body +-(NSNumber*) createUsersWithListInputWithCompletionBlock :(NSArray*) body completionHandler: (void (^)(NSError* error))completionBlock; /** @@ -48,8 +43,8 @@ @param username name that need to be deleted @param body Updated user object */ --(void) updateUserWithCompletionBlock :(NSString*) username - body:(RVBUser*) body +-(NSNumber*) updateUserWithCompletionBlock :(NSString*) username + body:(SWGUser*) body completionHandler: (void (^)(NSError* error))completionBlock; /** @@ -58,7 +53,7 @@ This can only be done by the logged in user. @param username The name that needs to be deleted */ --(void) deleteUserWithCompletionBlock :(NSString*) username +-(NSNumber*) deleteUserWithCompletionBlock :(NSString*) username completionHandler: (void (^)(NSError* error))completionBlock; /** @@ -67,8 +62,8 @@ @param username The name that needs to be fetched. Use user1 for testing. */ --(void) getUserByNameWithCompletionBlock :(NSString*) username - completionHandler: (void (^)(RVBUser* output, NSError* error))completionBlock; +-(NSNumber*) getUserByNameWithCompletionBlock :(NSString*) username + completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock; /** @@ -77,7 +72,7 @@ @param username The user name for login @param password The password for login in clear text */ --(void) loginUserWithCompletionBlock :(NSString*) username +-(NSNumber*) loginUserWithCompletionBlock :(NSString*) username password:(NSString*) password completionHandler: (void (^)(NSString* output, NSError* error))completionBlock; @@ -86,6 +81,6 @@ Logs out current logged in user session */ --(void) logoutUserWithCompletionBlock :(void (^)(NSError* error))completionBlock; +-(NSNumber*) logoutUserWithCompletionBlock :(void (^)(NSError* error))completionBlock; @end diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m new file mode 100644 index 00000000000..72a6c16321b --- /dev/null +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -0,0 +1,504 @@ +#import "SWGUserApi.h" +#import "SWGFile.h" +#import "SWGApiClient.h" +#import "SWGUser.h" + + + +@implementation SWGUserApi +static NSString * basePath = @"http://petstore.swagger.wordnik.com/api"; + ++(SWGUserApi*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { + static SWGUserApi* singletonAPI = nil; + + if (singletonAPI == nil) { + singletonAPI = [[SWGUserApi alloc] init]; + [singletonAPI addHeader:headerValue forKey:key]; + } + return singletonAPI; +} + ++(void) setBasePath:(NSString*)path { + basePath = path; +} + ++(NSString*) getBasePath { + return basePath; +} + +-(SWGApiClient*) apiClient { + return [SWGApiClient sharedClientFromPool:basePath]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(id) init { + self = [super init]; + [self apiClient]; + return self; +} + +-(void) setHeaderValue:(NSString*) value + forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + +-(unsigned long) requestQueueSize { + return [SWGApiClient requestQueueSize]; +} + + +-(NSNumber*) createUserWithCompletionBlock:(SWGUser*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) createUsersWithArrayInputWithCompletionBlock:(NSArray*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) createUsersWithListInputWithCompletionBlock:(NSArray*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"POST" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) updateUserWithCompletionBlock:(NSString*) username + body:(SWGUser*) body + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(body != nil && [body isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] init]; + for (id dict in (NSArray*)body) { + if([dict respondsToSelector:@selector(asDictionary)]) { + [objs addObject:[(SWGObject*)dict asDictionary]]; + } + else{ + [objs addObject:dict]; + } + } + bodyDictionary = objs; + } + else if([body respondsToSelector:@selector(asDictionary)]) { + bodyDictionary = [(SWGObject*)body asDictionary]; + } + else if([body isKindOfClass:[NSString class]]) { + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; + } + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; + bodyDictionary = body; + } + else{ + NSLog(@"don't know what to do with %@", body); + } + + if(username == nil) { + // error + } + if(body == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"PUT" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) deleteUserWithCompletionBlock:(NSString*) username + completionHandler: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(username == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"DELETE" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + +-(NSNumber*) getUserByNameWithCompletionBlock:(NSString*) username + completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"username", @"}"]] withString: [SWGApiClient escape:username]]; + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(username == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client dictionary:requestUrl + method:@"GET" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType:requestContentType + responseContentType:responseContentType + completionBlock:^(NSDictionary *data, NSError *error) { + if (error) { + completionBlock(nil, error);return; + } + SWGUser *result = nil; + if (data) { + result = [[SWGUser alloc]initWithValues: data]; + } + completionBlock(result , nil);}]; + + +} + +-(NSNumber*) loginUserWithCompletionBlock:(NSString*) username + password:(NSString*) password + completionHandler: (void (^)(NSString* output, NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + if(username != nil) + queryParams[@"username"] = username; + if(password != nil) + queryParams[@"password"] = password; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + if(username == nil) { + // error + } + if(password == nil) { + // error + } + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"GET" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + NSString *result = data ? [[NSString alloc]initWithString: data] : nil; + completionBlock(result, nil); + }]; + + +} + +-(NSNumber*) logoutUserWithCompletionBlock: (void (^)(NSError* error))completionBlock{ + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; + + // remove format in URL if needed + if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) + [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; + + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; + id bodyDictionary = nil; + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + return [client stringWithCompletionBlock:requestUrl + method:@"GET" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + + +} + + +@end From 731fddbc30455827fc9bc0a4f81f02aae4057707 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:44:02 -0700 Subject: [PATCH 07/20] regenerated client --- .../src/Com/Wordnik/Petstore/Api/PetApi.cs | 115 +++++++++++- .../src/Com/Wordnik/Petstore/Api/UserApi.cs | 4 +- .../Com/Wordnik/Petstore/Model/Category.cs | 8 +- .../src/Com/Wordnik/Petstore/Model/Order.cs | 12 +- .../src/Com/Wordnik/Petstore/Model/Pet.cs | 23 ++- .../src/Com/Wordnik/Petstore/Model/Tag.cs | 8 +- .../src/Com/Wordnik/Petstore/Model/User.cs | 13 +- .../flex/com/wordnik/client/api/PetApi.as | 121 +++++++++++-- .../flex/com/wordnik/client/api/StoreApi.as | 6 +- .../flex/com/wordnik/client/api/UserApi.as | 66 +++---- .../flex/com/wordnik/client/model/Category.as | 2 + .../flex/com/wordnik/client/model/Order.as | 14 +- .../main/flex/com/wordnik/client/model/Pet.as | 29 +-- .../main/flex/com/wordnik/client/model/Tag.as | 2 + .../flex/com/wordnik/client/model/User.as | 39 ++-- samples/client/petstore/php/PetApi.php | 154 ++++++++++++++-- samples/client/petstore/php/StoreApi.php | 10 +- samples/client/petstore/php/Swagger.php | 57 ++++-- samples/client/petstore/php/UserApi.php | 44 ++--- .../client/petstore/php/models/Category.php | 6 + samples/client/petstore/php/models/Order.php | 18 +- samples/client/petstore/php/models/Pet.php | 27 ++- samples/client/petstore/php/models/Tag.php | 6 + samples/client/petstore/php/models/User.php | 39 +++- samples/client/petstore/python/PetApi.py | 169 ++++++++++++++++-- samples/client/petstore/python/StoreApi.py | 6 +- samples/client/petstore/python/UserApi.py | 80 ++++----- .../client/petstore/python/models/Category.py | 2 + .../client/petstore/python/models/Order.py | 10 +- samples/client/petstore/python/models/Pet.py | 17 +- samples/client/petstore/python/models/Tag.py | 2 + samples/client/petstore/python/models/User.py | 25 ++- samples/client/petstore/python/swagger.py | 43 +++-- samples/client/petstore/ruby/lib/Pet_api.rb | 163 +++++++++++++++-- samples/client/petstore/ruby/lib/Store_api.rb | 15 +- samples/client/petstore/ruby/lib/User_api.rb | 46 +++-- .../ruby/lib/swagger/configuration.rb | 5 +- .../petstore/ruby/lib/swagger/request.rb | 7 +- .../client/petstore/ruby/models/Category.rb | 29 ++- samples/client/petstore/ruby/models/Order.rb | 58 +++--- samples/client/petstore/ruby/models/Pet.rb | 81 ++++----- samples/client/petstore/ruby/models/Tag.rb | 29 ++- samples/client/petstore/ruby/models/User.rb | 85 ++++----- .../com/wordnik/petstore/api/UserApi.scala | 4 +- .../scala/src/test/scala/UserApiTest.scala | 4 +- 45 files changed, 1235 insertions(+), 468 deletions(-) diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs index b8139909921..733e22f12db 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/PetApi.cs @@ -26,7 +26,7 @@ /// /// ID of pet that needs to be fetched /// - public Pet getPetById (string petId) { + public Pet getPetById (long petId) { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); @@ -92,6 +92,111 @@ } } /// + /// partial updates to a pet + /// + /// ID of pet that needs to be fetched + /// Pet object that needs to be added to the store + /// + public Array partialUpdate (string petId, Pet body) { + // create path and map variables + var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (petId == null || body == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "PATCH", queryParams, body, headerParams); + if(response != null){ + return (Array) ApiInvoker.deserialize(response, typeof(Array)); + } + else { + return null; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return null; + } + else { + throw ex; + } + } + } + /// + /// Updates a pet in the store with form data + /// + /// ID of pet that needs to be updated + /// Updated name of the pet + /// Updated status of the pet + /// + public void updatePetWithForm (string petId, string name, string status) { + // create path and map variables + var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.escapeString(petId.ToString())); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + // verify required params are set + if (petId == null ) { + throw new ApiException(400, "missing required params"); + } + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + /// + /// uploads an image + /// + /// Additional data to pass to server + /// file to upload + /// + public void uploadFile (string additionalMetadata, File body) { + // create path and map variables + var path = "/pet/uploadImage".Replace("{format}","json"); + + // query params + var queryParams = new Dictionary(); + var headerParams = new Dictionary(); + + string paramStr = null; + try { + var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, body, headerParams); + if(response != null){ + return ; + } + else { + return ; + } + } catch (ApiException ex) { + if(ex.ErrorCode == 404) { + return ; + } + else { + throw ex; + } + } + } + /// /// Add a new pet to the store /// /// Pet object that needs to be added to the store @@ -166,7 +271,7 @@ /// /// Status values that need to be considered for filter /// - public List findPetsByStatus (string status) { + public Array findPetsByStatus (string status) { // create path and map variables var path = "/pet/findByStatus".Replace("{format}","json"); @@ -186,7 +291,7 @@ try { var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); if(response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); + return (Array) ApiInvoker.deserialize(response, typeof(Array)); } else { return null; @@ -205,7 +310,7 @@ /// /// Tags to filter by /// - public List findPetsByTags (string tags) { + public Array findPetsByTags (string tags) { // create path and map variables var path = "/pet/findByTags".Replace("{format}","json"); @@ -225,7 +330,7 @@ try { var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams); if(response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); + return (Array) ApiInvoker.deserialize(response, typeof(Array)); } else { return null; diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs index d94ce91baad..bde3ed4af4b 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Api/UserApi.cs @@ -61,7 +61,7 @@ /// /// List of user object /// - public void createUsersWithArrayInput (array body) { + public void createUsersWithArrayInput (List body) { // create path and map variables var path = "/user/createWithArray".Replace("{format}","json"); @@ -96,7 +96,7 @@ /// /// List of user object /// - public void createUsersWithListInput (array body) { + public void createUsersWithListInput (List body) { // create path and map variables var path = "/user/createWithList".Replace("{format}","json"); diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs index 29dafc57737..e5aa324be6c 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Category.cs @@ -5,15 +5,17 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Category { - public string name { get; set; } - + /* Category unique identifier */ public long id { get; set; } + /* Name of the category */ + public string name { get; set; } + public override string ToString() { var sb = new StringBuilder(); sb.Append("class Category {\n"); - sb.Append(" name: ").Append(name).Append("\n"); sb.Append(" id: ").Append(id).Append("\n"); + sb.Append(" name: ").Append(name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs index 72b65ad4206..d4d5a0d77a1 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Order.cs @@ -5,24 +5,28 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Order { + /* Unique identifier for the order */ public long id { get; set; } - /* Order Status */ - public string status { get; set; } - + /* ID of pet being ordered */ public long petId { get; set; } + /* Number of pets ordered */ public int quantity { get; set; } + /* Status of the order */ + public string status { get; set; } + + /* Date shipped, only if it has been */ public DateTime shipDate { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" status: ").Append(status).Append("\n"); sb.Append(" petId: ").Append(petId).Append("\n"); sb.Append(" quantity: ").Append(quantity).Append("\n"); + sb.Append(" status: ").Append(status).Append("\n"); sb.Append(" shipDate: ").Append(shipDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs index 92acc0f980d..87bca18a1f4 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Pet.cs @@ -5,28 +5,33 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Pet { - public string name { get; set; } - + /* Unique identifier for the Pet */ public long id { get; set; } + /* Category the pet is in */ + public Category category { get; set; } + + /* Friendly name of the pet */ + public string name { get; set; } + + /* Image URLs */ + public List photoUrls { get; set; } + + /* Tags assigned to this pet */ public List tags { get; set; } /* pet status in the store */ public string status { get; set; } - public List photoUrls { get; set; } - - public Category category { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Pet {\n"); - sb.Append(" name: ").Append(name).Append("\n"); sb.Append(" id: ").Append(id).Append("\n"); + sb.Append(" category: ").Append(category).Append("\n"); + sb.Append(" name: ").Append(name).Append("\n"); + sb.Append(" photoUrls: ").Append(photoUrls).Append("\n"); sb.Append(" tags: ").Append(tags).Append("\n"); sb.Append(" status: ").Append(status).Append("\n"); - sb.Append(" photoUrls: ").Append(photoUrls).Append("\n"); - sb.Append(" category: ").Append(category).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs index 64daaa61c72..8a4b38b656b 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/Tag.cs @@ -5,15 +5,17 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class Tag { - public string name { get; set; } - + /* Unique identifier for the tag */ public long id { get; set; } + /* Friendly name for the tag */ + public string name { get; set; } + public override string ToString() { var sb = new StringBuilder(); sb.Append("class Tag {\n"); - sb.Append(" name: ").Append(name).Append("\n"); sb.Append(" id: ").Append(id).Append("\n"); + sb.Append(" name: ").Append(name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } diff --git a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs index bbbd6eaccc3..adce974f71f 100644 --- a/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs +++ b/samples/client/petstore/csharp/src/Com/Wordnik/Petstore/Model/User.cs @@ -5,18 +5,25 @@ using System.Collections.Generic; namespace Com.Wordnik.Petstore.Model { public class User { + /* Unique identifier for the user */ public long id { get; set; } - public string firstName { get; set; } - + /* Unique username */ public string username { get; set; } + /* First name of the user */ + public string firstName { get; set; } + + /* Last name of the user */ public string lastName { get; set; } + /* Email address of the user */ public string email { get; set; } + /* Password name of the user */ public string password { get; set; } + /* Phone number of the user */ public string phone { get; set; } /* User Status */ @@ -26,8 +33,8 @@ namespace Com.Wordnik.Petstore.Model { var sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" id: ").Append(id).Append("\n"); - sb.Append(" firstName: ").Append(firstName).Append("\n"); sb.Append(" username: ").Append(username).Append("\n"); + sb.Append(" firstName: ").Append(firstName).Append("\n"); sb.Append(" lastName: ").Append(lastName).Append("\n"); sb.Append(" email: ").Append(email).Append("\n"); sb.Append(" password: ").Append(password).Append("\n"); diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as index cc320ab96ff..6891d8456bc 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/PetApi.as @@ -7,6 +7,7 @@ import com.wordnik.swagger.common.ApiUserCredentials; import com.wordnik.swagger.event.Response; import com.wordnik.swagger.common.SwaggerApi; import com.wordnik.client.model.Pet; +import com.wordnik.client.model.File; import mx.rpc.AsyncToken; import mx.utils.UIDUtil; import flash.utils.Dictionary; @@ -23,15 +24,19 @@ public class PetApi extends SwaggerApi { } public static const event_getPetById: String = "getPetById"; +public static const event_deletePet: String = "deletePet"; +public static const event_partialUpdate: String = "partialUpdate"; +public static const event_updatePetWithForm: String = "updatePetWithForm"; +public static const event_uploadFile: String = "uploadFile"; public static const event_addPet: String = "addPet"; public static const event_updatePet: String = "updatePet"; public static const event_findPetsByStatus: String = "findPetsByStatus"; public static const event_findPetsByTags: String = "findPetsByTags"; /* * Returns Pet */ - public function getPetById (petId: String): String { + public function getPetById (petId: Number): String { // create path and map variables - var path: String = "/pet.{format}/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); // query params var queryParams: Dictionary = new Dictionary(); @@ -51,12 +56,108 @@ public static const event_findPetsByTags: String = "findPetsByTags"; token.returnType = Pet; return requestId; + } + /* + * Returns void */ + public function deletePet (petId: String): String { + // create path and map variables + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + // verify required params are set + if(petId == null ) { + throw new ApiError(400, "missing required params"); + } + var token:AsyncToken = getApiInvoker().invokeAPI(path, "DELETE", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "deletePet"; + + token.returnType = null ; + return requestId; + + } + /* + * Returns Array[Pet] */ + public function partialUpdate (petId: String, body: Pet): String { + // create path and map variables + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + // verify required params are set + if(petId == null || body == null ) { + throw new ApiError(400, "missing required params"); + } + var token:AsyncToken = getApiInvoker().invokeAPI(path, "PATCH", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "partialUpdate"; + + token.returnType = Array[Pet]; + return requestId; + + } + /* + * Returns void */ + public function updatePetWithForm (petId: String, name: String, status: String): String { + // create path and map variables + var path: String = "/pet/{petId}".replace(/{format}/g,"xml").replace("{" + "petId" + "}", getApiInvoker().escapeString(petId)); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + // verify required params are set + if(petId == null ) { + throw new ApiError(400, "missing required params"); + } + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, null, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "updatePetWithForm"; + + token.returnType = null ; + return requestId; + + } + /* + * Returns void */ + public function uploadFile (additionalMetadata: String, body: File): String { + // create path and map variables + var path: String = "/pet/uploadImage".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "uploadFile"; + + token.returnType = null ; + return requestId; + } /* * Returns void */ public function addPet (body: Pet): String { // create path and map variables - var path: String = "/pet.{format}".replace(/{format}/g,"xml"); + var path: String = "/pet".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -81,7 +182,7 @@ public static const event_findPetsByTags: String = "findPetsByTags"; * Returns void */ public function updatePet (body: Pet): String { // create path and map variables - var path: String = "/pet.{format}".replace(/{format}/g,"xml"); + var path: String = "/pet".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -103,10 +204,10 @@ public static const event_findPetsByTags: String = "findPetsByTags"; } /* - * Returns com.wordnik.client.model.PetList */ + * Returns Array[Pet] */ public function findPetsByStatus (status: String= "available"): String { // create path and map variables - var path: String = "/pet.{format}/findByStatus".replace(/{format}/g,"xml"); + var path: String = "/pet/findByStatus".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -125,15 +226,15 @@ public static const event_findPetsByTags: String = "findPetsByTags"; token.requestId = requestId; token.completionEventType = "findPetsByStatus"; - token.returnType = com.wordnik.client.model.PetList; + token.returnType = Array[Pet]; return requestId; } /* - * Returns com.wordnik.client.model.PetList */ + * Returns Array[Pet] */ public function findPetsByTags (tags: String): String { // create path and map variables - var path: String = "/pet.{format}/findByTags".replace(/{format}/g,"xml"); + var path: String = "/pet/findByTags".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -152,7 +253,7 @@ public static const event_findPetsByTags: String = "findPetsByTags"; token.requestId = requestId; token.completionEventType = "findPetsByTags"; - token.returnType = com.wordnik.client.model.PetList; + token.returnType = Array[Pet]; return requestId; } diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as index 4ce2a47f0cc..4712d9ae997 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/StoreApi.as @@ -29,7 +29,7 @@ public static const event_placeOrder: String = "placeOrder"; * Returns Order */ public function getOrderById (orderId: String): String { // create path and map variables - var path: String = "/store.{format}/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); + var path: String = "/store/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); // query params var queryParams: Dictionary = new Dictionary(); @@ -54,7 +54,7 @@ public static const event_placeOrder: String = "placeOrder"; * Returns void */ public function deleteOrder (orderId: String): String { // create path and map variables - var path: String = "/store.{format}/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); + var path: String = "/store/order/{orderId}".replace(/{format}/g,"xml").replace("{" + "orderId" + "}", getApiInvoker().escapeString(orderId)); // query params var queryParams: Dictionary = new Dictionary(); @@ -79,7 +79,7 @@ public static const event_placeOrder: String = "placeOrder"; * Returns void */ public function placeOrder (body: Order): String { // create path and map variables - var path: String = "/store.{format}/order".replace(/{format}/g,"xml"); + var path: String = "/store/order".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as index 1464eca03c8..d502f6341bf 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/api/UserApi.as @@ -22,8 +22,8 @@ public class UserApi extends SwaggerApi { super(apiCredentials, eventDispatcher); } -public static const event_createUsersWithArrayInput: String = "createUsersWithArrayInput"; public static const event_createUser: String = "createUser"; +public static const event_createUsersWithArrayInput: String = "createUsersWithArrayInput"; public static const event_createUsersWithListInput: String = "createUsersWithListInput"; public static const event_updateUser: String = "updateUser"; public static const event_deleteUser: String = "deleteUser"; @@ -32,34 +32,9 @@ public static const event_loginUser: String = "loginUser"; public static const event_logoutUser: String = "logoutUser"; /* * Returns void */ - public function createUsersWithArrayInput (body: Array): String { - // create path and map variables - var path: String = "/user.{format}/createWithArray".replace(/{format}/g,"xml"); - - // query params - var queryParams: Dictionary = new Dictionary(); - var headerParams: Dictionary = new Dictionary(); - - // verify required params are set - if(body == null ) { - throw new ApiError(400, "missing required params"); - } - var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); - - var requestId: String = getUniqueId(); - - token.requestId = requestId; - token.completionEventType = "createUsersWithArrayInput"; - - token.returnType = null ; - return requestId; - - } - /* - * Returns void */ public function createUser (body: User): String { // create path and map variables - var path: String = "/user.{format}".replace(/{format}/g,"xml"); + var path: String = "/user".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -79,12 +54,37 @@ public static const event_logoutUser: String = "logoutUser"; token.returnType = null ; return requestId; + } + /* + * Returns void */ + public function createUsersWithArrayInput (body: Array): String { + // create path and map variables + var path: String = "/user/createWithArray".replace(/{format}/g,"xml"); + + // query params + var queryParams: Dictionary = new Dictionary(); + var headerParams: Dictionary = new Dictionary(); + + // verify required params are set + if(body == null ) { + throw new ApiError(400, "missing required params"); + } + var token:AsyncToken = getApiInvoker().invokeAPI(path, "POST", queryParams, body, headerParams); + + var requestId: String = getUniqueId(); + + token.requestId = requestId; + token.completionEventType = "createUsersWithArrayInput"; + + token.returnType = null ; + return requestId; + } /* * Returns void */ public function createUsersWithListInput (body: Array): String { // create path and map variables - var path: String = "/user.{format}/createWithList".replace(/{format}/g,"xml"); + var path: String = "/user/createWithList".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -109,7 +109,7 @@ public static const event_logoutUser: String = "logoutUser"; * Returns void */ public function updateUser (username: String, body: User): String { // create path and map variables - var path: String = "/user.{format}/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); + var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); // query params var queryParams: Dictionary = new Dictionary(); @@ -134,7 +134,7 @@ public static const event_logoutUser: String = "logoutUser"; * Returns void */ public function deleteUser (username: String): String { // create path and map variables - var path: String = "/user.{format}/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); + var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); // query params var queryParams: Dictionary = new Dictionary(); @@ -159,7 +159,7 @@ public static const event_logoutUser: String = "logoutUser"; * Returns User */ public function getUserByName (username: String): String { // create path and map variables - var path: String = "/user.{format}/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); + var path: String = "/user/{username}".replace(/{format}/g,"xml").replace("{" + "username" + "}", getApiInvoker().escapeString(username)); // query params var queryParams: Dictionary = new Dictionary(); @@ -184,7 +184,7 @@ public static const event_logoutUser: String = "logoutUser"; * Returns string */ public function loginUser (username: String, password: String): String { // create path and map variables - var path: String = "/user.{format}/login".replace(/{format}/g,"xml"); + var path: String = "/user/login".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); @@ -213,7 +213,7 @@ public static const event_logoutUser: String = "logoutUser"; * Returns void */ public function logoutUser (): String { // create path and map variables - var path: String = "/user.{format}/logout".replace(/{format}/g,"xml"); + var path: String = "/user/logout".replace(/{format}/g,"xml"); // query params var queryParams: Dictionary = new Dictionary(); diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as index 1b17bd5b332..945997f2fb4 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Category.as @@ -2,9 +2,11 @@ package com.wordnik.client.model { [XmlRootNode(name="Category")] public class Category { + /* Category unique identifier */ [XmlElement(name="id")] public var id: Number = 0.0; + /* Name of the category */ [XmlElement(name="name")] public var name: String = null; diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as index 6124e260f8f..d1842252d2f 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Order.as @@ -2,19 +2,23 @@ package com.wordnik.client.model { [XmlRootNode(name="Order")] public class Order { + /* Unique identifier for the order */ [XmlElement(name="id")] public var id: Number = 0.0; + /* ID of pet being ordered */ [XmlElement(name="petId")] public var petId: Number = 0.0; - /* Order Status */ - [XmlElement(name="status")] - public var status: String = null; - + /* Number of pets ordered */ [XmlElement(name="quantity")] public var quantity: Number = 0.0; + /* Status of the order */ + [XmlElement(name="status")] + public var status: String = null; + + /* Date shipped, only if it has been */ [XmlElement(name="shipDate")] public var shipDate: Date = null; @@ -22,8 +26,8 @@ package com.wordnik.client.model { var str: String = "Order: "; str += " (id: " + id + ")"; str += " (petId: " + petId + ")"; - str += " (status: " + status + ")"; str += " (quantity: " + quantity + ")"; + str += " (status: " + status + ")"; str += " (shipDate: " + shipDate + ")"; return str; } diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as index a804d8f63d7..cfab2c7f90f 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Pet.as @@ -4,39 +4,44 @@ import com.wordnik.client.model.Category; import com.wordnik.client.model.Tag; [XmlRootNode(name="Pet")] public class Pet { - // This declaration below of _tags_obj_class is to force flash compiler to include this class - private var _tags_obj_class: com.wordnik.client.model.Tag = null; - [XmlElementWrapper(name="tags")] - [XmlElements(name="tag", type="com.wordnik.client.model.Tag")] - public var tags: Array = new Array(); - + /* Unique identifier for the Pet */ [XmlElement(name="id")] public var id: Number = 0.0; + /* Category the pet is in */ [XmlElement(name="category")] public var category: Category = null; - /* pet status in the store */ - [XmlElement(name="status")] - public var status: String = null; - + /* Friendly name of the pet */ [XmlElement(name="name")] public var name: String = null; + /* Image URLs */ // This declaration below of _photoUrls_obj_class is to force flash compiler to include this class private var _photoUrls_obj_class: com.wordnik.client.model.String = null; [XmlElementWrapper(name="photoUrls")] [XmlElements(name="photoUrl", type="com.wordnik.client.model.String")] public var photoUrls: Array = new Array(); + /* Tags assigned to this pet */ + // This declaration below of _tags_obj_class is to force flash compiler to include this class + private var _tags_obj_class: com.wordnik.client.model.Tag = null; + [XmlElementWrapper(name="tags")] + [XmlElements(name="tag", type="com.wordnik.client.model.Tag")] + public var tags: Array = new Array(); + + /* pet status in the store */ + [XmlElement(name="status")] + public var status: String = null; + public function toString(): String { var str: String = "Pet: "; - str += " (tags: " + tags + ")"; str += " (id: " + id + ")"; str += " (category: " + category + ")"; - str += " (status: " + status + ")"; str += " (name: " + name + ")"; str += " (photoUrls: " + photoUrls + ")"; + str += " (tags: " + tags + ")"; + str += " (status: " + status + ")"; return str; } diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as index e229eb0ba64..93f77b50b2e 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/Tag.as @@ -2,9 +2,11 @@ package com.wordnik.client.model { [XmlRootNode(name="Tag")] public class Tag { + /* Unique identifier for the tag */ [XmlElement(name="id")] public var id: Number = 0.0; + /* Friendly name for the tag */ [XmlElement(name="name")] public var name: String = null; diff --git a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as index 82a7b9d5bef..b5110b3cc5f 100644 --- a/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as +++ b/samples/client/petstore/flash/src/main/flex/com/wordnik/client/model/User.as @@ -2,41 +2,48 @@ package com.wordnik.client.model { [XmlRootNode(name="User")] public class User { + /* Unique identifier for the user */ [XmlElement(name="id")] public var id: Number = 0.0; - [XmlElement(name="lastName")] - public var lastName: String = null; - - [XmlElement(name="phone")] - public var phone: String = null; - + /* Unique username */ [XmlElement(name="username")] public var username: String = null; + /* First name of the user */ + [XmlElement(name="firstName")] + public var firstName: String = null; + + /* Last name of the user */ + [XmlElement(name="lastName")] + public var lastName: String = null; + + /* Email address of the user */ [XmlElement(name="email")] public var email: String = null; + /* Password name of the user */ + [XmlElement(name="password")] + public var password: String = null; + + /* Phone number of the user */ + [XmlElement(name="phone")] + public var phone: String = null; + /* User Status */ [XmlElement(name="userStatus")] public var userStatus: Number = 0.0; - [XmlElement(name="firstName")] - public var firstName: String = null; - - [XmlElement(name="password")] - public var password: String = null; - public function toString(): String { var str: String = "User: "; str += " (id: " + id + ")"; - str += " (lastName: " + lastName + ")"; - str += " (phone: " + phone + ")"; str += " (username: " + username + ")"; - str += " (email: " + email + ")"; - str += " (userStatus: " + userStatus + ")"; str += " (firstName: " + firstName + ")"; + str += " (lastName: " + lastName + ")"; + str += " (email: " + email + ")"; str += " (password: " + password + ")"; + str += " (phone: " + phone + ")"; + str += " (userStatus: " + userStatus + ")"; return str; } diff --git a/samples/client/petstore/php/PetApi.php b/samples/client/petstore/php/PetApi.php index de447aafaaa..94400f032b6 100644 --- a/samples/client/petstore/php/PetApi.php +++ b/samples/client/petstore/php/PetApi.php @@ -28,14 +28,14 @@ class PetApi { /** * getPetById * Find pet by ID - * petId, string: ID of pet that needs to be fetched (required) + * petId, int: ID of pet that needs to be fetched (required) * @return Pet */ public function getPetById($petId) { //parse inputs - $resourcePath = "/pet.{format}/{petId}"; + $resourcePath = "/pet/{petId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); @@ -43,7 +43,7 @@ class PetApi { if($petId != null) { $resourcePath = str_replace("{" . "petId" . "}", - $petId, $resourcePath); + $this->apiClient->toPathValue($petId), $resourcePath); } //make the API Call if (! isset($body)) { @@ -62,6 +62,134 @@ class PetApi { 'Pet'); return $responseObject; + } + /** + * deletePet + * Deletes a pet + * petId, string: Pet id to delete (required) + * @return + */ + + public function deletePet($petId) { + + //parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "DELETE"; + $queryParams = array(); + $headerParams = array(); + + if($petId != null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + //make the API Call + if (! isset($body)) { + $body = null; + } + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + /** + * partialUpdate + * partial updates to a pet + * petId, string: ID of pet that needs to be fetched (required) + * body, Pet: Pet object that needs to be added to the store (required) + * @return Array[Pet] + */ + + public function partialUpdate($petId, $body) { + + //parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "PATCH"; + $queryParams = array(); + $headerParams = array(); + + if($petId != null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + //make the API Call + if (! isset($body)) { + $body = null; + } + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + if(! $response){ + return null; + } + + $responseObject = $this->apiClient->deserialize($response, + 'Array[Pet]'); + return $responseObject; + + } + /** + * updatePetWithForm + * Updates a pet in the store with form data + * petId, string: ID of pet that needs to be updated (required) + * name, string: Updated name of the pet (optional) + * status, string: Updated status of the pet (optional) + * @return + */ + + public function updatePetWithForm($petId, $name=null, $status=null) { + + //parse inputs + $resourcePath = "/pet/{petId}"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $queryParams = array(); + $headerParams = array(); + + if($petId != null) { + $resourcePath = str_replace("{" . "petId" . "}", + $this->apiClient->toPathValue($petId), $resourcePath); + } + //make the API Call + if (! isset($body)) { + $body = null; + } + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + + } + /** + * uploadFile + * uploads an image + * additionalMetadata, string: Additional data to pass to server (optional) + * body, File: file to upload (optional) + * @return + */ + + public function uploadFile($additionalMetadata=null, $body=null) { + + //parse inputs + $resourcePath = "/pet/uploadImage"; + $resourcePath = str_replace("{format}", "json", $resourcePath); + $method = "POST"; + $queryParams = array(); + $headerParams = array(); + + //make the API Call + if (! isset($body)) { + $body = null; + } + $response = $this->apiClient->callAPI($resourcePath, $method, + $queryParams, $body, + $headerParams); + + } /** * addPet @@ -73,7 +201,7 @@ class PetApi { public function addPet($body) { //parse inputs - $resourcePath = "/pet.{format}"; + $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); @@ -99,7 +227,7 @@ class PetApi { public function updatePet($body) { //parse inputs - $resourcePath = "/pet.{format}"; + $resourcePath = "/pet"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "PUT"; $queryParams = array(); @@ -119,20 +247,20 @@ class PetApi { * findPetsByStatus * Finds Pets by status * status, string: Status values that need to be considered for filter (required) - * @return array[Pet] + * @return Array[Pet] */ public function findPetsByStatus($status) { //parse inputs - $resourcePath = "/pet.{format}/findByStatus"; + $resourcePath = "/pet/findByStatus"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); if($status != null) { - $queryParams['status'] = $this->apiClient->toPathValue($status); + $queryParams['status'] = $this->apiClient->toQueryValue($status); } //make the API Call if (! isset($body)) { @@ -148,7 +276,7 @@ class PetApi { } $responseObject = $this->apiClient->deserialize($response, - 'array[Pet]'); + 'Array[Pet]'); return $responseObject; } @@ -156,20 +284,20 @@ class PetApi { * findPetsByTags * Finds Pets by tags * tags, string: Tags to filter by (required) - * @return array[Pet] + * @return Array[Pet] */ public function findPetsByTags($tags) { //parse inputs - $resourcePath = "/pet.{format}/findByTags"; + $resourcePath = "/pet/findByTags"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); if($tags != null) { - $queryParams['tags'] = $this->apiClient->toPathValue($tags); + $queryParams['tags'] = $this->apiClient->toQueryValue($tags); } //make the API Call if (! isset($body)) { @@ -185,7 +313,7 @@ class PetApi { } $responseObject = $this->apiClient->deserialize($response, - 'array[Pet]'); + 'Array[Pet]'); return $responseObject; } diff --git a/samples/client/petstore/php/StoreApi.php b/samples/client/petstore/php/StoreApi.php index 50696eb5766..3ccabb3590c 100644 --- a/samples/client/petstore/php/StoreApi.php +++ b/samples/client/petstore/php/StoreApi.php @@ -35,7 +35,7 @@ class StoreApi { public function getOrderById($orderId) { //parse inputs - $resourcePath = "/store.{format}/order/{orderId}"; + $resourcePath = "/store/order/{orderId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); @@ -43,7 +43,7 @@ class StoreApi { if($orderId != null) { $resourcePath = str_replace("{" . "orderId" . "}", - $orderId, $resourcePath); + $this->apiClient->toPathValue($orderId), $resourcePath); } //make the API Call if (! isset($body)) { @@ -73,7 +73,7 @@ class StoreApi { public function deleteOrder($orderId) { //parse inputs - $resourcePath = "/store.{format}/order/{orderId}"; + $resourcePath = "/store/order/{orderId}"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "DELETE"; $queryParams = array(); @@ -81,7 +81,7 @@ class StoreApi { if($orderId != null) { $resourcePath = str_replace("{" . "orderId" . "}", - $orderId, $resourcePath); + $this->apiClient->toPathValue($orderId), $resourcePath); } //make the API Call if (! isset($body)) { @@ -103,7 +103,7 @@ class StoreApi { public function placeOrder($body) { //parse inputs - $resourcePath = "/store.{format}/order"; + $resourcePath = "/store/order"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); diff --git a/samples/client/petstore/php/Swagger.php b/samples/client/petstore/php/Swagger.php index 473d47f968f..ddf7d79de63 100644 --- a/samples/client/petstore/php/Swagger.php +++ b/samples/client/petstore/php/Swagger.php @@ -67,7 +67,7 @@ class APIClient { } if (is_object($postData) or is_array($postData)) { - $postData = json_encode($postData); + $postData = json_encode(self::sanitizeForSerialization($postData)); } $url = $this->apiServer . $resourcePath; @@ -118,18 +118,41 @@ class APIClient { $response_info['http_code']); } + return $data; } - + /** + * Build a JSON POST object + */ + public static function sanitizeForSerialization($postData) { + foreach ($postData as $key => $value) { + if (is_a($value, "DateTime")) { + $postData->{$key} = $value->format(DateTime::ISO8601); + } + } + return $postData; + } /** * Take value and turn it into a string suitable for inclusion in - * the path or the header + * the path, by url-encoding. + * @param string $value a string which will be part of the path + * @return string the serialized object + */ + public static function toPathValue($value) { + return rawurlencode($value); + } + + /** + * Take value and turn it into a string suitable for inclusion in + * the query, by imploding comma-separated if it's an object. + * If it's a string, pass through unchanged. It will be url-encoded + * later. * @param object $object an object to be serialized to a string * @return string the serialized object */ - public static function toPathValue($object) { + public static function toQueryValue($object) { if (is_array($object)) { return implode(',', $object); } else { @@ -137,9 +160,18 @@ class APIClient { } } + /** + * Just pass through the header value for now. Placeholder in case we + * find out we need to do something with header values. + * @param string $value a string which will be part of the header + * @return string the header string + */ + public static function toHeaderValue($value) { + return $value; + } /** - * Derialize a JSON string into an object + * Deserialize a JSON string into an object * * @param object $object object or primitive to be deserialized * @param string $class class name is passed as a string @@ -177,17 +209,14 @@ class APIClient { if (! property_exists($class, $true_property)) { if (substr($property, -1) == 's') { $true_property = substr($property, 0, -1); - if (! property_exists($class, $true_property)) { - trigger_error("class $class has no property $property" - . " or $true_property", E_USER_WARNING); - } - } else { - trigger_error("class $class has no property $property", - E_USER_WARNING); } } - $type = $classVars['swaggerTypes'][$true_property]; + if (array_key_exists($true_property, $classVars['swaggerTypes'])) { + $type = $classVars['swaggerTypes'][$true_property]; + } else { + $type = 'string'; + } if (in_array($type, array('string', 'int', 'float', 'bool'))) { settype($value, $type); $instance->{$true_property} = $value; @@ -209,3 +238,5 @@ class APIClient { ?> + + diff --git a/samples/client/petstore/php/UserApi.php b/samples/client/petstore/php/UserApi.php index 92dc42259c2..49a4b55fd46 100644 --- a/samples/client/petstore/php/UserApi.php +++ b/samples/client/petstore/php/UserApi.php @@ -26,16 +26,16 @@ class UserApi { } /** - * createUsersWithArrayInput - * Creates list of users with given input array - * body, array[User]: List of user object (required) + * createUser + * Create user + * body, User: Created user object (required) * @return */ - public function createUsersWithArrayInput($body) { + public function createUser($body) { //parse inputs - $resourcePath = "/user.{format}/createWithArray"; + $resourcePath = "/user"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); @@ -52,16 +52,16 @@ class UserApi { } /** - * createUser - * Create user - * body, User: Created user object (required) + * createUsersWithArrayInput + * Creates list of users with given input array + * body, array[User]: List of user object (required) * @return */ - public function createUser($body) { + public function createUsersWithArrayInput($body) { //parse inputs - $resourcePath = "/user.{format}"; + $resourcePath = "/user/createWithArray"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); @@ -80,14 +80,14 @@ class UserApi { /** * createUsersWithListInput * Creates list of users with given list input - * body, List[User]: List of user object (required) + * body, array[User]: List of user object (required) * @return */ public function createUsersWithListInput($body) { //parse inputs - $resourcePath = "/user.{format}/createWithList"; + $resourcePath = "/user/createWithList"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "POST"; $queryParams = array(); @@ -114,7 +114,7 @@ class UserApi { public function updateUser($username, $body) { //parse inputs - $resourcePath = "/user.{format}/{username}"; + $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "PUT"; $queryParams = array(); @@ -122,7 +122,7 @@ class UserApi { if($username != null) { $resourcePath = str_replace("{" . "username" . "}", - $username, $resourcePath); + $this->apiClient->toPathValue($username), $resourcePath); } //make the API Call if (! isset($body)) { @@ -144,7 +144,7 @@ class UserApi { public function deleteUser($username) { //parse inputs - $resourcePath = "/user.{format}/{username}"; + $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "DELETE"; $queryParams = array(); @@ -152,7 +152,7 @@ class UserApi { if($username != null) { $resourcePath = str_replace("{" . "username" . "}", - $username, $resourcePath); + $this->apiClient->toPathValue($username), $resourcePath); } //make the API Call if (! isset($body)) { @@ -174,7 +174,7 @@ class UserApi { public function getUserByName($username) { //parse inputs - $resourcePath = "/user.{format}/{username}"; + $resourcePath = "/user/{username}"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); @@ -182,7 +182,7 @@ class UserApi { if($username != null) { $resourcePath = str_replace("{" . "username" . "}", - $username, $resourcePath); + $this->apiClient->toPathValue($username), $resourcePath); } //make the API Call if (! isset($body)) { @@ -213,17 +213,17 @@ class UserApi { public function loginUser($username, $password) { //parse inputs - $resourcePath = "/user.{format}/login"; + $resourcePath = "/user/login"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); $headerParams = array(); if($username != null) { - $queryParams['username'] = $this->apiClient->toPathValue($username); + $queryParams['username'] = $this->apiClient->toQueryValue($username); } if($password != null) { - $queryParams['password'] = $this->apiClient->toPathValue($password); + $queryParams['password'] = $this->apiClient->toQueryValue($password); } //make the API Call if (! isset($body)) { @@ -252,7 +252,7 @@ class UserApi { public function logoutUser() { //parse inputs - $resourcePath = "/user.{format}/logout"; + $resourcePath = "/user/logout"; $resourcePath = str_replace("{format}", "json", $resourcePath); $method = "GET"; $queryParams = array(); diff --git a/samples/client/petstore/php/models/Category.php b/samples/client/petstore/php/models/Category.php index adb99943fa3..ca8e3b0a7a4 100644 --- a/samples/client/petstore/php/models/Category.php +++ b/samples/client/petstore/php/models/Category.php @@ -29,7 +29,13 @@ class Category { ); + /** + * Category unique identifier + */ public $id; // int + /** + * Name of the category + */ public $name; // string } diff --git a/samples/client/petstore/php/models/Order.php b/samples/client/petstore/php/models/Order.php index 71f45865f5f..645ce10e411 100644 --- a/samples/client/petstore/php/models/Order.php +++ b/samples/client/petstore/php/models/Order.php @@ -26,19 +26,31 @@ class Order { static $swaggerTypes = array( 'id' => 'int', 'petId' => 'int', - 'status' => 'string', 'quantity' => 'int', + 'status' => 'string', 'shipDate' => 'DateTime' ); + /** + * Unique identifier for the order + */ public $id; // int + /** + * ID of pet being ordered + */ public $petId; // int /** - * Order Status + * Number of pets ordered + */ + public $quantity; // int + /** + * Status of the order */ public $status; // string - public $quantity; // int + /** + * Date shipped, only if it has been + */ public $shipDate; // DateTime } diff --git a/samples/client/petstore/php/models/Pet.php b/samples/client/petstore/php/models/Pet.php index fa5906c7483..aa711a7edf6 100644 --- a/samples/client/petstore/php/models/Pet.php +++ b/samples/client/petstore/php/models/Pet.php @@ -24,23 +24,38 @@ class Pet { static $swaggerTypes = array( - 'tags' => 'array[Some(Tag)]', 'id' => 'int', 'category' => 'Category', - 'status' => 'string', 'name' => 'string', - 'photoUrls' => 'array[None]' + 'photoUrls' => 'array[string]', + 'tags' => 'array[Tag]', + 'status' => 'string' ); - public $tags; // array[Some(Tag)] + /** + * Unique identifier for the Pet + */ public $id; // int + /** + * Category the pet is in + */ public $category; // Category /** + * Friendly name of the pet + */ + public $name; // string + /** + * Image URLs + */ + public $photoUrls; // array[string] + /** + * Tags assigned to this pet + */ + public $tags; // array[Tag] + /** * pet status in the store */ public $status; // string - public $name; // string - public $photoUrls; // array[None] } diff --git a/samples/client/petstore/php/models/Tag.php b/samples/client/petstore/php/models/Tag.php index 8550685e45e..2d85e97b50b 100644 --- a/samples/client/petstore/php/models/Tag.php +++ b/samples/client/petstore/php/models/Tag.php @@ -29,7 +29,13 @@ class Tag { ); + /** + * Unique identifier for the tag + */ public $id; // int + /** + * Friendly name for the tag + */ public $name; // string } diff --git a/samples/client/petstore/php/models/User.php b/samples/client/petstore/php/models/User.php index a07e11d68af..69c239082ee 100644 --- a/samples/client/petstore/php/models/User.php +++ b/samples/client/petstore/php/models/User.php @@ -25,26 +25,47 @@ class User { static $swaggerTypes = array( 'id' => 'int', - 'lastName' => 'string', - 'phone' => 'string', 'username' => 'string', - 'email' => 'string', - 'userStatus' => 'int', 'firstName' => 'string', - 'password' => 'string' + 'lastName' => 'string', + 'email' => 'string', + 'password' => 'string', + 'phone' => 'string', + 'userStatus' => 'int' ); + /** + * Unique identifier for the user + */ public $id; // int - public $lastName; // string - public $phone; // string + /** + * Unique username + */ public $username; // string + /** + * First name of the user + */ + public $firstName; // string + /** + * Last name of the user + */ + public $lastName; // string + /** + * Email address of the user + */ public $email; // string /** + * Password name of the user + */ + public $password; // string + /** + * Phone number of the user + */ + public $phone; // string + /** * User Status */ public $userStatus; // int - public $firstName; // string - public $password; // string } diff --git a/samples/client/petstore/python/PetApi.py b/samples/client/petstore/python/PetApi.py index 1d999f69440..f544323f459 100644 --- a/samples/client/petstore/python/PetApi.py +++ b/samples/client/petstore/python/PetApi.py @@ -33,7 +33,7 @@ class PetApi(object): """Find pet by ID Args: - petId, str: ID of pet that needs to be fetched (required) + petId, long: ID of pet that needs to be fetched (required) Returns: Pet """ @@ -47,7 +47,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}/{petId}' + resourcePath = '/pet/{petId}' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -70,6 +70,155 @@ class PetApi(object): return responseObject + def deletePet(self, petId, **kwargs): + """Deletes a pet + + Args: + petId, str: Pet id to delete (required) + + Returns: + """ + + allParams = ['petId'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method deletePet" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'DELETE' + + queryParams = {} + headerParams = {} + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + + def partialUpdate(self, petId, body, **kwargs): + """partial updates to a pet + + Args: + petId, str: ID of pet that needs to be fetched (required) + body, Pet: Pet object that needs to be added to the store (required) + + Returns: Array[Pet] + """ + + allParams = ['petId', 'body'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method partialUpdate" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'PATCH' + + queryParams = {} + headerParams = {} + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'Array[Pet]') + return responseObject + + + def updatePetWithForm(self, petId, **kwargs): + """Updates a pet in the store with form data + + Args: + petId, str: ID of pet that needs to be updated (required) + name, str: Updated name of the pet (optional) + status, str: Updated status of the pet (optional) + + Returns: + """ + + allParams = ['petId', 'name', 'status'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method updatePetWithForm" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + + def uploadFile(self, **kwargs): + """uploads an image + + Args: + additionalMetadata, str: Additional data to pass to server (optional) + body, File: file to upload (optional) + + Returns: + """ + + allParams = ['additionalMetadata', 'body'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method uploadFile" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/uploadImage' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + def addPet(self, body, **kwargs): """Add a new pet to the store @@ -88,7 +237,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}' + resourcePath = '/pet' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' @@ -120,7 +269,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}' + resourcePath = '/pet' resourcePath = resourcePath.replace('{format}', 'json') method = 'PUT' @@ -140,7 +289,7 @@ class PetApi(object): Args: status, str: Status values that need to be considered for filter (required) - Returns: list[Pet] + Returns: Array[Pet] """ allParams = ['status'] @@ -152,7 +301,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}/findByStatus' + resourcePath = '/pet/findByStatus' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -169,7 +318,7 @@ class PetApi(object): if not response: return None - responseObject = self.apiClient.deserialize(response, 'list[Pet]') + responseObject = self.apiClient.deserialize(response, 'Array[Pet]') return responseObject @@ -179,7 +328,7 @@ class PetApi(object): Args: tags, str: Tags to filter by (required) - Returns: list[Pet] + Returns: Array[Pet] """ allParams = ['tags'] @@ -191,7 +340,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}/findByTags' + resourcePath = '/pet/findByTags' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -208,7 +357,7 @@ class PetApi(object): if not response: return None - responseObject = self.apiClient.deserialize(response, 'list[Pet]') + responseObject = self.apiClient.deserialize(response, 'Array[Pet]') return responseObject diff --git a/samples/client/petstore/python/StoreApi.py b/samples/client/petstore/python/StoreApi.py index 7529b731b06..68b8a9159e0 100644 --- a/samples/client/petstore/python/StoreApi.py +++ b/samples/client/petstore/python/StoreApi.py @@ -47,7 +47,7 @@ class StoreApi(object): params[key] = val del params['kwargs'] - resourcePath = '/store.{format}/order/{orderId}' + resourcePath = '/store/order/{orderId}' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -88,7 +88,7 @@ class StoreApi(object): params[key] = val del params['kwargs'] - resourcePath = '/store.{format}/order/{orderId}' + resourcePath = '/store/order/{orderId}' resourcePath = resourcePath.replace('{format}', 'json') method = 'DELETE' @@ -124,7 +124,7 @@ class StoreApi(object): params[key] = val del params['kwargs'] - resourcePath = '/store.{format}/order' + resourcePath = '/store/order' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' diff --git a/samples/client/petstore/python/UserApi.py b/samples/client/petstore/python/UserApi.py index 25065076ef4..b02b9718617 100644 --- a/samples/client/petstore/python/UserApi.py +++ b/samples/client/petstore/python/UserApi.py @@ -29,38 +29,6 @@ class UserApi(object): self.apiClient = apiClient - def createUsersWithArrayInput(self, body, **kwargs): - """Creates list of users with given input array - - Args: - body, list[User]: List of user object (required) - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithArrayInput" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user.{format}/createWithArray' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - def createUser(self, body, **kwargs): """Create user @@ -79,7 +47,39 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}' + resourcePath = '/user' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + + def createUsersWithArrayInput(self, body, **kwargs): + """Creates list of users with given input array + + Args: + body, list[User]: List of user object (required) + + Returns: + """ + + allParams = ['body'] + + params = locals() + for (key, val) in params['kwargs'].iteritems(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithArrayInput" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/createWithArray' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' @@ -97,7 +97,7 @@ class UserApi(object): """Creates list of users with given list input Args: - body, List[User]: List of user object (required) + body, list[User]: List of user object (required) Returns: """ @@ -111,7 +111,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/createWithList' + resourcePath = '/user/createWithList' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' @@ -144,7 +144,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/{username}' + resourcePath = '/user/{username}' resourcePath = resourcePath.replace('{format}', 'json') method = 'PUT' @@ -180,7 +180,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/{username}' + resourcePath = '/user/{username}' resourcePath = resourcePath.replace('{format}', 'json') method = 'DELETE' @@ -216,7 +216,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/{username}' + resourcePath = '/user/{username}' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -258,7 +258,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/login' + resourcePath = '/user/login' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -298,7 +298,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/logout' + resourcePath = '/user/logout' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' diff --git a/samples/client/petstore/python/models/Category.py b/samples/client/petstore/python/models/Category.py index 465f6034066..35b7fe08ad6 100644 --- a/samples/client/petstore/python/models/Category.py +++ b/samples/client/petstore/python/models/Category.py @@ -27,6 +27,8 @@ class Category: } + #Category unique identifier self.id = None # long + #Name of the category self.name = None # str diff --git a/samples/client/petstore/python/models/Order.py b/samples/client/petstore/python/models/Order.py index 32b64ea5762..fc361a9f36b 100644 --- a/samples/client/petstore/python/models/Order.py +++ b/samples/client/petstore/python/models/Order.py @@ -23,17 +23,21 @@ class Order: self.swaggerTypes = { 'id': 'long', 'petId': 'long', - 'status': 'str', 'quantity': 'int', + 'status': 'str', 'shipDate': 'datetime' } + #Unique identifier for the order self.id = None # long + #ID of pet being ordered self.petId = None # long - #Order Status - self.status = None # str + #Number of pets ordered self.quantity = None # int + #Status of the order + self.status = None # str + #Date shipped, only if it has been self.shipDate = None # datetime diff --git a/samples/client/petstore/python/models/Pet.py b/samples/client/petstore/python/models/Pet.py index 7eefc439515..e4559794263 100644 --- a/samples/client/petstore/python/models/Pet.py +++ b/samples/client/petstore/python/models/Pet.py @@ -21,21 +21,26 @@ class Pet: def __init__(self): self.swaggerTypes = { - 'tags': 'list[Tag]', 'id': 'long', 'category': 'Category', - 'status': 'str', 'name': 'str', - 'photoUrls': 'list[str]' + 'photoUrls': 'list[str]', + 'tags': 'list[Tag]', + 'status': 'str' } - self.tags = None # list[Tag] + #Unique identifier for the Pet self.id = None # long + #Category the pet is in self.category = None # Category + #Friendly name of the pet + self.name = None # str + #Image URLs + self.photoUrls = None # list[str] + #Tags assigned to this pet + self.tags = None # list[Tag] #pet status in the store self.status = None # str - self.name = None # str - self.photoUrls = None # list[str] diff --git a/samples/client/petstore/python/models/Tag.py b/samples/client/petstore/python/models/Tag.py index 341f71c60ae..452f5b50ea3 100644 --- a/samples/client/petstore/python/models/Tag.py +++ b/samples/client/petstore/python/models/Tag.py @@ -27,6 +27,8 @@ class Tag: } + #Unique identifier for the tag self.id = None # long + #Friendly name for the tag self.name = None # str diff --git a/samples/client/petstore/python/models/User.py b/samples/client/petstore/python/models/User.py index d68a5ccde9a..80f3a1e6f53 100644 --- a/samples/client/petstore/python/models/User.py +++ b/samples/client/petstore/python/models/User.py @@ -22,24 +22,31 @@ class User: def __init__(self): self.swaggerTypes = { 'id': 'long', - 'lastName': 'str', - 'phone': 'str', 'username': 'str', - 'email': 'str', - 'userStatus': 'int', 'firstName': 'str', - 'password': 'str' + 'lastName': 'str', + 'email': 'str', + 'password': 'str', + 'phone': 'str', + 'userStatus': 'int' } + #Unique identifier for the user self.id = None # long - self.lastName = None # str - self.phone = None # str + #Unique username self.username = None # str + #First name of the user + self.firstName = None # str + #Last name of the user + self.lastName = None # str + #Email address of the user self.email = None # str + #Password name of the user + self.password = None # str + #Phone number of the user + self.phone = None # str #User Status self.userStatus = None # int - self.firstName = None # str - self.password = None # str diff --git a/samples/client/petstore/python/swagger.py b/samples/client/petstore/python/swagger.py index ef3d5f9a44a..98ed6250e02 100644 --- a/samples/client/petstore/python/swagger.py +++ b/samples/client/petstore/python/swagger.py @@ -36,7 +36,7 @@ class ApiClient: for param, value in headerParams.iteritems(): headers[param] = value - headers['Content-type'] = 'application/json' + #headers['Content-type'] = 'application/json' headers['api_key'] = self.apiKey if self.cookie: @@ -44,15 +44,18 @@ class ApiClient: data = None - if method == 'GET': + if queryParams: + # Need to remove None values, these should not be sent + sentQueryParams = {} + for param, value in queryParams.items(): + if value != None: + sentQueryParams[param] = value + url = url + '?' + urllib.urlencode(sentQueryParams) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.urlencode(sentQueryParams) + if method in ['GET']: + + #Options to add statements later on and for compatibility + pass elif method in ['POST', 'PUT', 'DELETE']: @@ -81,21 +84,21 @@ class ApiClient: return data def toPathValue(self, obj): - """Serialize a list to a CSV string, if necessary. + """Convert a string or object to a path-friendly value Args: - obj -- data object to be serialized + obj -- object or string value Returns: - string -- json serialization of object + string -- quoted value """ if type(obj) == list: - return ','.join(obj) + return urllib.quote(','.join(obj)) else: - return obj + return urllib.quote(str(obj)) def sanitizeForSerialization(self, obj): """Dump an object into JSON for POSTing.""" - if not obj: + if type(obj) == type(None): return None elif type(obj) in [str, int, long, float, bool]: return obj @@ -139,12 +142,12 @@ class ApiClient: subClass = match.group(1) return [self.deserialize(subObj, subClass) for subObj in obj] - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str']): + if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): objClass = eval(objClass) else: # not a native type, must be model class objClass = eval(objClass + '.' + objClass) - if objClass in [str, int, long, float, bool]: + if objClass in [int, long, float, dict, list, str, bool]: return objClass(obj) elif objClass == datetime: # Server will always return a time stamp in UTC, but with @@ -164,7 +167,12 @@ class ApiClient: value = attrType(value) except UnicodeEncodeError: value = unicode(value) + except TypeError: + value = value setattr(instance, attr, value) + elif (attrType == 'datetime'): + setattr(instance, attr, datetime.datetime.strptime(value[:-5], + "%Y-%m-%dT%H:%M:%S.%f")) elif 'list[' in attrType: match = re.match('list\[(.*)\]', attrType) subClass = match.group(1) @@ -198,3 +206,4 @@ class MethodRequest(urllib2.Request): def get_method(self): return getattr(self, 'method', urllib2.Request.get_method(self)) + diff --git a/samples/client/petstore/ruby/lib/Pet_api.rb b/samples/client/petstore/ruby/lib/Pet_api.rb index 2cb00a1f7f6..51774c9abef 100644 --- a/samples/client/petstore/ruby/lib/Pet_api.rb +++ b/samples/client/petstore/ruby/lib/Pet_api.rb @@ -14,10 +14,11 @@ class Pet_api # verify existence of params raise "pet_id is required" if pet_id.nil? # set default values and merge with input - options = { :pet_id => pet_id}.merge(opts) + options = { + :pet_id => pet_id}.merge(opts) #resource path - path = "/pet.{format}/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) # pull querystring keys from options @@ -31,16 +32,155 @@ class Pet_api Pet.new(response) end +def self.delete_pet (pet_id,opts={}) + query_param_keys = [] + + # verify existence of params + raise "pet_id is required" if pet_id.nil? + # set default values and merge with input + options = { + :pet_id => pet_id}.merge(opts) + + #resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + +def self.partial_update (pet_id,body,opts={}) + query_param_keys = [] + + # verify existence of params + raise "pet_id is required" if pet_id.nil? + raise "body is required" if body.nil? + # set default values and merge with input + options = { + :pet_id => pet_id, + :body => body}.merge(opts) + + #resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + response = Swagger::Request.new(:PATCH, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body + response.map {|response|Pet.new(response)} + end + +def self.update_pet_with_form (pet_id,name,status,opts={}) + query_param_keys = [] + + # verify existence of params + raise "pet_id is required" if pet_id.nil? + # set default values and merge with input + options = { + :pet_id => pet_id, + :name => name, + :status => status}.merge(opts) + + #resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) + + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + +def self.upload_file (additional_metadata,body,opts={}) + query_param_keys = [] + + # set default values and merge with input + options = { + :additional_metadata => additional_metadata, + :body => body}.merge(opts) + + #resource path + path = "/pet/uploadImage".sub('{format}','json') + + # pull querystring keys from options + queryopts = options.select do |key,value| + query_param_keys.include? key + end + + headers = nil + post_body = nil + if body != nil + if body.is_a?(Array) + array = Array.new + body.each do |item| + if item.respond_to?("to_body".to_sym) + array.push item.to_body + else + array.push item + end + end + post_body = array + + else + if body.respond_to?("to_body".to_sym) + post_body = body.to_body + else + post_body = body + end + end + end + Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make + + end + def self.add_pet (body,opts={}) query_param_keys = [] # verify existence of params raise "body is required" if body.nil? # set default values and merge with input - options = { :body => body}.merge(opts) + options = { + :body => body}.merge(opts) #resource path - path = "/pet.{format}".sub('{format}','json') + path = "/pet".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -79,10 +219,11 @@ def self.update_pet (body,opts={}) # verify existence of params raise "body is required" if body.nil? # set default values and merge with input - options = { :body => body}.merge(opts) + options = { + :body => body}.merge(opts) #resource path - path = "/pet.{format}".sub('{format}','json') + path = "/pet".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -121,10 +262,11 @@ def self.find_pets_by_status (status= "available",opts={}) # verify existence of params raise "status is required" if status.nil? # set default values and merge with input - options = { :status => status}.merge(opts) + options = { + :status => status}.merge(opts) #resource path - path = "/pet.{format}/findByStatus".sub('{format}','json') + path = "/pet/findByStatus".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -143,10 +285,11 @@ def self.find_pets_by_tags (tags,opts={}) # verify existence of params raise "tags is required" if tags.nil? # set default values and merge with input - options = { :tags => tags}.merge(opts) + options = { + :tags => tags}.merge(opts) #resource path - path = "/pet.{format}/findByTags".sub('{format}','json') + path = "/pet/findByTags".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| diff --git a/samples/client/petstore/ruby/lib/Store_api.rb b/samples/client/petstore/ruby/lib/Store_api.rb index 2469dd12c95..d2bd259bd65 100644 --- a/samples/client/petstore/ruby/lib/Store_api.rb +++ b/samples/client/petstore/ruby/lib/Store_api.rb @@ -14,10 +14,11 @@ class Store_api # verify existence of params raise "order_id is required" if order_id.nil? # set default values and merge with input - options = { :order_id => order_id}.merge(opts) + options = { + :order_id => order_id}.merge(opts) #resource path - path = "/store.{format}/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) # pull querystring keys from options @@ -37,10 +38,11 @@ def self.delete_order (order_id,opts={}) # verify existence of params raise "order_id is required" if order_id.nil? # set default values and merge with input - options = { :order_id => order_id}.merge(opts) + options = { + :order_id => order_id}.merge(opts) #resource path - path = "/store.{format}/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) # pull querystring keys from options @@ -60,10 +62,11 @@ def self.place_order (body,opts={}) # verify existence of params raise "body is required" if body.nil? # set default values and merge with input - options = { :body => body}.merge(opts) + options = { + :body => body}.merge(opts) #resource path - path = "/store.{format}/order".sub('{format}','json') + path = "/store/order".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| diff --git a/samples/client/petstore/ruby/lib/User_api.rb b/samples/client/petstore/ruby/lib/User_api.rb index de73d035eeb..1ba377b22c4 100644 --- a/samples/client/petstore/ruby/lib/User_api.rb +++ b/samples/client/petstore/ruby/lib/User_api.rb @@ -8,16 +8,17 @@ class User_api URI.encode(string.to_s) end - def self.create_users_with_array_input (body,opts={}) + def self.create_user (body,opts={}) query_param_keys = [] # verify existence of params raise "body is required" if body.nil? # set default values and merge with input - options = { :body => body}.merge(opts) + options = { + :body => body}.merge(opts) #resource path - path = "/user.{format}/createWithArray".sub('{format}','json') + path = "/user".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -50,16 +51,17 @@ class User_api end -def self.create_user (body,opts={}) +def self.create_users_with_array_input (body,opts={}) query_param_keys = [] # verify existence of params raise "body is required" if body.nil? # set default values and merge with input - options = { :body => body}.merge(opts) + options = { + :body => body}.merge(opts) #resource path - path = "/user.{format}".sub('{format}','json') + path = "/user/createWithArray".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -98,10 +100,11 @@ def self.create_users_with_list_input (body,opts={}) # verify existence of params raise "body is required" if body.nil? # set default values and merge with input - options = { :body => body}.merge(opts) + options = { + :body => body}.merge(opts) #resource path - path = "/user.{format}/createWithList".sub('{format}','json') + path = "/user/createWithList".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -141,10 +144,12 @@ def self.update_user (username,body,opts={}) raise "username is required" if username.nil? raise "body is required" if body.nil? # set default values and merge with input - options = { :username => username, :body => body}.merge(opts) + options = { + :username => username, + :body => body}.merge(opts) #resource path - path = "/user.{format}/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) # pull querystring keys from options @@ -184,10 +189,11 @@ def self.delete_user (username,opts={}) # verify existence of params raise "username is required" if username.nil? # set default values and merge with input - options = { :username => username}.merge(opts) + options = { + :username => username}.merge(opts) #resource path - path = "/user.{format}/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) # pull querystring keys from options @@ -207,10 +213,11 @@ def self.get_user_by_name (username,opts={}) # verify existence of params raise "username is required" if username.nil? # set default values and merge with input - options = { :username => username}.merge(opts) + options = { + :username => username}.merge(opts) #resource path - path = "/user.{format}/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) # pull querystring keys from options @@ -231,10 +238,12 @@ def self.login_user (username,password,opts={}) raise "username is required" if username.nil? raise "password is required" if password.nil? # set default values and merge with input - options = { :username => username, :password => password}.merge(opts) + options = { + :username => username, + :password => password}.merge(opts) #resource path - path = "/user.{format}/login".sub('{format}','json') + path = "/user/login".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| @@ -251,10 +260,11 @@ def self.logout_user (opts={}) query_param_keys = [] # set default values and merge with input - options = { }.merge(opts) + options = { + }.merge(opts) #resource path - path = "/user.{format}/logout".sub('{format}','json') + path = "/user/logout".sub('{format}','json') # pull querystring keys from options queryopts = options.select do |key,value| diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb index 137abd1bdfe..c3d127b1569 100644 --- a/samples/client/petstore/ruby/lib/swagger/configuration.rb +++ b/samples/client/petstore/ruby/lib/swagger/configuration.rb @@ -3,7 +3,8 @@ module Swagger class Configuration require 'swagger/version' - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, + :user_agent, :logger, :inject_format # Defaults go in here.. def initialize @@ -12,8 +13,10 @@ module Swagger @host = 'api.wordnik.com' @base_path = '/v4' @user_agent = "ruby-#{Swagger::VERSION}" + @inject_format = true end end end + diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb index 93a8ddead2f..a5ab62fc484 100644 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger/request.rb @@ -81,8 +81,10 @@ module Swagger # Stick a .{format} placeholder into the path if there isn't # one already or an actual format like json or xml # e.g. /words/blah => /words.{format}/blah - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end end p = p.sub("{format}", self.format.to_s) @@ -184,3 +186,4 @@ module Swagger end end + diff --git a/samples/client/petstore/ruby/models/Category.rb b/samples/client/petstore/ruby/models/Category.rb index c77144950f5..54bd6a5245b 100644 --- a/samples/client/petstore/ruby/models/Category.rb +++ b/samples/client/petstore/ruby/models/Category.rb @@ -3,32 +3,29 @@ class Category # :internal => :external def self.attribute_map - { - :id => :id, :name => :name + { + :id => :id, + :name => :name - } + } end def initialize(attributes = {}) + return if attributes.empty? # Morph attribute keys into undescored rubyish style - if attributes.to_s != "" + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + if self.class.attribute_map[:"name"] + @name = attributes["name"] + end + - if Category.attribute_map["id".to_sym] != nil - name = "id".to_sym - value = attributes["id"] - send("#{name}=", value) if self.respond_to?(name) - end - if Category.attribute_map["name".to_sym] != nil - name = "name".to_sym - value = attributes["name"] - send("#{name}=", value) if self.respond_to?(name) - end - end end def to_body body = {} - Category.attribute_map.each_pair do |key,value| + self.class.attribute_map.each_pair do |key, value| body[value] = self.send(key) unless self.send(key).nil? end body diff --git a/samples/client/petstore/ruby/models/Order.rb b/samples/client/petstore/ruby/models/Order.rb index 4bc865e31db..81bc6d5a4dc 100644 --- a/samples/client/petstore/ruby/models/Order.rb +++ b/samples/client/petstore/ruby/models/Order.rb @@ -1,49 +1,43 @@ class Order - attr_accessor :id, :pet_id, :status, :quantity, :ship_date + attr_accessor :id, :pet_id, :quantity, :status, :ship_date # :internal => :external def self.attribute_map - { - :id => :id, :pet_id => :petId, :status => :status, :quantity => :quantity, :ship_date => :shipDate + { + :id => :id, + :pet_id => :petId, + :quantity => :quantity, + :status => :status, + :ship_date => :shipDate - } + } end def initialize(attributes = {}) + return if attributes.empty? # Morph attribute keys into undescored rubyish style - if attributes.to_s != "" + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + if self.class.attribute_map[:"pet_id"] + @pet_id = attributes["petId"] + end + if self.class.attribute_map[:"quantity"] + @quantity = attributes["quantity"] + end + if self.class.attribute_map[:"status"] + @status = attributes["status"] + end + if self.class.attribute_map[:"ship_date"] + @ship_date = attributes["shipDate"] + end + - if Order.attribute_map["id".to_sym] != nil - name = "id".to_sym - value = attributes["id"] - send("#{name}=", value) if self.respond_to?(name) - end - if Order.attribute_map["pet_id".to_sym] != nil - name = "pet_id".to_sym - value = attributes["petId"] - send("#{name}=", value) if self.respond_to?(name) - end - if Order.attribute_map["status".to_sym] != nil - name = "status".to_sym - value = attributes["status"] - send("#{name}=", value) if self.respond_to?(name) - end - if Order.attribute_map["quantity".to_sym] != nil - name = "quantity".to_sym - value = attributes["quantity"] - send("#{name}=", value) if self.respond_to?(name) - end - if Order.attribute_map["ship_date".to_sym] != nil - name = "ship_date".to_sym - value = attributes["shipDate"] - send("#{name}=", value) if self.respond_to?(name) - end - end end def to_body body = {} - Order.attribute_map.each_pair do |key,value| + self.class.attribute_map.each_pair do |key, value| body[value] = self.send(key) unless self.send(key).nil? end body diff --git a/samples/client/petstore/ruby/models/Pet.rb b/samples/client/petstore/ruby/models/Pet.rb index 26c32b785fe..f4b3eb2e4c8 100644 --- a/samples/client/petstore/ruby/models/Pet.rb +++ b/samples/client/petstore/ruby/models/Pet.rb @@ -1,66 +1,49 @@ class Pet - attr_accessor :tags, :id, :category, :status, :name, :photo_urls + attr_accessor :id, :category, :name, :photo_urls, :tags, :status # :internal => :external def self.attribute_map - { - :tags => :tags, :id => :id, :category => :category, :status => :status, :name => :name, :photo_urls => :photoUrls + { + :id => :id, + :category => :category, + :name => :name, + :photo_urls => :photoUrls, + :tags => :tags, + :status => :status - } + } end def initialize(attributes = {}) + return if attributes.empty? # Morph attribute keys into undescored rubyish style - if attributes.to_s != "" - - if Pet.attribute_map["tags".to_sym] != nil - name = "tags".to_sym - value = attributes["tags"] - if value.is_a?(Array) - array = Array.new - value.each do |arrayValue| - array.push Tag.new(arrayValue) - end - send("#{name}=", array) if self.respond_to?(name) - end - end - if Pet.attribute_map["id".to_sym] != nil - name = "id".to_sym - value = attributes["id"] - send("#{name}=", value) if self.respond_to?(name) - end - if Pet.attribute_map["category".to_sym] != nil - name = "category".to_sym - value = attributes["category"] - send("#{name}=", value) if self.respond_to?(name) - end - if Pet.attribute_map["status".to_sym] != nil - name = "status".to_sym - value = attributes["status"] - send("#{name}=", value) if self.respond_to?(name) - end - if Pet.attribute_map["name".to_sym] != nil - name = "name".to_sym - value = attributes["name"] - send("#{name}=", value) if self.respond_to?(name) - end - if Pet.attribute_map["photo_urls".to_sym] != nil - name = "photo_urls".to_sym - value = attributes["photoUrls"] - if value.is_a?(Array) - array = Array.new - value.each do |arrayValue| - array.push arrayValue - end - send("#{name}=", array) if self.respond_to?(name) - end - end + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + if self.class.attribute_map[:"category"] + @category = attributes["category"] + end + if self.class.attribute_map[:"name"] + @name = attributes["name"] + end + if self.class.attribute_map[:"photo_urls"] + if (value = attributes["photoUrls"]).is_a?(Array) + @photo_urls = valueend end + if self.class.attribute_map[:"tags"] + if (value = attributes["tags"]).is_a?(Array) + @tags = value.map{ |v| Tag.new(v) }end + end + if self.class.attribute_map[:"status"] + @status = attributes["status"] + end + + end def to_body body = {} - Pet.attribute_map.each_pair do |key,value| + self.class.attribute_map.each_pair do |key, value| body[value] = self.send(key) unless self.send(key).nil? end body diff --git a/samples/client/petstore/ruby/models/Tag.rb b/samples/client/petstore/ruby/models/Tag.rb index 5360a29f23d..abe4929a3d1 100644 --- a/samples/client/petstore/ruby/models/Tag.rb +++ b/samples/client/petstore/ruby/models/Tag.rb @@ -3,32 +3,29 @@ class Tag # :internal => :external def self.attribute_map - { - :id => :id, :name => :name + { + :id => :id, + :name => :name - } + } end def initialize(attributes = {}) + return if attributes.empty? # Morph attribute keys into undescored rubyish style - if attributes.to_s != "" + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + if self.class.attribute_map[:"name"] + @name = attributes["name"] + end + - if Tag.attribute_map["id".to_sym] != nil - name = "id".to_sym - value = attributes["id"] - send("#{name}=", value) if self.respond_to?(name) - end - if Tag.attribute_map["name".to_sym] != nil - name = "name".to_sym - value = attributes["name"] - send("#{name}=", value) if self.respond_to?(name) - end - end end def to_body body = {} - Tag.attribute_map.each_pair do |key,value| + self.class.attribute_map.each_pair do |key, value| body[value] = self.send(key) unless self.send(key).nil? end body diff --git a/samples/client/petstore/ruby/models/User.rb b/samples/client/petstore/ruby/models/User.rb index 9c0b83d6a21..ab01d21bfaf 100644 --- a/samples/client/petstore/ruby/models/User.rb +++ b/samples/client/petstore/ruby/models/User.rb @@ -1,64 +1,55 @@ class User - attr_accessor :id, :last_name, :phone, :username, :email, :user_status, :first_name, :password + attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status # :internal => :external def self.attribute_map - { - :id => :id, :last_name => :lastName, :phone => :phone, :username => :username, :email => :email, :user_status => :userStatus, :first_name => :firstName, :password => :password + { + :id => :id, + :username => :username, + :first_name => :firstName, + :last_name => :lastName, + :email => :email, + :password => :password, + :phone => :phone, + :user_status => :userStatus - } + } end def initialize(attributes = {}) + return if attributes.empty? # Morph attribute keys into undescored rubyish style - if attributes.to_s != "" + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + if self.class.attribute_map[:"username"] + @username = attributes["username"] + end + if self.class.attribute_map[:"first_name"] + @first_name = attributes["firstName"] + end + if self.class.attribute_map[:"last_name"] + @last_name = attributes["lastName"] + end + if self.class.attribute_map[:"email"] + @email = attributes["email"] + end + if self.class.attribute_map[:"password"] + @password = attributes["password"] + end + if self.class.attribute_map[:"phone"] + @phone = attributes["phone"] + end + if self.class.attribute_map[:"user_status"] + @user_status = attributes["userStatus"] + end + - if User.attribute_map["id".to_sym] != nil - name = "id".to_sym - value = attributes["id"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["last_name".to_sym] != nil - name = "last_name".to_sym - value = attributes["lastName"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["phone".to_sym] != nil - name = "phone".to_sym - value = attributes["phone"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["username".to_sym] != nil - name = "username".to_sym - value = attributes["username"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["email".to_sym] != nil - name = "email".to_sym - value = attributes["email"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["user_status".to_sym] != nil - name = "user_status".to_sym - value = attributes["userStatus"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["first_name".to_sym] != nil - name = "first_name".to_sym - value = attributes["firstName"] - send("#{name}=", value) if self.respond_to?(name) - end - if User.attribute_map["password".to_sym] != nil - name = "password".to_sym - value = attributes["password"] - send("#{name}=", value) if self.respond_to?(name) - end - end end def to_body body = {} - User.attribute_map.each_pair do |key,value| + self.class.attribute_map.each_pair do |key, value| body[value] = self.send(key) unless self.send(key).nil? end body diff --git a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala b/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala index 2c6cc8ab6f0..5a1ee6ad3a4 100644 --- a/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala +++ b/samples/client/petstore/scala/src/main/scala/com/wordnik/petstore/api/UserApi.scala @@ -43,7 +43,7 @@ class UserApi { case ex: ApiException => throw ex } } - def createUsersWithArrayInput (body: Array[User]) = { + def createUsersWithArrayInput (body: List[User]) = { // create path and map variables val path = "/user/createWithArray".replaceAll("\\{format\\}","json") val contentType = { @@ -71,7 +71,7 @@ class UserApi { case ex: ApiException => throw ex } } - def createUsersWithListInput (body: Array[User]) = { + def createUsersWithListInput (body: List[User]) = { // create path and map variables val path = "/user/createWithList".replaceAll("\\{format\\}","json") val contentType = { diff --git a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala index 60bdaa78b87..e6aed8482d1 100644 --- a/samples/client/petstore/scala/src/test/scala/UserApiTest.scala +++ b/samples/client/petstore/scala/src/test/scala/UserApiTest.scala @@ -79,7 +79,7 @@ class UserApiTest extends FlatSpec with ShouldMatchers { "XXXXXXXXXXX", "408-867-5309", 1) - }).toArray + }).toList api.createUsersWithArrayInput(userArray) for (i <- (1 to 2)) { @@ -104,7 +104,7 @@ class UserApiTest extends FlatSpec with ShouldMatchers { "XXXXXXXXXXX", "408-867-5309", 1) - }).toArray + }).toList api.createUsersWithListInput(userList) for (i <- (1 to 3)) { From 189569518d8f13816020f5ceab4fc8c09a5ca91b Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:44:44 -0700 Subject: [PATCH 08/20] updated to use afnetworking, cocoapods --- src/main/resources/objc/NIKApiInvoker.h | 40 -- src/main/resources/objc/NIKApiInvoker.m | 336 -------------- src/main/resources/objc/NIKSwaggerObject.h | 6 - src/main/resources/objc/NIKSwaggerObject.m | 10 - src/main/resources/objc/Podfile.mustache | 3 + src/main/resources/objc/SWGApiClient.h | 64 +++ src/main/resources/objc/SWGApiClient.m | 419 ++++++++++++++++++ .../resources/objc/{NIKDate.h => SWGDate.h} | 4 +- .../resources/objc/{NIKDate.m => SWGDate.m} | 4 +- .../resources/objc/{NIKFile.h => SWGFile.h} | 8 +- .../resources/objc/{NIKFile.m => SWGFile.m} | 4 +- src/main/resources/objc/SWGObject.h | 6 + src/main/resources/objc/SWGObject.m | 17 + src/main/resources/objc/api-body.mustache | 324 ++++++-------- src/main/resources/objc/api-header.mustache | 17 +- src/main/resources/objc/model-body.mustache | 27 +- src/main/resources/objc/model-header.mustache | 6 +- 17 files changed, 673 insertions(+), 622 deletions(-) delete mode 100644 src/main/resources/objc/NIKApiInvoker.h delete mode 100644 src/main/resources/objc/NIKApiInvoker.m delete mode 100644 src/main/resources/objc/NIKSwaggerObject.h delete mode 100644 src/main/resources/objc/NIKSwaggerObject.m create mode 100644 src/main/resources/objc/Podfile.mustache create mode 100644 src/main/resources/objc/SWGApiClient.h create mode 100644 src/main/resources/objc/SWGApiClient.m rename src/main/resources/objc/{NIKDate.h => SWGDate.h} (72%) rename src/main/resources/objc/{NIKDate.m => SWGDate.m} (95%) rename src/main/resources/objc/{NIKFile.h => SWGFile.h} (75%) rename src/main/resources/objc/{NIKFile.m => SWGFile.m} (90%) create mode 100644 src/main/resources/objc/SWGObject.h create mode 100644 src/main/resources/objc/SWGObject.m diff --git a/src/main/resources/objc/NIKApiInvoker.h b/src/main/resources/objc/NIKApiInvoker.h deleted file mode 100644 index 2d6977eadcc..00000000000 --- a/src/main/resources/objc/NIKApiInvoker.h +++ /dev/null @@ -1,40 +0,0 @@ -#import - -@interface NIKApiInvoker : NSObject { - -@private - NSOperationQueue *_queue; - NSMutableDictionary * _defaultHeaders; -} -@property(nonatomic, readonly) NSOperationQueue* queue; -@property(nonatomic, readonly) NSMutableDictionary * defaultHeaders; -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; - -+ (NIKApiInvoker*)sharedInstance; - -- (void)updateLoadCountWithDelta:(NSInteger)countDelta; -- (void)startLoad; -- (void)stopLoad; - - --(void) addHeader:(NSString*)value forKey:(NSString*)key; - --(NSString*) escapeString:(NSString*) string; - --(void) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id)body - headerParams: (NSDictionary*) headerParams - contentType: contentType - completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock; - --(void) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id)body - headerParams: (NSDictionary*) headerParams - contentType: contentType - completionBlock: (void (^)(NSString*, NSError *))completionBlock; - -@end diff --git a/src/main/resources/objc/NIKApiInvoker.m b/src/main/resources/objc/NIKApiInvoker.m deleted file mode 100644 index 819930ef66f..00000000000 --- a/src/main/resources/objc/NIKApiInvoker.m +++ /dev/null @@ -1,336 +0,0 @@ -#import "NIKApiInvoker.h" -#import "NIKFile.h" - -@implementation NIKApiInvoker - -@synthesize queue = _queue; -@synthesize defaultHeaders = _defaultHeaders; - - -static NSInteger __LoadingObjectsCount = 0; - -+ (NIKApiInvoker*)sharedInstance { - static NIKApiInvoker *_sharedInstance = nil; - if (!_sharedInstance) { - _sharedInstance = [[NIKApiInvoker alloc] init]; - } - return _sharedInstance; -} - -- (void)updateLoadCountWithDelta:(NSInteger)countDelta { - @synchronized(self) { - __LoadingObjectsCount += countDelta; - __LoadingObjectsCount = (__LoadingObjectsCount < 0) ? 0 : __LoadingObjectsCount ; - -#if TARGET_OS_IPHONE - [UIApplication sharedApplication].networkActivityIndicatorVisible = __LoadingObjectsCount > 0; -#endif - } -} - -- (void)startLoad { - [self updateLoadCountWithDelta:1]; -} - -- (void)stopLoad { - [self updateLoadCountWithDelta:-1]; -} - - -- (id) init { - self = [super init]; - _queue = [[NSOperationQueue alloc] init]; - _defaultHeaders = [[NSMutableDictionary alloc] init]; - _cachePolicy = NSURLRequestUseProtocolCachePolicy; - return self; -} - --(void) addHeader:(NSString*) value - forKey:(NSString*)key { - [_defaultHeaders setValue:value forKey:key]; -} - --(NSString*) escapeString:(NSString *)unescaped { - return (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); -} - --(void) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - contentType: (NSString*) contentType - completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock -{ - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - NSString * separator = nil; - int counter = 0; - if(queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; - else separator = @"&"; - NSString * value; - if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ - value = [self escapeString:[queryParams valueForKey:key]]; - } - else { - value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; - } - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [self escapeString:key], value]]; - counter += 1; - } - } - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"request url: %@", requestUrl); - } - - NSURL* URL = [NSURL URLWithString:requestUrl]; - - NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init]; - [request setURL:URL]; - [request setCachePolicy:self.cachePolicy]; - [request setTimeoutInterval:30]; - - for(NSString * key in [_defaultHeaders keyEnumerator]){ - [request setValue:[_defaultHeaders valueForKey:key] forHTTPHeaderField:key]; - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [request setHTTPMethod:method]; - if(body != nil) { - NSError * error = [NSError new]; - NSData * data = nil; - if([body isKindOfClass:[NSDictionary class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else if ([body isKindOfClass:[NIKFile class]]){ - NIKFile * file = (NIKFile*) body; - - NSString *boundary = @"Fo0+BAr"; - contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; - - // add the body - NSMutableData *postBody = [NSMutableData data]; - [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[@"Content-Disposition: form-data; name= \"some_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", file] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", file.mimeType] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData: file.data]; - [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - } - else if ([body isKindOfClass:[NSArray class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else { - data = [body dataUsingEncoding:NSUTF8StringEncoding]; - } - NSString *postLength = [NSString stringWithFormat:@"%d", [data length]]; - [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; - [request setHTTPBody:data]; - - [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; - } - - // Handle caching on GET requests - if ((_cachePolicy == NSURLRequestReturnCacheDataElseLoad || _cachePolicy == NSURLRequestReturnCacheDataDontLoad) && [method isEqualToString:@"GET"]) { - NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; - NSData *data = [cacheResponse data]; - if (data) { - NSError *error = nil; - NSDictionary* results = [NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]; - completionBlock(results, nil); - } - } - - if (_cachePolicy == NSURLRequestReturnCacheDataDontLoad) - return; - - [self startLoad]; - NSDate *date = [NSDate date]; - [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler: - ^(NSURLResponse *response, NSData *data, NSError *error) { - long statusCode = [(NSHTTPURLResponse*)response statusCode]; - - if (error) { - completionBlock(nil, error); - return; - } - else if (!NSLocationInRange(statusCode, NSMakeRange(200, 99))){ - error = [NSError errorWithDomain:@"swagger" - code:statusCode - userInfo:[NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]]; - completionBlock(nil, error); - return; - } - else { - NSDictionary* results = [NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]; - completionBlock(results, nil); - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"fetched results (%f seconds): %@", [[NSDate date] timeIntervalSinceDate:date], results); - } - } - - [self stopLoad]; - }]; -} - --(void) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - contentType: (NSString*) contentType - completionBlock: (void (^)(NSString*, NSError *))completionBlock -{ - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - NSString * separator = nil; - int counter = 0; - if(queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; - else separator = @"&"; - NSString * value; - if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ - value = [self escapeString:[queryParams valueForKey:key]]; - } - else { - value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; - } - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [self escapeString:key], value]]; - counter += 1; - } - } - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"request url: %@", requestUrl); - } - - NSURL* URL = [NSURL URLWithString:requestUrl]; - - NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init]; - [request setURL:URL]; - [request setCachePolicy:self.cachePolicy]; - [request setTimeoutInterval:30]; - - for(NSString * key in [_defaultHeaders keyEnumerator]){ - [request setValue:[_defaultHeaders valueForKey:key] forHTTPHeaderField:key]; - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [request setHTTPMethod:method]; - if(body != nil) { - NSError * error = [NSError new]; - NSData * data = nil; - if([body isKindOfClass:[NSDictionary class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else if ([body isKindOfClass:[NIKFile class]]){ - NIKFile * file = (NIKFile*) body; - - NSString *boundary = @"Fo0+BAr"; - contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]; - - // add the body - NSMutableData *postBody = [NSMutableData data]; - [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[@"Content-Disposition: form-data; name= \"some_name\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"image_file\"; filename=\"%@\"\r\n", file] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData:[[NSString stringWithFormat:@"Content-Type: %@\r\n\r\n", file.mimeType] dataUsingEncoding:NSUTF8StringEncoding]]; - [postBody appendData: file.data]; - [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]]; - } - else if ([body isKindOfClass:[NSArray class]]){ - data = [NSJSONSerialization dataWithJSONObject:body - options:kNilOptions error:&error]; - } - else { - data = [body dataUsingEncoding:NSUTF8StringEncoding]; - } - NSString *postLength = [NSString stringWithFormat:@"%d", [data length]]; - [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; - [request setHTTPBody:data]; - - [request setValue:contentType forHTTPHeaderField:@"Content-Type"]; - } - - - // Handle caching on GET requests - if ((_cachePolicy == NSURLRequestReturnCacheDataElseLoad || _cachePolicy == NSURLRequestReturnCacheDataDontLoad) && [method isEqualToString:@"GET"]) { - NSCachedURLResponse *cacheResponse = [[NSURLCache sharedURLCache] cachedResponseForRequest:request]; - NSData *data = [cacheResponse data]; - if (data) { - NSString* results = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - - if(results && [results length] >= 2) { - if(([results characterAtIndex:0] == '\"') && ([results characterAtIndex:([results length] - 1) == '\"'])){ - results = [results substringWithRange:NSMakeRange(1, [results length] -2)]; - } - } - completionBlock(results, nil); - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - // NSLog(@"cached results: %@", results); - } - } - - } - - if (_cachePolicy == NSURLRequestReturnCacheDataDontLoad) - return; - - [self startLoad]; - NSDate *date = [NSDate date]; - [NSURLConnection sendAsynchronousRequest:request queue:_queue completionHandler: - ^(NSURLResponse *response, NSData *data, NSError *error) { - int statusCode = [(NSHTTPURLResponse*)response statusCode]; - if (error) { - completionBlock(nil, error); - return; - } - else if (!NSLocationInRange(statusCode, NSMakeRange(200, 99))){ - error = [NSError errorWithDomain:@"swagger" - code:statusCode - userInfo:[NSJSONSerialization JSONObjectWithData:data - options:kNilOptions - error:&error]]; - completionBlock(nil, error); - return; - } - else { - NSString* results = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - - if(results && [results length] >= 2) { - if(([results characterAtIndex:0] == '\"') && ([results characterAtIndex:([results length] - 1) == '\"'])){ - results = [results substringWithRange:NSMakeRange(1, [results length] -2)]; - } - - } - completionBlock(results, nil); - if ([[NSUserDefaults standardUserDefaults] boolForKey:@"RVBLogging"]) { - NSLog(@"fetched results (%f seconds): %@", [[NSDate date] timeIntervalSinceDate:date], results); - } - } - [self stopLoad]; - }]; -} -@end \ No newline at end of file diff --git a/src/main/resources/objc/NIKSwaggerObject.h b/src/main/resources/objc/NIKSwaggerObject.h deleted file mode 100644 index 18f95663de1..00000000000 --- a/src/main/resources/objc/NIKSwaggerObject.h +++ /dev/null @@ -1,6 +0,0 @@ -#import - -@interface NIKSwaggerObject : NSObject -- (id) initWithValues: (NSDictionary*)dict; -- (NSDictionary*) asDictionary; -@end diff --git a/src/main/resources/objc/NIKSwaggerObject.m b/src/main/resources/objc/NIKSwaggerObject.m deleted file mode 100644 index 2467ce13ca8..00000000000 --- a/src/main/resources/objc/NIKSwaggerObject.m +++ /dev/null @@ -1,10 +0,0 @@ -#import "NIKSwaggerObject.h" - -@implementation NIKSwaggerObject -- (id) initWithValues: (NSDictionary*)dict { - return self; -} -- (NSDictionary*) asDictionary{ - return [NSDictionary init]; -} -@end diff --git a/src/main/resources/objc/Podfile.mustache b/src/main/resources/objc/Podfile.mustache new file mode 100644 index 00000000000..ee3f0856b6f --- /dev/null +++ b/src/main/resources/objc/Podfile.mustache @@ -0,0 +1,3 @@ +platform :ios, '6.0' +xcodeproj '{{projectName}}/{{projectName}}.xcodeproj' +pod 'AFNetworking', '~> 1.0' diff --git a/src/main/resources/objc/SWGApiClient.h b/src/main/resources/objc/SWGApiClient.h new file mode 100644 index 00000000000..aab60cd0595 --- /dev/null +++ b/src/main/resources/objc/SWGApiClient.h @@ -0,0 +1,64 @@ +#import +#import "AFHTTPClient.h" + +@interface SWGApiClient : AFHTTPClient + +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, assign) BOOL logRequests; +@property(nonatomic, assign) BOOL logCacheHits; +@property(nonatomic, assign) BOOL logServerResponses; +@property(nonatomic, assign) BOOL logJSON; +@property(nonatomic, assign) BOOL logHTTP; +@property(nonatomic, readonly) NSOperationQueue* queue; + ++(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl; + ++(NSOperationQueue*) sharedQueue; + ++(void)setLoggingEnabled:(bool) state; + ++(void)clearCache; + ++(void)setCacheEnabled:(BOOL) enabled; + ++(unsigned long)requestQueueSize; + ++(void) setOfflineState:(BOOL) state; + ++(AFNetworkReachabilityStatus) getReachabilityStatus; + ++(NSNumber*) nextRequestId; + ++(NSNumber*) queueRequest; + ++(void) cancelRequest:(NSNumber*)requestId; + ++(NSString*) escape:(id)unescaped; + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; + ++(void) configureCacheReachibilityForHost:(NSString*)host; + +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey; + +-(NSNumber*) dictionary:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock; + +-(NSNumber*) stringWithCompletionBlock:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSString*, NSError *))completionBlock; +@end + diff --git a/src/main/resources/objc/SWGApiClient.m b/src/main/resources/objc/SWGApiClient.m new file mode 100644 index 00000000000..669fd4d570b --- /dev/null +++ b/src/main/resources/objc/SWGApiClient.m @@ -0,0 +1,419 @@ +#import "SWGApiClient.h" +#import "SWGFile.h" + +#import "AFJSONRequestOperation.h" + +@implementation SWGApiClient + +static long requestId = 0; +static bool offlineState = true; +static NSMutableSet * queuedRequests = nil; +static bool cacheEnabled = false; +static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; +static NSOperationQueue* sharedQueue; +static void (^reachabilityChangeBlock)(int); +static bool loggingEnabled = false; + ++(void)setLoggingEnabled:(bool) state { + loggingEnabled = state; +} + ++(void)clearCache { + [[NSURLCache sharedURLCache] removeAllCachedResponses]; +} + ++(void)setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + ++(void)configureCacheWithMemoryAndDiskCapacity:(unsigned long) memorySize + diskSize:(unsigned long) diskSize { + NSAssert(memorySize > 0, @"invalid in-memory cache size"); + NSAssert(diskSize >= 0, @"invalid disk cache size"); + + NSURLCache *cache = + [[NSURLCache alloc] + initWithMemoryCapacity:memorySize + diskCapacity:diskSize + diskPath:@"swagger_url_cache"]; + + [NSURLCache setSharedURLCache:cache]; +} + ++(NSOperationQueue*) sharedQueue { + return sharedQueue; +} + ++(SWGApiClient *)sharedClientFromPool:(NSString *)baseUrl { + static NSMutableDictionary *_pool = nil; + if (queuedRequests == nil) { + queuedRequests = [[NSMutableSet alloc]init]; + } + if(_pool == nil) { + // setup static vars + // create queue + sharedQueue = [[NSOperationQueue alloc] init]; + + // create pool + _pool = [[NSMutableDictionary alloc] init]; + + // initialize URL cache + [SWGApiClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; + + // configure reachability + [SWGApiClient configureCacheReachibilityForHost:baseUrl]; + } + + @synchronized(self) { + SWGApiClient * client = [_pool objectForKey:baseUrl]; + if (client == nil) { + client = [[SWGApiClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; + [client registerHTTPOperationClass:[AFJSONRequestOperation class]]; + client.parameterEncoding = AFJSONParameterEncoding; + [_pool setValue:client forKey:baseUrl ]; + if(loggingEnabled) + NSLog(@"new client for path %@", baseUrl); + } + if(loggingEnabled) + NSLog(@"returning client for path %@", baseUrl); + return client; + } +} + +-(void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey { + [self setDefaultHeader:forKey value:value]; +} + ++(unsigned long)requestQueueSize { + return [queuedRequests count]; +} + ++(NSNumber*) nextRequestId { + long nextId = ++requestId; + if(loggingEnabled) + NSLog(@"got id %ld", nextId); + return [NSNumber numberWithLong:nextId]; +} + ++(NSNumber*) queueRequest { + NSNumber* requestId = [SWGApiClient nextRequestId]; + if(loggingEnabled) + NSLog(@"added %@ to request queue", requestId); + [queuedRequests addObject:requestId]; + return requestId; +} + ++(void) cancelRequest:(NSNumber*)requestId { + [queuedRequests removeObject:requestId]; +} + ++(NSString*) escape:(id)unescaped { + if([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } +} + +-(Boolean) executeRequestWithId:(NSNumber*) requestId { + NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { + if([obj intValue] == [requestId intValue]) + return TRUE; + else return FALSE; + }]; + + if(matchingItems.count == 1) { + if(loggingEnabled) + NSLog(@"removing request id %@", requestId); + [queuedRequests removeObject:requestId]; + return true; + } + else + return false; +} + +-(id)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + if (!self) + return nil; + return self; +} + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + ++(void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++(void) configureCacheReachibilityForHost:(NSString*)host { + [[SWGApiClient sharedClientFromPool:host ] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + switch (status) { + case AFNetworkReachabilityStatusUnknown: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + [SWGApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusNotReachable: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + [SWGApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusReachableViaWWAN: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + [SWGApiClient setOfflineState:false]; + break; + + case AFNetworkReachabilityStatusReachableViaWiFi: + if(loggingEnabled) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + [SWGApiClient setOfflineState:false]; + break; + default: + break; + } + // call the reachability block, if configured + if(reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; +} + +-(NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + NSString * separator = nil; + int counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + if(queryParams != nil){ + for(NSString * key in [queryParams keyEnumerator]){ + if(counter == 0) separator = @"?"; + else separator = @"&"; + NSString * value; + if([[queryParams valueForKey:key] isKindOfClass:[NSString class]]){ + value = [SWGApiClient escape:[queryParams valueForKey:key]]; + } + else { + value = [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]; + } + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [SWGApiClient escape:key], value]]; + counter += 1; + } + } + return requestUrl; +} + +- (NSString*)descriptionForRequest:(NSURLRequest*)request { + return [[request URL] absoluteString]; +} + +- (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 ); +} + + +-(NSNumber*) dictionary:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock { + + NSMutableURLRequest * request = nil; + + if ([body isKindOfClass:[SWGFile class]]){ + SWGFile * file = (SWGFile*) body; + + request = [self multipartFormRequestWithMethod:@"POST" + path:path + parameters:nil + constructingBodyWithBlock: ^(id formData) { + [formData appendPartWithFileData:[file data] + name:@"image" + fileName:[file name] + mimeType:[file mimeType]]; + }]; + } + else { + request = [self requestWithMethod:method + path:[self pathWithQueryParamsToString:path queryParams:queryParams] + parameters:body]; + } + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) + hasHeaderParams = true; + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(body != nil) { + if([body isKindOfClass:[NSDictionary class]]){ + [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + } + else if ([body isKindOfClass:[SWGFile class]]) {} + else { + NSAssert(false, @"unsupported post type!"); + } + } + if(headerParams != nil){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"]; + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + + if (self.logRequests) { + [self logRequest:request]; + } + + NSNumber* requestId = [SWGApiClient queueRequest]; + AFJSONRequestOperation *op = + [AFJSONRequestOperation + JSONRequestOperationWithRequest:request + success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:JSON forRequest:request error:nil]; + completionBlock(JSON, nil); + } + } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:nil forRequest:request error:error]; + completionBlock(nil, error); + } + } + ]; + + [self enqueueHTTPRequestOperation:op]; + return requestId; +} + +-(NSNumber*) stringWithCompletionBlock:(NSString*) path + method:(NSString*) method + queryParams:(NSDictionary*) queryParams + body:(id) body + headerParams:(NSDictionary*) headerParams + requestContentType:(NSString*) requestContentType + responseContentType:(NSString*) responseContentType + completionBlock:(void (^)(NSString*, NSError *))completionBlock { + AFHTTPClient *client = self; + client.parameterEncoding = AFJSONParameterEncoding; + + NSMutableURLRequest * request = nil; + + if ([body isKindOfClass:[SWGFile class]]){ + SWGFile * file = (SWGFile*) body; + + request = [self multipartFormRequestWithMethod:@"POST" + path:path + parameters:nil + constructingBodyWithBlock: ^(id formData) { + [formData appendPartWithFileData:[file data] + name:@"image" + fileName:[file name] + mimeType:[file mimeType]]; + }]; + } + else { + request = [self requestWithMethod:method + path:[self pathWithQueryParamsToString:path queryParams:queryParams] + parameters:body]; + } + + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) + hasHeaderParams = true; + if(offlineState) { + NSLog(@"%@ cache forced", path); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", path); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", path); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(body != nil) { + if([body isKindOfClass:[NSDictionary class]]){ + [request setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; + } + else if ([body isKindOfClass:[SWGFile class]]){} + else { + NSAssert(false, @"unsupported post type!"); + } + } + if(headerParams != nil){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [request setValue:[headerParams valueForKey:responseContentType] forHTTPHeaderField:@"Accept"]; + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSNumber* requestId = [SWGApiClient queueRequest]; + AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request]; + [op setCompletionBlockWithSuccess: + ^(AFHTTPRequestOperation *resp, + id responseObject) { + NSString *response = [resp responseString]; + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:responseObject forRequest:request error:nil]; + completionBlock(response, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + if(self.logServerResponses) + [self logResponse:nil forRequest:request error:error]; + completionBlock(nil, error); + } + }]; + + [self enqueueHTTPRequestOperation:op]; + return requestId; +} + +@end diff --git a/src/main/resources/objc/NIKDate.h b/src/main/resources/objc/SWGDate.h similarity index 72% rename from src/main/resources/objc/NIKDate.h rename to src/main/resources/objc/SWGDate.h index 3af47f7e4fc..2c6c7cfe01b 100644 --- a/src/main/resources/objc/NIKDate.h +++ b/src/main/resources/objc/SWGDate.h @@ -1,7 +1,7 @@ #import -#import "NIKSwaggerObject.h" +#import "SWGObject.h" -@interface NIKDate : NIKSwaggerObject { +@interface SWGDate : SWGObject { @private NSDate *_date; } diff --git a/src/main/resources/objc/NIKDate.m b/src/main/resources/objc/SWGDate.m similarity index 95% rename from src/main/resources/objc/NIKDate.m rename to src/main/resources/objc/SWGDate.m index c1f9a163deb..07a1405626b 100644 --- a/src/main/resources/objc/NIKDate.m +++ b/src/main/resources/objc/SWGDate.m @@ -1,6 +1,6 @@ -#import "NIKDate.h" +#import "SWGDate.h" -@implementation NIKDate +@implementation SWGDate @synthesize date = _date; diff --git a/src/main/resources/objc/NIKFile.h b/src/main/resources/objc/SWGFile.h similarity index 75% rename from src/main/resources/objc/NIKFile.h rename to src/main/resources/objc/SWGFile.h index 03409257677..fe6e81c289d 100644 --- a/src/main/resources/objc/NIKFile.h +++ b/src/main/resources/objc/SWGFile.h @@ -1,11 +1,7 @@ #import -@interface NIKFile : NSObject { -@private - NSString* name; - NSString* mimeType; - NSData* data; -} +@interface SWGFile : NSObject + @property(nonatomic, readonly) NSString* name; @property(nonatomic, readonly) NSString* mimeType; @property(nonatomic, readonly) NSData* data; diff --git a/src/main/resources/objc/NIKFile.m b/src/main/resources/objc/SWGFile.m similarity index 90% rename from src/main/resources/objc/NIKFile.m rename to src/main/resources/objc/SWGFile.m index b743161a389..42552767af4 100644 --- a/src/main/resources/objc/NIKFile.m +++ b/src/main/resources/objc/SWGFile.m @@ -1,6 +1,6 @@ -#import "NIKFile.h" +#import "SWGFile.h" -@implementation NIKFile +@implementation SWGFile @synthesize name = _name; @synthesize mimeType = _mimeType; diff --git a/src/main/resources/objc/SWGObject.h b/src/main/resources/objc/SWGObject.h new file mode 100644 index 00000000000..031bae69279 --- /dev/null +++ b/src/main/resources/objc/SWGObject.h @@ -0,0 +1,6 @@ +#import + +@interface SWGObject : NSObject +- (id) initWithValues:(NSDictionary*)dict; +- (NSDictionary*) asDictionary; +@end diff --git a/src/main/resources/objc/SWGObject.m b/src/main/resources/objc/SWGObject.m new file mode 100644 index 00000000000..9b37b3592b1 --- /dev/null +++ b/src/main/resources/objc/SWGObject.m @@ -0,0 +1,17 @@ +#import "SWGObject.h" + +@implementation SWGObject + +- (id) initWithValues:(NSDictionary*)dict { + return self; +} + +- (NSDictionary*) asDictionary{ + return [NSDictionary init]; +} + +- (NSString*)description { + return [NSString stringWithFormat:@"%@ %@", [super description], [self asDictionary]]; +} + +@end diff --git a/src/main/resources/objc/api-body.mustache b/src/main/resources/objc/api-body.mustache index 249cd5947f1..18571099c1e 100644 --- a/src/main/resources/objc/api-body.mustache +++ b/src/main/resources/objc/api-body.mustache @@ -1,6 +1,7 @@ {{#operations}} #import "{{classname}}.h" -#import "NIKFile.h" +#import "SWGFile.h" +#import "SWGApiClient.h" {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @@ -9,9 +10,6 @@ @implementation {{classname}} static NSString * basePath = @"{{basePath}}"; -@synthesize queue = _queue; -@synthesize api = _api; - +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key { static {{classname}}* singletonAPI = nil; @@ -22,21 +20,40 @@ static NSString * basePath = @"{{basePath}}"; return singletonAPI; } ++(void) setBasePath:(NSString*)path { + basePath = path; +} + ++(NSString*) getBasePath { + return basePath; +} + +-(SWGApiClient*) apiClient { + return [SWGApiClient sharedClientFromPool:basePath]; +} + +-(void) addHeader:(NSString*)value forKey:(NSString*)key { + [[self apiClient] setHeaderValue:value forKey:key]; +} + -(id) init { self = [super init]; - _queue = [[NSOperationQueue alloc] init]; - _api = [NIKApiInvoker sharedInstance]; - + [self apiClient]; return self; } --(void) addHeader:(NSString*) value +-(void) setHeaderValue:(NSString*) value forKey:(NSString*)key { - [_api addHeader:value forKey:key]; + [[self apiClient] setHeaderValue:value forKey:key]; } +-(unsigned long) requestQueueSize { + return [SWGApiClient requestQueueSize]; +} + + {{#operation}} --(void) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}}{{newline}} {{/allParams}} +-(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}}{{newline}} {{/allParams}} {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} { @@ -46,11 +63,11 @@ static NSString * basePath = @"{{basePath}}"; if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [_api escapeString:{{paramName}}]]; + {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [SWGApiClient escape:{{paramName}}]]; {{/pathParams}} - NSString* contentType = @"application/json"; - + NSString* requestContentType = @"application/json"; + NSString* responseContentType = @"application/json"; NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; {{#queryParams}}if({{paramName}} != nil) @@ -67,7 +84,7 @@ static NSString * basePath = @"{{basePath}}"; NSMutableArray * objs = [[NSMutableArray alloc] init]; for (id dict in (NSArray*)body) { if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; + [objs addObject:[(SWGObject*)dict asDictionary]]; } else{ [objs addObject:dict]; @@ -76,13 +93,20 @@ static NSString * basePath = @"{{basePath}}"; bodyDictionary = objs; } else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; + bodyDictionary = [(SWGObject*)body asDictionary]; } else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; + // convert it to a dictionary + NSError * error; + NSString * str = (NSString*)body; + NSDictionary *JSON = + [NSJSONSerialization JSONObjectWithData:[str dataUsingEncoding:NSUTF8StringEncoding] + options:NSJSONReadingMutableContainers + error:&error]; + bodyDictionary = JSON; } - else if([body isKindOfClass: [NIKFile class]]) { - contentType = @"form-data"; + else if([body isKindOfClass: [SWGFile class]]) { + requestContentType = @"form-data"; bodyDictionary = body; } else{ @@ -99,99 +123,109 @@ static NSString * basePath = @"{{basePath}}"; {{/requiredParams}} {{/requiredParamCount}} - {{#returnContainer}} - [_api dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - contentType: contentType - completionBlock: ^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - - {{#returnBaseType}} - if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - {{#returnTypeIsPrimitive}} - {{returnBaseType}}* d = [[{{returnBaseType}} alloc]initWithString: data]; - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc]initWithValues: dict]; - {{/returnTypeIsPrimitive}} - [objs addObject:d]; - } - completionBlock(objs, nil); - } - {{#returnSimpleType}} - {{#returnTypeIsPrimitive}}{{#returnBaseType}}completionBlock( [[{{returnBaseType}} alloc]initWithString: data], nil;{{/returnBaseType}} - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{#returnBaseType}}completionBlock( [[{{returnBaseType}} alloc]initWithValues: data], nil);{{/returnBaseType}} - {{/returnTypeIsPrimitive}} - {{/returnSimpleType}} + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - {{/returnBaseType}} - }]; + {{#returnContainer}} + return [client dictionary: requestUrl + method: @"{{httpMethod}}" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSDictionary *data, NSError *error) { + if (error) { + {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} + {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} + return; + } + + {{#returnBaseType}} + if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + {{#returnTypeIsPrimitive}} + // {{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}"){{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}}{{/instantiationType}}{{newline}} + {{returnBaseType}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data]; + {{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}} + {{{returnBaseType}}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: dict]; + {{/returnTypeIsPrimitive}} + [objs addObject:d]; + } + completionBlock(objs, nil); + } + {{#returnSimpleType}} + {{#returnTypeIsPrimitive}}{{#returnBaseType}}completionBlock( [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data], nil;{{/returnBaseType}} + {{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}} + {{#returnBaseType}}completionBlock( [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: data], nil);{{/returnBaseType}} + {{/returnTypeIsPrimitive}} + {{/returnSimpleType}} + + {{/returnBaseType}} + }]; {{/returnContainer}} {{#returnSimpleType}} {{#returnTypeIsPrimitive}} {{#returnBaseType}} - [_api stringWithCompletionBlock:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(nil, error); - return; - } - - completionBlock( [[{{returnBaseType}} alloc]initWithString: data], nil); - }]; + return [client stringWithCompletionBlock:requestUrl + method:@"{{httpMethod}}" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(nil, error); + return; + } + {{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; + completionBlock(result, nil); + }]; {{/returnBaseType}} {{^returnBaseType}} - [_api stringWithCompletionBlock:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSString *data, NSError *error) { - if (error) { - completionBlock(error); - return; - } - completionBlock(nil); - }]; + return [client stringWithCompletionBlock:requestUrl + method:@"{{httpMethod}}" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock:^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; {{/returnBaseType}} {{/returnTypeIsPrimitive}} {{#returnBaseType}} {{^returnTypeIsPrimitive}} - [_api dictionary:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - - {{#returnBaseType}} - {{#returnBaseType}}completionBlock( [[{{returnBaseType}} alloc]initWithValues: data], nil);{{/returnBaseType}} - {{/returnBaseType}} - }]; + return [client dictionary:requestUrl + method:@"{{httpMethod}}" + queryParams:queryParams + body:bodyDictionary + headerParams:headerParams + requestContentType:requestContentType + responseContentType:responseContentType + completionBlock:^(NSDictionary *data, NSError *error) { + if (error) { + {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} + {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} + return; + } + {{#returnBaseType}} + {{returnBaseType}} *result = nil; + if (data) { + result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: data]; + } + {{#returnBaseType}}completionBlock(result , nil);{{/returnBaseType}} + {{/returnBaseType}} + }]; {{/returnTypeIsPrimitive}} {{/returnBaseType}} {{/returnSimpleType}} @@ -200,98 +234,6 @@ static NSString * basePath = @"{{basePath}}"; {{/operation}} -{{#operation}} --(void) {{nickname}}AsJsonWithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}{{newline}}{{/hasMore}}{{/allParams}}{{newline}} - {{#returnBaseType}}completionHandler:(void (^)(NSString*, NSError *))completionBlock{{/returnBaseType}} - {{^returnBaseType}}completionHandler:(void (^)(NSError *))completionBlock{{/returnBaseType}} { - - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; - - // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@""]; - - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [_api escapeString:{{paramName}}]]; - {{/pathParams}} - - NSString* contentType = @"application/json"; - - NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; - {{#queryParams}}if({{paramName}} != nil) - queryParams[@"{{baseName}}"] = {{paramName}}; - {{/queryParams}} - NSMutableDictionary* headerParams = [[NSMutableDictionary alloc] init]; - {{#headerParams}}if({{paramName}} != nil) - headerParams[@"{{baseName}}"] = {{paramName}}; - {{/headerParams}} - - id bodyDictionary = nil; - {{#bodyParam}} - if(body != nil && [body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)body) { - if([dict respondsToSelector:@selector(asDictionary)]) { - [objs addObject:[(NIKSwaggerObject*)dict asDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([body respondsToSelector:@selector(asDictionary)]) { - bodyDictionary = [(NIKSwaggerObject*)body asDictionary]; - } - else if([body isKindOfClass:[NSString class]]) { - bodyDictionary = body; - } - else{ - NSLog(@"don't know what to do with %@", body); - } - - {{/bodyParam}} - - {{#requiredParamCount}} - {{#requiredParams}} - if({{paramName}} == nil) { - // error - } - {{/requiredParams}} - {{/requiredParamCount}} - - [_api dictionary:requestUrl - method:@"{{httpMethod}}" - queryParams:queryParams - body:bodyDictionary - headerParams:headerParams - contentType:contentType - completionBlock:^(NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} - return; - } - - {{#returnBaseType}} - NSData * responseData = nil; - if([data isKindOfClass:[NSDictionary class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - else if ([data isKindOfClass:[NSArray class]]){ - responseData = [NSJSONSerialization dataWithJSONObject:data - options:kNilOptions error:&error]; - } - NSString * json = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding]; - completionBlock(json, nil); - {{/returnBaseType}} - - {{^returnBaseType}}completionBlock(nil);{{/returnBaseType}}{{newline}} - }]; -{{newline}} -} - -{{/operation}} {{newline}} {{/operations}} @end \ No newline at end of file diff --git a/src/main/resources/objc/api-header.mustache b/src/main/resources/objc/api-header.mustache index e13de4b92c6..6b2091aed21 100644 --- a/src/main/resources/objc/api-header.mustache +++ b/src/main/resources/objc/api-header.mustache @@ -1,21 +1,16 @@ #import -#import "NIKApiInvoker.h" {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} {{#operations}} -@interface {{classname}}: NSObject { - -@private - NSOperationQueue *_queue; - NIKApiInvoker * _api; -} -@property(nonatomic, readonly) NSOperationQueue* queue; -@property(nonatomic, readonly) NIKApiInvoker* api; +@interface {{classname}}: NSObject -(void) addHeader:(NSString*)value forKey:(NSString*)key; - +-(unsigned long) requestQueueSize; ++({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; ++(void) setBasePath:(NSString*)basePath; ++(NSString*) getBasePath; {{#operation}} /** @@ -29,7 +24,7 @@ {{/allParams}} */ --(void) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}{{newline}} {{/hasMore}}{{/allParams}} +-(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}{{newline}} {{/hasMore}}{{/allParams}} {{#returnBaseType}}{{#hasParams}}{{newline}} completionHandler: {{/hasParams}}(void (^)({{returnType}} output, NSError* error))completionBlock;{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}}{{newline}} completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} diff --git a/src/main/resources/objc/model-body.mustache b/src/main/resources/objc/model-body.mustache index f918930c40f..f927adedb00 100644 --- a/src/main/resources/objc/model-body.mustache +++ b/src/main/resources/objc/model-body.mustache @@ -1,6 +1,6 @@ {{#models}} {{#model}} -#import "NIKDate.h" +#import "SWGDate.h" #import "{{classname}}.h" @implementation {{classname}} @@ -22,7 +22,7 @@ _{{name}} = dict[@"{{baseName}}"]; {{/isPrimitiveType}} {{#complexType}} - id {{name}}_dict = dict[@"{{name}}"]; + id {{name}}_dict = dict[@"{{baseName}}"]; {{#isContainer}} if([{{name}}_dict isKindOfClass:[NSArray class]]) { @@ -30,7 +30,7 @@ if([(NSArray*){{name}}_dict count] > 0) { for (NSDictionary* dict in (NSArray*){{name}}_dict) { - {{{complexType}}}* d = [[{{{complexType}}} alloc] initWithValues:dict]; + {{{complexType}}}* d = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc] initWithValues:dict]; [objs addObject:d]; } @@ -45,7 +45,8 @@ } {{/isContainer}} {{#isNotContainer}} - _{{name}} = [[{{complexType}} alloc]initWithValues:{{name}}_dict]; + if({{name}}_dict != nil) + _{{name}} = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{complexType}}} {{/instantiationType}} alloc]initWithValues:{{name}}_dict]; {{/isNotContainer}} {{/complexType}} {{/vars}}{{newline}} @@ -61,21 +62,21 @@ if([_{{name}} isKindOfClass:[NSArray class]]){ NSMutableArray * array = [[NSMutableArray alloc] init]; for( {{complexType}} *{{name}} in (NSArray*)_{{name}}) { - [array addObject:[(NIKSwaggerObject*){{name}} asDictionary]]; + [array addObject:[(SWGObject*){{name}} asDictionary]]; } - dict[@"{{baseName}}"] = array; + dict[@"{{name}}"] = array; } - else if(_{{name}} && [_{{name}} isKindOfClass:[NIKDate class]]) { - NSString * dateString = [(NIKDate*)_{{name}} toString]; + else if(_{{name}} && [_{{name}} isKindOfClass:[SWGDate class]]) { + NSString * dateString = [(SWGDate*)_{{name}} toString]; if(dateString){ dict[@"{{name}}"] = dateString; } } - } - else { - {{/complexType}} - if(_{{name}} != nil) dict[@"{{baseName}}"] = {{#complexType}}[(NIKSwaggerObject*){{/complexType}}_{{name}} {{#complexType}}asDictionary]{{/complexType}}; - {{#complexType}} + else { + {{/complexType}} + if(_{{name}} != nil) dict[@"{{baseName}}"] = {{#complexType}}[(SWGObject*){{/complexType}}_{{name}} {{#complexType}}asDictionary]{{/complexType}}; + {{#complexType}} + } } {{/complexType}} {{/vars}} diff --git a/src/main/resources/objc/model-header.mustache b/src/main/resources/objc/model-header.mustache index ae2b3189730..80b4458bca8 100644 --- a/src/main/resources/objc/model-header.mustache +++ b/src/main/resources/objc/model-header.mustache @@ -1,15 +1,15 @@ #import -#import "NIKSwaggerObject.h" +#import "SWGObject.h" {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} {{#models}} {{#model}} -@interface {{classname}} : NIKSwaggerObject +@interface {{classname}} : SWGObject {{#vars}} -@property(nonatomic) {{datatype}} {{name}}; +@property(nonatomic) {{datatype}} {{name}}; {{#description}}/* {{{description}}} {{#isNotRequired}}[optional]{{/isNotRequired}} */{{/description}}{{newline}} {{/vars}} - (id) {{#vars}}{{name}}: ({{datatype}}) {{name}}{{#hasMore}}{{newline}} {{/hasMore}}{{^hasMore}};{{/hasMore}} {{/vars}} From b6b28bb1a23a7a704d27e0f40fa6cad958679882 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:45:05 -0700 Subject: [PATCH 09/20] added version checking to avoid runtime scala incompatibilities --- bin/Version.scala | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 bin/Version.scala diff --git a/bin/Version.scala b/bin/Version.scala new file mode 100644 index 00000000000..8607187f845 --- /dev/null +++ b/bin/Version.scala @@ -0,0 +1,5 @@ +val version = scala.util.Properties.scalaPropOrElse("version.number", "unknown").toString match { + case "2.10.0" => "2.10" + case e: String => e +} +println(version) \ No newline at end of file From 5a3426dee6b3e6069f7435bb5d126f93888a7bcc Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:45:29 -0700 Subject: [PATCH 10/20] renamed to use SWG as default prefix --- .../swagger/codegen/BasicObjcGenerator.scala | 25 ++++++++++++------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala b/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala index b70409b7c37..02806438963 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/BasicObjcGenerator.scala @@ -45,7 +45,9 @@ class BasicObjcGenerator extends BasicGenerator { "NSString") override def typeMapping = Map( - "Date" -> "NIKDate", + "enum" -> "NSString", + "date" -> "SWGDate", + "Date" -> "SWGDate", "boolean" -> "NSNumber", "string" -> "NSString", "integer" -> "NSNumber", @@ -59,10 +61,9 @@ class BasicObjcGenerator extends BasicGenerator { "object" -> "NSObject") override def importMapping = Map( - "RVBDate" -> "NIKDate", - "Date" -> "NIKDate") + "Date" -> "SWGDate") - override def toModelFilename(name: String) = "RVB" + name + override def toModelFilename(name: String) = "SWG" + name // naming for the models override def toModelName(name: String) = { @@ -74,16 +75,24 @@ class BasicObjcGenerator extends BasicGenerator { ).toSet.contains(name) match { case true => name(0).toUpper + name.substring(1) case _ => { - "RVB" + name(0).toUpper + name.substring(1) + "SWG" + name(0).toUpper + name.substring(1) } } } + // objective c doesn't like variables starting with "new" + override def toVarName(name: String): String = { + if(name.startsWith("new") || reservedWords.contains(name)) { + escapeReservedWord(name) + } + else name + } + // naming for the apis - override def toApiName(name: String) = "RVB" + name(0).toUpper + name.substring(1) + "Api" + override def toApiName(name: String) = "SWG" + name(0).toUpper + name.substring(1) + "Api" // location of templates - override def templateDir = "src/main/resources/objc" + override def templateDir = "objc" // template used for models modelTemplateFiles += "model-header.mustache" -> ".h" @@ -110,7 +119,6 @@ class BasicObjcGenerator extends BasicGenerator { responseClass match { case "void" => None case e: String => { - println(responseClass) if(responseClass.toLowerCase.startsWith("array") || responseClass.toLowerCase.startsWith("list")) Some("NSArray") else @@ -162,7 +170,6 @@ class BasicObjcGenerator extends BasicGenerator { } override def toDeclaration(obj: ModelProperty) = { - println("getting declaration for " + obj) var declaredType = toDeclaredType(obj.`type`) declaredType.toLowerCase match { case "list" => { From 044621b325034b4c5266e421fc7eaaab76e54db7 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:45:45 -0700 Subject: [PATCH 11/20] fixed import issue for objc --- src/main/scala/com/wordnik/swagger/codegen/Codegen.scala | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala index 096dd45819e..b76455ec5b6 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala @@ -115,6 +115,7 @@ class Codegen(config: CodegenConfig) { case true => } }) + allImports --= config.defaultIncludes allImports --= primitives allImports --= containers @@ -235,11 +236,11 @@ class Codegen(config: CodegenConfig) { case n: Int => { val ComplexTypeMatcher = "(.*)\\[(.*)\\].*".r val ComplexTypeMatcher(container, basePart) = param.dataType - container + "[" + config.toDeclaredType(basePart) + "]" + config.toDeclaredType(container + "[" + config.toDeclaredType(basePart) + "]") } } - params += "dataType" -> config.toDeclaredType(u) + params += "dataType" -> u param.allowableValues match { case a: AllowableValues => params += "allowableValues" -> allowableValuesToString(a) @@ -424,7 +425,7 @@ class Codegen(config: CodegenConfig) { baseType = config.typeMapping.contains(baseType) match { case true => config.typeMapping(baseType) case false => { - imports += Map("import" -> config.toDeclaredType(baseType)) + // imports += Map("import" -> config.toDeclaredType(baseType)) baseType } } From 5076d76a7423baa26400eee41a52d2661c46dd22 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 14:46:03 -0700 Subject: [PATCH 12/20] updated scripts to detect scala version and use appropriate library if possible --- bin/android-java-petstore.sh | 11 ++++------- bin/csharp-petstore.sh | 11 ++++------- bin/flash-petstore.sh | 12 +++++------- bin/java-petstore-filemap.sh | 11 ++++------- bin/java-petstore.sh | 11 ++++------- bin/java-wordnik-api.sh | 13 +++++-------- bin/objc-petstore.sh | 13 ++++++------- bin/objc-wordnik-api.sh | 11 ++++------- bin/php-petstore.sh | 11 ++++------- bin/php-wordnik-api.sh | 11 ++++------- bin/python-petstore.sh | 11 ++++------- bin/python-wordnik-api.sh | 10 ++++------ bin/python3-petstore.sh | 11 ++++------- bin/python3-wordnik-api.sh | 11 ++++------- bin/ruby-petstore.sh | 11 ++++------- bin/runscala.sh | 11 ++++------- bin/scala-async.sh | 9 ++++----- bin/scala-petstore.sh | 10 ++++------ bin/scala-wordnik-api.sh | 12 +++++------- bin/static-docs.sh | 10 ++++------ bin/update-spec.sh | 10 ++++------ bin/validate.sh | 10 ++++------ 22 files changed, 93 insertions(+), 148 deletions(-) diff --git a/bin/android-java-petstore.sh b/bin/android-java-petstore.sh index 85e3be72d2e..881f55c835e 100755 --- a/bin/android-java-petstore.sh +++ b/bin/android-java-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/android-java/AndroidJavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/csharp-petstore.sh b/bin/csharp-petstore.sh index df7c23ba4c8..0a3b32074df 100755 --- a/bin/csharp-petstore.sh +++ b/bin/csharp-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/csharp/CsharpPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/flash-petstore.sh b/bin/flash-petstore.sh index a5ef38dbe1b..b28f805045b 100755 --- a/bin/flash-petstore.sh +++ b/bin/flash-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -21,14 +22,11 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties " ags="$@ samples/client/petstore/flash/FlashPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi diff --git a/bin/java-petstore-filemap.sh b/bin/java-petstore-filemap.sh index d65c9acb33c..59c34c5c4e1 100755 --- a/bin/java-petstore-filemap.sh +++ b/bin/java-petstore-filemap.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DfileMap=src/test/resources/petstore-1.1/resources.json -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index c3cf021f665..6edd5590bce 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/java/JavaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/java-wordnik-api.sh b/bin/java-wordnik-api.sh index 5b94d208a86..8a5f99a45e3 100755 --- a/bin/java-wordnik-api.sh +++ b/bin/java-wordnik-api.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -21,15 +22,11 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json" ags="$@ samples/client/wordnik-api/java/JavaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index aa60d23660a..9b44b495984 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -1,6 +1,9 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) + +version="$(scala ./bin/Version.scala)" while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +27,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/objc/ObjcPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/objc-wordnik-api.sh b/bin/objc-wordnik-api.sh index 1581152684e..9caf81f37c8 100755 --- a/bin/objc-wordnik-api.sh +++ b/bin/objc-wordnik-api.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" ags="$@ samples/client/wordnik-api/objc/ObjcWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/php-petstore.sh b/bin/php-petstore.sh index a51b38062a0..bcaf405d9ff 100755 --- a/bin/php-petstore.sh +++ b/bin/php-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/php/PHPPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/php-wordnik-api.sh b/bin/php-wordnik-api.sh index c56bdf7b89f..cb44bac1de2 100755 --- a/bin/php-wordnik-api.sh +++ b/bin/php-wordnik-api.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" ags="$@ samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh index e6539915248..2e23a34c4ad 100755 --- a/bin/python-petstore.sh +++ b/bin/python-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/python/PythonPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/python-wordnik-api.sh b/bin/python-wordnik-api.sh index 7758beb5066..fba87f8bc53 100755 --- a/bin/python-wordnik-api.sh +++ b/bin/python-wordnik-api.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,11 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" ags="$@ samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi diff --git a/bin/python3-petstore.sh b/bin/python3-petstore.sh index a0c027857b6..1608c9fed08 100755 --- a/bin/python3-petstore.sh +++ b/bin/python3-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/python3/Python3PetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/python3-wordnik-api.sh b/bin/python3-wordnik-api.sh index c6227230481..f9eaaaf00cf 100755 --- a/bin/python3-wordnik-api.sh +++ b/bin/python3-wordnik-api.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/ruby-petstore.sh b/bin/ruby-petstore.sh index 9a5dd87090f..b8466edf15c 100755 --- a/bin/ruby-petstore.sh +++ b/bin/ruby-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/ruby/RubyPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/runscala.sh b/bin/runscala.sh index a10525a2182..44090ab0632 100755 --- a/bin/runscala.sh +++ b/bin/runscala.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,12 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/scala-async.sh b/bin/scala-async.sh index d4ddecf381c..289e0e43a60 100755 --- a/bin/scala-async.sh +++ b/bin/scala-async.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -23,10 +24,8 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. ags="com.wordnik.swagger.codegen.ScalaAsyncClientGenerator $@" -if [ -f $APP_DIR/target/swagger-codegen.jar ]; then - java -cp target/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt "run-main $ags" + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - - diff --git a/bin/scala-petstore.sh b/bin/scala-petstore.sh index ff04f1ad483..dc3ff444d87 100755 --- a/bin/scala-petstore.sh +++ b/bin/scala-petstore.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,11 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ samples/client/petstore/scala/ScalaPetstoreCodegen.scala http://petstore.swagger.wordnik.com/api/api-docs special-key" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi diff --git a/bin/scala-wordnik-api.sh b/bin/scala-wordnik-api.sh index 59fdfe63bf9..5cfec0b37d4 100755 --- a/bin/scala-wordnik-api.sh +++ b/bin/scala-wordnik-api.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -21,14 +22,11 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json" ags="$@ samples/client/wordnik-api/scala/ScalaWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - scala -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt assembly - scala -cp target/swagger-codegen.jar $ags + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi diff --git a/bin/static-docs.sh b/bin/static-docs.sh index 373d049bb54..5884a3479b3 100755 --- a/bin/static-docs.sh +++ b/bin/static-docs.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -24,11 +25,8 @@ cd $APP_DIR export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" ags="$@ SwaggerDocGenerator http://developer.wordnik.com/v4/resources.json" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - java -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt "run-main $ags" + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/update-spec.sh b/bin/update-spec.sh index df444504762..60ec0943cc6 100755 --- a/bin/update-spec.sh +++ b/bin/update-spec.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -23,11 +24,8 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. ags="com.wordnik.swagger.codegen.SpecConverter $@" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - java -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt "run-main $ags" + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - diff --git a/bin/validate.sh b/bin/validate.sh index 4a34069ba3e..91fdcc382a2 100755 --- a/bin/validate.sh +++ b/bin/validate.sh @@ -1,6 +1,7 @@ #!/bin/sh SCRIPT="$0" +SCALA_RUNNER_VERSION=$(scala ./bin/Version.scala) while [ -h "$SCRIPT" ] ; do ls=`ls -ld "$SCRIPT"` @@ -23,11 +24,8 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. ags="com.wordnik.swagger.codegen.spec.Validator $@" -if [ -f $APP_DIR/target/scala-2.9.1/swagger-codegen.jar ]; then - scala -cp target/scala-2.9.1/swagger-codegen.jar $ags -elif [[ -f $APP_DIR/target/scala-2.10/swagger-codegen.jar ]]; then - java -cp target/scala-2.10/swagger-codegen.jar $ags +if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then + scala -cp target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar $ags else - ./sbt "run-main $ags" + echo "Please set scalaVersion := \"$SCALA_RUNNER_VERSION\" in build.sbt and run ./sbt assembly" fi - From 8fb6fc847c7bfe3ebb83accd4573d76085fa32eb Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 15:26:20 -0700 Subject: [PATCH 13/20] fix for #81 --- src/main/scala/com/wordnik/swagger/codegen/Codegen.scala | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala index 43b9eee76f2..f218b7fc149 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala @@ -171,7 +171,7 @@ class Codegen(config: CodegenConfig) { protected def compileTemplate(templateFile: String, rootDir: Option[File] = None, engine: Option[TemplateEngine] = None): (String, (TemplateEngine, Template)) = { val engine = new TemplateEngine(rootDir orElse Some(new File("."))) - val srcName = config.templateDir + File.separator + templateFile + val srcName = config.templateDir + "/" + templateFile val srcStream = { getClass.getClassLoader.getResourceAsStream(srcName) match { case is: java.io.InputStream => is From 2dda926cb65a229dfa12b4026bee334ba3d9b922 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Fri, 18 Oct 2013 16:05:50 -0700 Subject: [PATCH 14/20] added path to spec files --- bin/php-wordnik-api.sh | 2 +- bin/python-wordnik-api.sh | 2 +- bin/python3-wordnik-api.sh | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/bin/php-wordnik-api.sh b/bin/php-wordnik-api.sh index cb44bac1de2..06c046de5d5 100755 --- a/bin/php-wordnik-api.sh +++ b/bin/php-wordnik-api.sh @@ -22,7 +22,7 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json" ags="$@ samples/client/wordnik-api/php/PHPWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then diff --git a/bin/python-wordnik-api.sh b/bin/python-wordnik-api.sh index fba87f8bc53..1f5a33ca1ba 100755 --- a/bin/python-wordnik-api.sh +++ b/bin/python-wordnik-api.sh @@ -22,7 +22,7 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json" ags="$@ samples/client/wordnik-api/python/PythonWordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then diff --git a/bin/python3-wordnik-api.sh b/bin/python3-wordnik-api.sh index f9eaaaf00cf..772ee924fd6 100755 --- a/bin/python3-wordnik-api.sh +++ b/bin/python3-wordnik-api.sh @@ -22,7 +22,7 @@ cd $APP_DIR # if you've executed sbt assembly previously it will use that instead. -export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties -DfileMap=samples/client/wordnik-api/spec-files/resources.json" ags="$@ samples/client/wordnik-api/python3/Python3WordnikApiCodegen.scala http://api.wordnik.com/v4/resources.json" if [ -f $APP_DIR/target/scala-$SCALA_RUNNER_VERSION/swagger-codegen.jar ]; then From af96f33e6f72a1c9a2cc09ec7f0d9ffc85467b50 Mon Sep 17 00:00:00 2001 From: Russell Horton Date: Fri, 18 Oct 2013 16:24:08 -0700 Subject: [PATCH 15/20] regenerated python, python3 and php clients --- samples/client/petstore/python/swagger.py | 2 +- samples/client/petstore/python3/PetApi.py | 169 ++++++++++++++++-- samples/client/petstore/python3/StoreApi.py | 6 +- samples/client/petstore/python3/UserApi.py | 80 ++++----- .../petstore/python3/models/Category.py | 2 + .../client/petstore/python3/models/Order.py | 10 +- samples/client/petstore/python3/models/Pet.py | 17 +- samples/client/petstore/python3/models/Tag.py | 2 + .../client/petstore/python3/models/User.py | 25 ++- samples/client/petstore/python3/swagger.py | 43 +++-- .../wordnik-api/php/wordnik/Swagger.php | 1 + .../wordnik-api/python/wordnik/swagger.py | 27 +-- .../wordnik-api/python3/wordnik/swagger.py | 26 +-- .../com/wordnik/client/api/AccountApi.scala | 4 +- .../com/wordnik/client/api/WordApi.scala | 14 +- .../com/wordnik/client/api/WordListApi.scala | 2 +- .../com/wordnik/client/api/WordsApi.scala | 2 +- .../com/wordnik/client/model/Definition.scala | 8 +- .../com/wordnik/client/model/Example.scala | 2 +- .../wordnik/client/model/WordOfTheDay.scala | 2 +- 20 files changed, 317 insertions(+), 127 deletions(-) diff --git a/samples/client/petstore/python/swagger.py b/samples/client/petstore/python/swagger.py index 98ed6250e02..1065ad800e7 100644 --- a/samples/client/petstore/python/swagger.py +++ b/samples/client/petstore/python/swagger.py @@ -159,7 +159,7 @@ class ApiClient: instance = objClass() for attr, attrType in instance.swaggerTypes.iteritems(): - if attr in obj: + if obj is not None and attr in obj and type(obj) in [list, dict]: value = obj[attr] if attrType in ['str', 'int', 'long', 'float', 'bool']: attrType = eval(attrType) diff --git a/samples/client/petstore/python3/PetApi.py b/samples/client/petstore/python3/PetApi.py index 0bf9a88777b..42f20e12766 100644 --- a/samples/client/petstore/python3/PetApi.py +++ b/samples/client/petstore/python3/PetApi.py @@ -33,7 +33,7 @@ class PetApi(object): """Find pet by ID Args: - petId, str: ID of pet that needs to be fetched (required) + petId, int: ID of pet that needs to be fetched (required) Returns: Pet """ @@ -47,7 +47,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}/{petId}' + resourcePath = '/pet/{petId}' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -70,6 +70,155 @@ class PetApi(object): return responseObject + def deletePet(self, petId, **kwargs): + """Deletes a pet + + Args: + petId, str: Pet id to delete (required) + + Returns: + """ + + allParams = ['petId'] + + params = locals() + for (key, val) in params['kwargs'].items(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method deletePet" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'DELETE' + + queryParams = {} + headerParams = {} + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + + def partialUpdate(self, petId, body, **kwargs): + """partial updates to a pet + + Args: + petId, str: ID of pet that needs to be fetched (required) + body, Pet: Pet object that needs to be added to the store (required) + + Returns: Array[Pet] + """ + + allParams = ['petId', 'body'] + + params = locals() + for (key, val) in params['kwargs'].items(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method partialUpdate" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'PATCH' + + queryParams = {} + headerParams = {} + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + if not response: + return None + + responseObject = self.apiClient.deserialize(response, 'Array[Pet]') + return responseObject + + + def updatePetWithForm(self, petId, **kwargs): + """Updates a pet in the store with form data + + Args: + petId, str: ID of pet that needs to be updated (required) + name, str: Updated name of the pet (optional) + status, str: Updated status of the pet (optional) + + Returns: + """ + + allParams = ['petId', 'name', 'status'] + + params = locals() + for (key, val) in params['kwargs'].items(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method updatePetWithForm" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/{petId}' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + + if ('petId' in params): + replacement = str(self.apiClient.toPathValue(params['petId'])) + resourcePath = resourcePath.replace('{' + 'petId' + '}', + replacement) + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + + def uploadFile(self, **kwargs): + """uploads an image + + Args: + additionalMetadata, str: Additional data to pass to server (optional) + body, File: file to upload (optional) + + Returns: + """ + + allParams = ['additionalMetadata', 'body'] + + params = locals() + for (key, val) in params['kwargs'].items(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method uploadFile" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/pet/uploadImage' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + def addPet(self, body, **kwargs): """Add a new pet to the store @@ -88,7 +237,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}' + resourcePath = '/pet' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' @@ -120,7 +269,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}' + resourcePath = '/pet' resourcePath = resourcePath.replace('{format}', 'json') method = 'PUT' @@ -140,7 +289,7 @@ class PetApi(object): Args: status, str: Status values that need to be considered for filter (required) - Returns: list[Pet] + Returns: Array[Pet] """ allParams = ['status'] @@ -152,7 +301,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}/findByStatus' + resourcePath = '/pet/findByStatus' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -169,7 +318,7 @@ class PetApi(object): if not response: return None - responseObject = self.apiClient.deserialize(response, 'list[Pet]') + responseObject = self.apiClient.deserialize(response, 'Array[Pet]') return responseObject @@ -179,7 +328,7 @@ class PetApi(object): Args: tags, str: Tags to filter by (required) - Returns: list[Pet] + Returns: Array[Pet] """ allParams = ['tags'] @@ -191,7 +340,7 @@ class PetApi(object): params[key] = val del params['kwargs'] - resourcePath = '/pet.{format}/findByTags' + resourcePath = '/pet/findByTags' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -208,7 +357,7 @@ class PetApi(object): if not response: return None - responseObject = self.apiClient.deserialize(response, 'list[Pet]') + responseObject = self.apiClient.deserialize(response, 'Array[Pet]') return responseObject diff --git a/samples/client/petstore/python3/StoreApi.py b/samples/client/petstore/python3/StoreApi.py index 655f95e8747..95dd4b6c0ae 100644 --- a/samples/client/petstore/python3/StoreApi.py +++ b/samples/client/petstore/python3/StoreApi.py @@ -47,7 +47,7 @@ class StoreApi(object): params[key] = val del params['kwargs'] - resourcePath = '/store.{format}/order/{orderId}' + resourcePath = '/store/order/{orderId}' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -88,7 +88,7 @@ class StoreApi(object): params[key] = val del params['kwargs'] - resourcePath = '/store.{format}/order/{orderId}' + resourcePath = '/store/order/{orderId}' resourcePath = resourcePath.replace('{format}', 'json') method = 'DELETE' @@ -124,7 +124,7 @@ class StoreApi(object): params[key] = val del params['kwargs'] - resourcePath = '/store.{format}/order' + resourcePath = '/store/order' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' diff --git a/samples/client/petstore/python3/UserApi.py b/samples/client/petstore/python3/UserApi.py index 404e05b4f0a..1d3feb3585e 100644 --- a/samples/client/petstore/python3/UserApi.py +++ b/samples/client/petstore/python3/UserApi.py @@ -29,38 +29,6 @@ class UserApi(object): self.apiClient = apiClient - def createUsersWithArrayInput(self, body, **kwargs): - """Creates list of users with given input array - - Args: - body, list[User]: List of user object (required) - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].items(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithArrayInput" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user.{format}/createWithArray' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - - postData = (params['body'] if 'body' in params else None) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams) - - - def createUser(self, body, **kwargs): """Create user @@ -79,7 +47,39 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}' + resourcePath = '/user' + resourcePath = resourcePath.replace('{format}', 'json') + method = 'POST' + + queryParams = {} + headerParams = {} + + postData = (params['body'] if 'body' in params else None) + + response = self.apiClient.callAPI(resourcePath, method, queryParams, + postData, headerParams) + + + + def createUsersWithArrayInput(self, body, **kwargs): + """Creates list of users with given input array + + Args: + body, list[User]: List of user object (required) + + Returns: + """ + + allParams = ['body'] + + params = locals() + for (key, val) in params['kwargs'].items(): + if key not in allParams: + raise TypeError("Got an unexpected keyword argument '%s' to method createUsersWithArrayInput" % key) + params[key] = val + del params['kwargs'] + + resourcePath = '/user/createWithArray' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' @@ -97,7 +97,7 @@ class UserApi(object): """Creates list of users with given list input Args: - body, List[User]: List of user object (required) + body, list[User]: List of user object (required) Returns: """ @@ -111,7 +111,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/createWithList' + resourcePath = '/user/createWithList' resourcePath = resourcePath.replace('{format}', 'json') method = 'POST' @@ -144,7 +144,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/{username}' + resourcePath = '/user/{username}' resourcePath = resourcePath.replace('{format}', 'json') method = 'PUT' @@ -180,7 +180,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/{username}' + resourcePath = '/user/{username}' resourcePath = resourcePath.replace('{format}', 'json') method = 'DELETE' @@ -216,7 +216,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/{username}' + resourcePath = '/user/{username}' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -258,7 +258,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/login' + resourcePath = '/user/login' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' @@ -298,7 +298,7 @@ class UserApi(object): params[key] = val del params['kwargs'] - resourcePath = '/user.{format}/logout' + resourcePath = '/user/logout' resourcePath = resourcePath.replace('{format}', 'json') method = 'GET' diff --git a/samples/client/petstore/python3/models/Category.py b/samples/client/petstore/python3/models/Category.py index 8dc3a9aa1fb..2d598186fb3 100644 --- a/samples/client/petstore/python3/models/Category.py +++ b/samples/client/petstore/python3/models/Category.py @@ -27,6 +27,8 @@ class Category: } + #Category unique identifier self.id = None # int + #Name of the category self.name = None # str diff --git a/samples/client/petstore/python3/models/Order.py b/samples/client/petstore/python3/models/Order.py index 8e886fedbab..8da56e2836f 100644 --- a/samples/client/petstore/python3/models/Order.py +++ b/samples/client/petstore/python3/models/Order.py @@ -23,17 +23,21 @@ class Order: self.swaggerTypes = { 'id': 'int', 'petId': 'int', - 'status': 'str', 'quantity': 'int', + 'status': 'str', 'shipDate': 'datetime' } + #Unique identifier for the order self.id = None # int + #ID of pet being ordered self.petId = None # int - #Order Status - self.status = None # str + #Number of pets ordered self.quantity = None # int + #Status of the order + self.status = None # str + #Date shipped, only if it has been self.shipDate = None # datetime diff --git a/samples/client/petstore/python3/models/Pet.py b/samples/client/petstore/python3/models/Pet.py index e27e20a8b96..e9093d8f470 100644 --- a/samples/client/petstore/python3/models/Pet.py +++ b/samples/client/petstore/python3/models/Pet.py @@ -21,21 +21,26 @@ class Pet: def __init__(self): self.swaggerTypes = { - 'tags': 'list[Tag]', 'id': 'int', 'category': 'Category', - 'status': 'str', 'name': 'str', - 'photoUrls': 'list[str]' + 'photoUrls': 'list[str]', + 'tags': 'list[Tag]', + 'status': 'str' } - self.tags = None # list[Tag] + #Unique identifier for the Pet self.id = None # int + #Category the pet is in self.category = None # Category + #Friendly name of the pet + self.name = None # str + #Image URLs + self.photoUrls = None # list[str] + #Tags assigned to this pet + self.tags = None # list[Tag] #pet status in the store self.status = None # str - self.name = None # str - self.photoUrls = None # list[str] diff --git a/samples/client/petstore/python3/models/Tag.py b/samples/client/petstore/python3/models/Tag.py index 3b508edbd95..c4d7aed51e1 100644 --- a/samples/client/petstore/python3/models/Tag.py +++ b/samples/client/petstore/python3/models/Tag.py @@ -27,6 +27,8 @@ class Tag: } + #Unique identifier for the tag self.id = None # int + #Friendly name for the tag self.name = None # str diff --git a/samples/client/petstore/python3/models/User.py b/samples/client/petstore/python3/models/User.py index d4e35a081f2..30d0b052f9d 100644 --- a/samples/client/petstore/python3/models/User.py +++ b/samples/client/petstore/python3/models/User.py @@ -22,24 +22,31 @@ class User: def __init__(self): self.swaggerTypes = { 'id': 'int', - 'lastName': 'str', - 'phone': 'str', 'username': 'str', - 'email': 'str', - 'userStatus': 'int', 'firstName': 'str', - 'password': 'str' + 'lastName': 'str', + 'email': 'str', + 'password': 'str', + 'phone': 'str', + 'userStatus': 'int' } + #Unique identifier for the user self.id = None # int - self.lastName = None # str - self.phone = None # str + #Unique username self.username = None # str + #First name of the user + self.firstName = None # str + #Last name of the user + self.lastName = None # str + #Email address of the user self.email = None # str + #Password name of the user + self.password = None # str + #Phone number of the user + self.phone = None # str #User Status self.userStatus = None # int - self.firstName = None # str - self.password = None # str diff --git a/samples/client/petstore/python3/swagger.py b/samples/client/petstore/python3/swagger.py index e350bb8e19f..293cc09cb55 100644 --- a/samples/client/petstore/python3/swagger.py +++ b/samples/client/petstore/python3/swagger.py @@ -35,7 +35,7 @@ class ApiClient: for param, value in headerParams.items(): headers[param] = value - headers['Content-type'] = 'application/json' + #headers['Content-type'] = 'application/json' headers['api_key'] = self.apiKey if self.cookie: @@ -43,15 +43,19 @@ class ApiClient: data = None - if method == 'GET': + + if queryParams: + # Need to remove None values, these should not be sent + sentQueryParams = {} + for param, value in queryParams.items(): + if value != None: + sentQueryParams[param] = value + url = url + '?' + urllib.parse.urlencode(sentQueryParams) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) + if method in ['GET']: + + #Options to add statements later on and for compatibility + pass elif method in ['POST', 'PUT', 'DELETE']: @@ -84,21 +88,21 @@ class ApiClient: return data def toPathValue(self, obj): - """Serialize a list to a CSV string, if necessary. + """Convert a string or object to a path-friendly value Args: - obj -- data object to be serialized + obj -- object or string value Returns: - string -- json serialization of object + string -- quoted value """ if type(obj) == list: - return ','.join(obj) + return urllib.parse.quote(','.join(obj)) else: - return obj + return urllib.parse.quote(str(obj)) def sanitizeForSerialization(self, obj): """Dump an object into JSON for POSTing.""" - if not obj: + if type(obj) == type(None): return None elif type(obj) in [str, int, float, bool]: return obj @@ -133,12 +137,12 @@ class ApiClient: subClass = match.group(1) return [self.deserialize(subObj, subClass) for subObj in obj] - if (objClass in ['int', 'float', 'dict', 'list', 'str']): + if (objClass in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']): objClass = eval(objClass) else: # not a native type, must be model class objClass = eval(objClass + '.' + objClass) - if objClass in [str, int, float, bool]: + if objClass in [int, float, dict, list, str, bool]: return objClass(obj) elif objClass == datetime: # Server will always return a time stamp in UTC, but with @@ -159,7 +163,12 @@ class ApiClient: value = attrType(value) except UnicodeEncodeError: value = unicode(value) + except TypeError: + value = value setattr(instance, attr, value) + elif (attrType == 'datetime'): + setattr(instance, attr, datetime.datetime.strptime(value[:-5], + "%Y-%m-%dT%H:%M:%S.%f")) elif 'list[' in attrType: match = re.match('list\[(.*)\]', attrType) subClass = match.group(1) diff --git a/samples/client/wordnik-api/php/wordnik/Swagger.php b/samples/client/wordnik-api/php/wordnik/Swagger.php index e7b7c11fbeb..ddf7d79de63 100644 --- a/samples/client/wordnik-api/php/wordnik/Swagger.php +++ b/samples/client/wordnik-api/php/wordnik/Swagger.php @@ -239,3 +239,4 @@ class APIClient { ?> + diff --git a/samples/client/wordnik-api/python/wordnik/swagger.py b/samples/client/wordnik-api/python/wordnik/swagger.py index f63cc585e25..1065ad800e7 100644 --- a/samples/client/wordnik-api/python/wordnik/swagger.py +++ b/samples/client/wordnik-api/python/wordnik/swagger.py @@ -36,7 +36,7 @@ class ApiClient: for param, value in headerParams.iteritems(): headers[param] = value - headers['Content-type'] = 'application/json' + #headers['Content-type'] = 'application/json' headers['api_key'] = self.apiKey if self.cookie: @@ -44,15 +44,18 @@ class ApiClient: data = None - if method == 'GET': + if queryParams: + # Need to remove None values, these should not be sent + sentQueryParams = {} + for param, value in queryParams.items(): + if value != None: + sentQueryParams[param] = value + url = url + '?' + urllib.urlencode(sentQueryParams) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.urlencode(sentQueryParams) + if method in ['GET']: + + #Options to add statements later on and for compatibility + pass elif method in ['POST', 'PUT', 'DELETE']: @@ -95,7 +98,7 @@ class ApiClient: def sanitizeForSerialization(self, obj): """Dump an object into JSON for POSTing.""" - if not obj: + if type(obj) == type(None): return None elif type(obj) in [str, int, long, float, bool]: return obj @@ -156,7 +159,7 @@ class ApiClient: instance = objClass() for attr, attrType in instance.swaggerTypes.iteritems(): - if attr in obj: + if obj is not None and attr in obj and type(obj) in [list, dict]: value = obj[attr] if attrType in ['str', 'int', 'long', 'float', 'bool']: attrType = eval(attrType) @@ -164,6 +167,8 @@ class ApiClient: value = attrType(value) except UnicodeEncodeError: value = unicode(value) + except TypeError: + value = value setattr(instance, attr, value) elif (attrType == 'datetime'): setattr(instance, attr, datetime.datetime.strptime(value[:-5], diff --git a/samples/client/wordnik-api/python3/wordnik/swagger.py b/samples/client/wordnik-api/python3/wordnik/swagger.py index e77856eeb18..293cc09cb55 100644 --- a/samples/client/wordnik-api/python3/wordnik/swagger.py +++ b/samples/client/wordnik-api/python3/wordnik/swagger.py @@ -35,7 +35,7 @@ class ApiClient: for param, value in headerParams.items(): headers[param] = value - headers['Content-type'] = 'application/json' + #headers['Content-type'] = 'application/json' headers['api_key'] = self.apiKey if self.cookie: @@ -43,15 +43,19 @@ class ApiClient: data = None - if method == 'GET': + + if queryParams: + # Need to remove None values, these should not be sent + sentQueryParams = {} + for param, value in queryParams.items(): + if value != None: + sentQueryParams[param] = value + url = url + '?' + urllib.parse.urlencode(sentQueryParams) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value != None: - sentQueryParams[param] = value - url = url + '?' + urllib.parse.urlencode(sentQueryParams) + if method in ['GET']: + + #Options to add statements later on and for compatibility + pass elif method in ['POST', 'PUT', 'DELETE']: @@ -98,7 +102,7 @@ class ApiClient: def sanitizeForSerialization(self, obj): """Dump an object into JSON for POSTing.""" - if not obj: + if type(obj) == type(None): return None elif type(obj) in [str, int, float, bool]: return obj @@ -159,6 +163,8 @@ class ApiClient: value = attrType(value) except UnicodeEncodeError: value = unicode(value) + except TypeError: + value = value setattr(instance, attr, value) elif (attrType == 'datetime'): setattr(instance, attr, datetime.datetime.strptime(value[:-5], diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala index a5dd0901880..ca4e6e9fe08 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/AccountApi.scala @@ -1,8 +1,8 @@ package com.wordnik.client.api -import com.wordnik.client.model.User -import com.wordnik.client.model.WordList import com.wordnik.client.model.ApiTokenStatus +import com.wordnik.client.model.WordList +import com.wordnik.client.model.User import com.wordnik.client.model.AuthenticationToken import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala index cab9db7e07a..de8f3d0348c 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordApi.scala @@ -1,16 +1,16 @@ package com.wordnik.client.api -import com.wordnik.client.model.FrequencySummary -import com.wordnik.client.model.Bigram -import com.wordnik.client.model.WordObject -import com.wordnik.client.model.ExampleSearchResults -import com.wordnik.client.model.Example +import com.wordnik.client.model.Definition import com.wordnik.client.model.ScrabbleScoreResult import com.wordnik.client.model.TextPron +import com.wordnik.client.model.Example import com.wordnik.client.model.Syllable -import com.wordnik.client.model.Related -import com.wordnik.client.model.Definition import com.wordnik.client.model.AudioFile +import com.wordnik.client.model.ExampleSearchResults +import com.wordnik.client.model.WordObject +import com.wordnik.client.model.Bigram +import com.wordnik.client.model.Related +import com.wordnik.client.model.FrequencySummary import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala index bc4124f6c2a..3b51e692c24 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordListApi.scala @@ -1,8 +1,8 @@ package com.wordnik.client.api -import com.wordnik.client.model.WordListWord import com.wordnik.client.model.WordList import com.wordnik.client.model.StringValue +import com.wordnik.client.model.WordListWord import com.wordnik.client.common.ApiInvoker import com.wordnik.client.common.ApiException diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala index a5b96d4f3f2..92e9fac23b7 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/api/WordsApi.scala @@ -1,7 +1,7 @@ package com.wordnik.client.api -import com.wordnik.client.model.DefinitionSearchResults import com.wordnik.client.model.WordObject +import com.wordnik.client.model.DefinitionSearchResults import com.wordnik.client.model.WordOfTheDay import com.wordnik.client.model.WordSearchResults import com.wordnik.client.common.ApiInvoker diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala index 9f2996d793c..67d29195bf3 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Definition.scala @@ -1,11 +1,11 @@ package com.wordnik.client.model -import com.wordnik.client.model.Label import com.wordnik.client.model.ExampleUsage -import com.wordnik.client.model.TextPron -import com.wordnik.client.model.Citation -import com.wordnik.client.model.Related import com.wordnik.client.model.Note +import com.wordnik.client.model.Citation +import com.wordnik.client.model.TextPron +import com.wordnik.client.model.Label +import com.wordnik.client.model.Related case class Definition ( extendedText: String, text: String, diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala index 349ec7e70a5..3d3e45996a2 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/Example.scala @@ -1,8 +1,8 @@ package com.wordnik.client.model import com.wordnik.client.model.Sentence -import com.wordnik.client.model.ContentProvider import com.wordnik.client.model.ScoredWord +import com.wordnik.client.model.ContentProvider case class Example ( id: Long, exampleId: Long, diff --git a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala index dccf9403f2d..3c64a66571b 100644 --- a/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala +++ b/samples/client/wordnik-api/scala/src/main/scala/com/wordnik/client/model/WordOfTheDay.scala @@ -1,8 +1,8 @@ package com.wordnik.client.model import java.util.Date -import com.wordnik.client.model.SimpleExample import com.wordnik.client.model.SimpleDefinition +import com.wordnik.client.model.SimpleExample import com.wordnik.client.model.ContentProvider case class WordOfTheDay ( id: Long, From 01b745c366732fd8a41aa8debf9777d5b7daf353 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 22 Oct 2013 02:23:50 -0700 Subject: [PATCH 16/20] added hack to support writing json models in 1.1 format --- .../com/wordnik/swagger/codegen/Codegen.scala | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala index f218b7fc149..d78bae95110 100644 --- a/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala +++ b/src/main/scala/com/wordnik/swagger/codegen/Codegen.scala @@ -500,6 +500,18 @@ class Codegen(config: CodegenConfig) { } } + def writeJson(m: AnyRef): String = { + Option(System.getProperty("modelFormat")) match { + case Some(e) if e =="1.1" => write1_1(m) + case _ => write(m) + } + } + + def write1_1(m: AnyRef): String = { + implicit val formats = SwaggerSerializers.formats("1.1") + write(m) + } + def writeSupportingClasses(apis: Map[(String, String), List[(String, Operation)]], models: Map[String, Model]) = { val rootDir = new java.io.File(".") val engine = new TemplateEngine(Some(rootDir)) @@ -519,7 +531,7 @@ class Codegen(config: CodegenConfig) { val modelList = new ListBuffer[HashMap[String, AnyRef]] models.foreach(m => { - val json = write(m._2) + val json = writeJson(m._2) modelList += HashMap( "modelName" -> m._1, From d5b53a17787fed779c03c94b57d067dcbffd696a Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 22 Oct 2013 02:24:37 -0700 Subject: [PATCH 17/20] updated templates --- samples/server-generator/node/templates/api.mustache | 11 ++++++----- samples/server-generator/node/templates/main.mustache | 3 +-- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/samples/server-generator/node/templates/api.mustache b/samples/server-generator/node/templates/api.mustache index 9cf99367f9a..055b320effd 100644 --- a/samples/server-generator/node/templates/api.mustache +++ b/samples/server-generator/node/templates/api.mustache @@ -1,6 +1,7 @@ var swagger = require("swagger-node-express"); var url = require("url"); var errors = swagger.errors; +var params = swagger.params; /* add model includes */ @@ -22,15 +23,15 @@ exports.{{nickname}} = { "path" : "{{path}}", "notes" : "{{{notes}}}", "summary" : "{{{summary}}}", - "method": "{{httpMethod}}", + "httpMethod": "{{httpMethod}}", "params" : [{{#queryParams}} - swagger.queryParam("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{required}}, {{allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}} + params.query("{{paramName}}", "{{description}}", "{{swaggerDataType}}", {{required}}, {{allowMultiple}}, "{{{allowableValues}}}"{{#defaultValue}}, {{{defaultValue}}}{{/defaultValue}}){{#hasMore}},{{/hasMore}} {{/queryParams}}].concat([{{#pathParams}} - swagger.pathParam("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} + params.path("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} {{/pathParams}}]).concat([{{#headerParams}} - swagger.header("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} + params.header("{{paramName}}", "{{description}}"){{#hasMore}},{{/hasMore}} {{/headerParams}}]).concat([{{#bodyParams}} - swagger.postParam("{{swaggerDataType}}", "{{description}}", {{required}}) + params.body("body", "{{swaggerDataType}}", "{{description}}", {{required}}) {{/bodyParams}}]), "responseClass" : "{{returnType}}", "errorResponses" : [errors.invalid('id'), errors.notFound('{{returnType}}')], diff --git a/samples/server-generator/node/templates/main.mustache b/samples/server-generator/node/templates/main.mustache index c02df860521..aa0acc81d98 100644 --- a/samples/server-generator/node/templates/main.mustache +++ b/samples/server-generator/node/templates/main.mustache @@ -8,7 +8,6 @@ app.use(express.bodyParser()); swagger.setAppHandler(app); -// resources for the demo {{#apis}} var {{name}}Api = require("./apis/{{className}}.js"); {{/apis}} @@ -16,7 +15,7 @@ var {{name}}Api = require("./apis/{{className}}.js"); swagger.addModels(models) {{#apis}} {{#operations}} - {{#operation}}.add{{httpMethod}}({{name}}Api.{{nickname}}){{/operation}}{{newline}} + {{#operation}}.add{{method}}({{name}}Api.{{nickname}}){{/operation}}{{newline}} {{/operations}} {{/apis}}; From 27a8be23819270fad5b2e6a0c73a55d3d64c74ee Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 22 Oct 2013 12:08:31 -0700 Subject: [PATCH 18/20] upped version for release --- build.sbt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/build.sbt b/build.sbt index 8a808b74a77..8ce46eac954 100644 --- a/build.sbt +++ b/build.sbt @@ -5,9 +5,9 @@ organization := "com.wordnik" name := "swagger-codegen" -version := "2.0.10-SNAPSHOT" +version := "2.0.11" -scalaVersion := "2.10.0" +scalaVersion := "2.9.1" javacOptions ++= Seq("-target", "1.6", "-source", "1.6", "-Xlint:unchecked", "-Xlint:deprecation") From b815ffa4033ddbcad5ab2efbb841c8b0b71355b0 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 22 Oct 2013 12:08:43 -0700 Subject: [PATCH 19/20] formatting --- .../UserInterfaceState.xcuserstate | Bin 14324 -> 15400 bytes .../scalatra/templates/api.mustache | 1 - 2 files changed, 1 deletion(-) diff --git a/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate b/samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata/tony.xcuserdatad/UserInterfaceState.xcuserstate index 742c5c4def3185ea558fd8de6745c5f7f6f60685..86db4ca5035c954f237bd14307c8e615c2ce6c8b 100644 GIT binary patch delta 8235 zcmaKQ2Vhji^Z(B7yIe2H zdKbNi-bdTecC;JqL5I*`^btCSzCdTtWpoAIK;NRf=pK5Eo}fR`Uw{Arg9v1x1s&+Y z07i%bAEZDXs0;N1P#;pE0W^e0&={IR3uq1Ppd(~JH|PzyFc9*f0ER;$jD|5V7RJE> zSO|+?F$7@=EQMvT99F569dLrfFrOB%W)*uU@g|+SZu|K*p5?h9b6aJ!}W0s+!D9K zt#KRN9>0z|<1V-d?u+xV9}mKXxCoEHCHPG|9#cFM&%(3uVjRRv@EW`kzk|2qop?9i zhxg;d_!E2_e~!=MAMo7(zK8GQAMpeH6Ml$)#*gr0{0IIM|3wgy5fzCf8loje5<}vM zh1iLM)FyREL(+`2B&|qSl1aLe?j(!!AU#Qcl1=hR0U1sTNf8-A#*%U5O)`m0CDX`s zGM_9U3&|p~m@Fr&$=l>T@;>>11a^`=WG^{L4w0keV{(R^CFjU_a)DeVm&ljoCi#xs zB0rNy&A8GvbY{xPcD}m$mMZ-LYH zb%Vcf^I~JDiN?|-I*3udL5r!YPy1G_yXEAj=j8eef@K1=AzP(wK5}IK$da7GlGb_o zB}K&}({siZjVcKq7A&dXkCBIan-}|Y`egQK+u2{zd_=xyxLAeGBQcU7DauAU$XSL4 zP;(i|rE%01v_=_{(IAvxjs~M4)I#mlSxr0)6{4teRDgz4D~&HlMQ8-I(FCSbt4M30 zvn`EJMxlS_P%3JG#-Oo%GcsG{4=l+qD$FS!SI&AGSF?H(P5d8L0mjNf6K!clmKsc^ zpsD>cGCPeb$;mD7H!m*E8CQX(poXY%c#Y|3Mz%^_MbJJ(@%L&KXnM`{W}*4WS&3$& zIcP4LN8Pj*txY|ZXaQP?7NNz|OJAqmXm{$$R#}2))w{Q3rh32z+lHuqW{q~#)wg+@41dX(qT*rs!M<8?0R4h~N6rdH@D%;V zNZQj5p^s`wm@IuWi$)a>^oOPB_d=}jmngGyvHyj#KtND!D~O;OFKq>4kRWGiDRos- z${~_12?|hxRz*A0F0^X}M6rGBKr`9?nV5Ng*LEY>DpSZI`nU4ujv8D&*93Ot+zhc` zhB&Z*72?4L36My$Xb;+x_M*LMAKI7pqy0A{8#uuQN$gz-72lS*v=rCINGUlNV^sgDHkPQQ9J{=nJ zVS~*Gei-t~a6SyB1#~zY&NrBiPz1%V43C5oT0}>%;WC36dIo<^$o9jVFg0Y%@h|}< z!XyX)1s*2D6grZY&{1?W9Ye>`ar8|(elxPebYw>zPzRU|b6_saW8gS}{h8Rag&w9K z(Gy|69a1!=YR3lqi$m}iJR7krp?5(QI(94ezjT+Cu$mbJR?&%Nu!c@z8*yFgO@mS> z4|SK(Kp9j}%G|nBPJUsv6*s}#D5?V9g3Yjn@^mttQUUKUk=~_KnHX;|?J{IJ-QWXM zuMBq5X;fJ~aW@=hcmjK1FYJT;Z~zX%Av>pfl+#I-Aa+b2q_9a0HIR$M6Y!3diU? zI-f41m2?%|KsPe!hZR71IPrzAUIDYlp|8vth70IHdWa_eZ3kQ0DAg---oVAL zWC1)1j|nL?njR^`W9iWO&ySLQ6h3+ZR{IE&MDQ8AGh@KU@CFK0fsg8A4gygE2X*wJ#H zdDTgJ=@MRx*Ri4XxD=PM;T5=&74I8Rzu>RJjKFz%k)Em%%6JogD;&!79Q`~T#$oT< z%EB1Gi{HcV)6?_|dZtDghhjGz(=S3Z9Fu!kOrHJ!$7GvO_)+w#j2|&6D^WizMg8an zro=_c%0iZ?@TZ{wSjCi5hC}59KAEj@FslWx6K&8dRbqT9m?rgc_%!|^SSq!%SUwY6 zC-r9IbC?w>Tkv^&0bj(I@R#^9zJjmfukhFOGQC2t(y!>(^c#AOUZ?+|H?|-_P5l;Lqi^3BbVpZp-wm!az0z%{>b@Vm{c5+ls{27O%T!P7m5mh4UcDkFV)KujriNU2W-u*f7iB$o$PFGReI zP2wk^nuH7@gL%L_kaChwhVsDiAYie^jw(TurJm^xQt~PlIzUEK<`hCkG|b{k8P6P* zOyEI6l@~~WB_NiD2qiq3Os4c2=`ZkC9c*}z^C06v%0pC8Y34n)=DQ=WG@FHDt8F}k z%w|O}nMr2xpx{ASPUeugJg9hxWSTs-G$lc@B-qDl5mb<+WLdD6HLYL;S@{Y~ku{_O zIX9BEWF1*gN=X?U<3YoNjt2t|F+9Z5jT=cN*+4duP2?@InTI$Y96TiPP@4xI5A|N% zsdqy=#e+6mH7s}|VL(u2l<0@lbkH4P0)4h>DkI1WUW@mtYdGre@USsxu}#y~=sytd zH)X5ly_jYWS`rk&CJC~dWJkhe=D(MZ@{v!-iBKSYN{*4w$Z;MlJXm>%=fPGEyxn zf@Rg_T{e7nyl03{YD%5zbWCoOd;i2KuS&Z65q@X!X+oCzU1|U zu*1&3NcD_7XRQ9DZ+Ir&i?joPkYXj#Hn9)X;8m%+Wxb>^W14@|9e#?9hdwm$jHKL1u4G4>q@g&_y(+zNqq#BtULNCG<&@-9 zu&%MFaTdE8VPDlYeUsx^d^24pa1*(7F2K<$je79VlPSeRFCKbtl%0Dj; zedsP87#{X#Rp72r-4f4|XmbWiqw`C~bq#uJuWGk|3AB(~6slH3wQ|V2uZm)3%;BM5 zSh^s$BrJ%(oC~7H>@LNZ?DaM9`s!G6N-QajlIvMIcTx=vDm=#CD^Y$KlCz7e@F|m9 zi}JU?F>XCq%9XL~$8sM_fE&3@bR!P~dGPZvm?cA&3h56#4B^?q&{+duxOc)3koPwP z)Igj@k)JXcyF$Jq-;nF%2D^v6MZPCLkbC4AyLHUw#&cV^QvvRd zfC%CQPJvrcTi_Km5VRDe3%Ut<333HRg2{rZg6V>pg4u$(g871lg2jR*f=z*=#Px_95jP`lMLddl8u5F?b724pv5*r+2&07#p;PD+HWIcKrVD!s`wIsMbA^M2 z`NCns;lk0vfN;KWsc@a}1K~d5XTr0>^TLb5FNIfx-wMAI-WJ{w-WA>#DMcPp3sJ79 zNHj@AMUzESMbkwyMYBb7MXNzL;{isiAW-mC?$~+ zwL~K^N*t0}5|1QVQcsd9X((wd=^*JL=_~0k86fdX221iK!z7a=b0iBTizQ1WDXf>rwWZ0@6lq;)b7>1{OKEFqS7|S4A89{nwseqmh;*p5Kw2oBCEYANEIlHaBv~z)N0uy03CQZo>dP9)8p*oL@?>LWb7iY#J7mXX zH)X%cm2$n@AditJ$bIq#@}}~(@^e)&Q9VflIa*YY3a59AN!kK|9~zssM?|4;;^ zifDyZVOKa6NeZvRr>LW-r)a0>qIgHKM{!DVT5(2kPH{nTNpV?mRq?grn&M~0W5q9u zr;6Vd&lP_t{!)UHC-()8U|F2RZUdQRLxbxRnt^!RU1{CRd1`ds`jdmt4^vuSAC&6 zt2(c`sQOZMTXjcuS9M?YK=n}dNcBYZYb1$OMkYlzjqDvcHgalYY2?<(4MNy?uJEFdbIvaI9DsVCC%cv`A zsXAI6qmEU_sjX_8x|TXs-B8_F-B#UMU8F8i2i0rT>(r&{P3rg6+tnYakE+k8zgFK? z-%;OH-;eGQJs^5?^!VsS(W|0Ai9Qkii^iqts>#+2){NAQ(u~oJ(@fUP)XdWaHET5M zHD#I#&0fth%^A%(%>~V+fabF1hUTW`mgalS51MMi;BI z>)g89IZ|Fwr#_HbG1p+!=H$^v1w?MZ-w?Vg2 zw@J5I_n~f&ZlCU;?y&BN?vn1h?mOLW-5uRs-BaCvb${xSUZ5B1#d@h;qc`i_`ec2I zzOKHZzOlZEzL~y@zPEmup6XZWcj|ZP_vrWO59lxHuj_B?9~m?TtHEYSG&l?{LsLVV zp@pGUz|h9f&d|ls)6m<{*U;ZEz>sekW*BZ5Z5V5K(=f#_%`n5T%ur$2VAy2XY&c^0 z*zl?0Gs6kPdBY{cWy4j&O{3fxWqi%p+BnQO!nn*>Vcc!pYus-tFzZ!otJ~RF|CZLWEM`Z{>6kk)f0<+^ zwMk>rnG7b2Dc+P|a+qAEOw&Bmho+;ZQ>N3VGp2K<3#M;O*G)G}H%+%p-DV)|=gdNLv{`31m`!H0*>p@R`Yx2ZRQo`HrN?E&b&l&A*DWq9E+=kaoIh?z+_1R9xDj!saVO)RSzMMLmNzVuEWBlkWx8dS zWsYUNaGmAEHyU*bV~Eqg5O)2opDZ=GsW4=+0NO)neNPR zc6Ro1_H|}EbDVk3LCzxQ1m|>T(7DXH(z(XD-dW~+FW@}rJn1~+Jny{Z{K|RFdBb_r z`P8L!?R6b;opPObU2H)_F=j<(^8z(KgdY5`P zd$)UcdUtvEc#n9$^j`6P?Y-{(*883Jw)c+rZeQ<@-iO{t-oKI|nIuOfmn8GaQ?Nmarn)B5`I_zrcC-j DdzF-D delta 7876 zcmaJ_2Y6Fe`#<9*O`3hP(o#)pE)2qLmO zmXW>fpRb&Oa||Ph2TT598`lEum*etJ_etFS>RK!1$+U% z0=vN1-~jjm90te132+Xa2fu?qz%}qExCJ3Z5JLtEpb$nt5fno$)ImKoKqEB4C}@Tj z$Uz58g!Nzp*w_!7z!oqCror~G6YL7R!S1jh><g(4=fZg~0A|7ka0y%rE8%Lm2Cj#n!!7U&xC`!vd*EJp0R9MnfydzqcmZC7 z*WnF#6W)Ti5keR-NPvXMAAv+jj3SW|sgNESkP$^ACvu@=R39}*El?ZO7Ii^gQ8wz0 z`k=nZi-w|6s1OyQ(daES9led-K{L=y^e&o(-b1s|95ffrM+?znv@lu$N6{!F2*Ie6pzD`updvyZ{v6H z3_KIh!SitqUW3=-^>_pR3~$0;;H`K&-husl@Lqff|AY_Yv-li7kFViB@pb$NKgNIK zCrkt*V#G`&qhs`pfw3~t49B<_Hxth!Fo{ePrYX~mY0jiFZ!%q&u1q(kJJW+nXZkVy znE}i|CXX4;`K z1Q|jv@1{R-9F!+lBytn#H%d-Uq|>Vai~@zgLE=br>S8jzhLQ?0DHv40g3$O`#Xg@`889j4$5D5KzP9rX zDa*_Ag(CPFOaK!>1+_m3_yGZYV5Ff7*O&leC(Vw7DPSsPO#}Y{(J{tk(&ApYyz8s zKX6#B7d0Ra3Ggb12lm(p2YP5^4A=_33=G!j8L*8S8LZKX!?w4B9f3ufLAV^|27iMmbe<}~zu*~plXM}y=rqNX0c0Tc z?t$_%cO+B*wgyU|6w08SbS2$LchaKszkpnGP!{Gp}!MTI%VCj0*23^n%<4JGQhxB~~WI<$wAkq{($4%%BHl%>*_x}TiguoJ*WsaA^H-H4T z1b)~WYzla_ddDErAnbG-*tS>q%w8E?t6)2j5`GMGI>3&BWf6J}>=2A2>}Y2?6Yx!v z6R6bc{7ow=#Lp)L_JCQyRRhyuPnZESNiOk`VI;2x_JY~4H|#@(lR`3{Od#GqU46q! zv-5ppy-IDc4vj9z550yKc(6Y83zwK~MY+Dd8Tom`L)=<3UYHv+GZ^N;Ar?54lvKgVa0)3UWfTmjIh+4Q7_q73HVFP|^=80Xb@bkY zv&mR8j%2-zCN{N98PW+SdOm!AQ1{GkWu-Yo3VdnB#X05Ga6V`bQfi0%0Dc(sdm))v z3DRkRUT;gKs%=qWNl}5XLw-T2uQ-^kTIpqQIdH95LAsdH`a0gGq{ONCR3>UFLsgG)X7`xguE4gRYzw#+(D+1|Ik#mHblYx zfl9gBzYp$zk^67RJH#6X)OSHA4#Mxr3^MDb6NliDIs+bs$H+|bF3C!dP36<;*ggr* z{Ez54D*7JDicKxzUP>lX{9l4sgW&lUUWQlTf5{v&m&_x98u%OhoszDR`D7C%ZKe6S z9#PQ--hq#4je&RJJ$N7f1s}kN@DX{REFd3{h2%rBh%8izG+}*h(ZN%PNtaET>6XAvXFEi!?MJNKIB$A}y&T-v256>Ca~m znUMK~zJ*kitXc+#Vu7m)sZk7BL29Z{9I}&@WGyYR=|#CEwNh@B7?jeY1Zree@WDeL z@M`MbCoY`{H9(Dn{D#ztHKa1g4|+rW35<+1`B4gL6;^LaY3qXQRQmAI{}^e9I) zQ0B)$sm}CaJ@F1m>(Jd-I<}~IWPV{@txMfdPvEMiLOoDA727~Q3BJ@CrltpE7L^qb z^>G~njD+o-nOsi2fF9+d;XxxlGz{gD&E#{kr5fc2%LMr% zR3yBCLP=KNT9=B^MB2!p5>$%H&=@opjYH*VJeokhB-_YWWINeGc9LCWH`%im#G*;a zj|ja_MpNkjG&ePXLOK@*ja2b;(g7@}Ggf%}os9t{Pi0M<*3WlN*&VkM3sP0B4Q! z+p)7Q^||jj0VlnlQ6D#aJ)C2ot`;r6%#?nwS356DCEh&*12JL5NT7u*$hBY%@8JVZRi zJe1NI8XYZ$9kX#CYCW_a;lAYQbIjrabSJt?nLLD)-PPvymeFSTs`Wd-QX3}0Q)p$wJf6(M2p)>6@KijFhhiQ^(s{{_X@%d#vjRI~ zI6*aj56=#4k4YUd7tgCxi}3q+32?2#3-AYcA^s3A!i#w*=b@5^EDtq2)bY@;3NOXW z@N&EYSK=xjns{j8A;-g59y)oLP0%O4#MGySl<_e27+PTLH{GMUwty3Bm=xv>rX|yghbcU4!@~|d?DAq6Giglw;Am}_woE%7zQMzmJZx3X zbYMC%op{)qhp9YF3)W^w;Eu-{*dIT^*^}w@I+bjuH`9lQZFxusYEK==ONdP!#0+_z z>`*3`@$s-D52=yPbZT0Mdv$tB!Pybujxr;Fgc->cY&w`Q0{Pzz?bJ*mQ#A0!PTel2 zG^d)9MuU`W`f*3!YExUxl+#sBLn>v;n0CxqW?U$+t~~5UW8-0W9`;zpjEB9MiA)9k z2_JVmIPF#l<)3WpdZiW$t{?I=7Aznz!Qm8m7$z5`dZisYS4Am=^ zlzWwm?wMVD<-Xjs;-SOy$M}kmFx5;=ugub%QXhdp1dJdCB!I@C1!zroRp34=}bGSKp9zB0sK&#^-yafA~(JHu+9>IN158=MVU(rLjU3d@P zhmYb1^gJz-o|M%vyO}f0Lje$Afj|%;Pzs_1ae_oaeL)LBM?pWq0Kp)^V8IYUu3(s8 zxL|~!K;Reff+>P&g6V>H1TzJ*1hWNm1pz^&V6$Mi;I?l3cnV9BRnF!CVUj3h%iMYM`T9i zMU0P_8L=W_Tf{FBCn8QooQXIW@gU-vNGM`OjYVmqwxaf;j-t+@E~0LtA)+$TRM7{b zO`^|5Ux>aGeI?oCvR!1qNN;3W8ksBgUMc$3PANe5iQRLqeED=gX zl1PbK(o)h!QXnalES9X0d?Ps~IW9RVIU_kIxgd>@YNUFpQEHZ2{ZdY9mo|_#m!?Qt zN?S`iNIOa2ly;SNmyVatldh9)l5UZ1m2Q)MD?KhfDLpMcD?Km0DE(D>MS4&Am-M0Z zvGj@bAL%n0lwp}tW|lRTb&=)Crpe~Y*2}iZ_R03kzLk9^`(F05?6~Zt?6mBx?7Zx; zoRfRx*>bPEK<*zUFO^rwXUJ#EYvilsYvk+XAImq$zmV^g@0RbCe=Yw;{*(NO{FwZ# z{Ji|4{15q`@*DD}3b8_>kSP?3W{UQTZi>E&{)&MLuVT2OP*I{NS4>tcR4iAlQGBFW zulPjqjpAFy&x&)33yMpM%ZmRhZYpjo?kesp9w;6up(*i zHB~iNwNj<3+Nj#8GE_cQp=zvZs_GrpOw}yaJk@;F0@XrQmFgqaX4O8`LDdP>Y1LWP z1(pAj>ayw~%di4g$ck7kYhX>Rg^gxyY-6?++m>z5c4RxV*=&DyAnRpw* zRc3)b;)9hU#YO7V0T&AD z>TT*n>YM5(nn;aQBiAT3tVW~JX$%^t#;r-vBx&kt>T4Qm8f%(rI%xW6iZlVuXPO^1 zPqk_-r;XLxwJvSEHc{J3+eO=5o372&_R{v&4%6mo{iWKm+H&ng?IbPH&eG1)&etx` zF4iv9F4tCSS7|qCw`#X(w`=!k_i6WQzttYsUe^Auy{5gcy`#OS{Y(2$7pc?h%sQ)% z)7f=Som-cnOV+j2wb8ZHbs@-%a07 zKT2Pue@kDYFVm0Jm+L3!EA)Q-JpFwA0{ue$BK;EmGW`mDmA*#5O20>cSbs(T$Pi(O zHZ(N!FytC07^WJg8KxWN7?v7p4C@U3O@_^eErwl&-G;q}?+rf~4jE1uP8v=deluJ% zTsPb@+%eoUJT+pYz!+f^8zn}A(PE4?+KdjP%NTD=G`2Q&GWIg|GY&8gG7dHRjCsa< z<5(jx&N9w3&NnVFE;cSTE;m*hHyd}DqD(GROH*r8nyIa+y{V(Av#E>U)Xmhx)YCM~ zG~6`8RA4GH6`RUT<4hAw6(+xlH!U=MZu-e|)^sn*5!EazGip@S)Tp^p3!@fAEs0td zwK8gT)Y_!$f6mv^+Yjc{ptvTJCVa_sVn`fFAnirXu zn3tK4nJ=1uHD57bwfLhfE=#;6(c-ZTwT!luSjsHpEaNQ`EekCxEo&_6EbA?wSTS-!CxupG3Uu$;D>wOp`VvRt;@w%oJ)WqD-z+w#;Zwo0rrtHL_Ry41SHy3YEs zb%XU&>u1&-)?L;;)~~JKS`S)(us)4;MrTJ)i{2FdWAy3hbN=WH(Z5DtiM|?rEBb!) zgXqW6PdE`L;}o2V({TpQ#F@ENt}~a-_2&k1UM`m##^rM(xl-;u?gMTSx0GAXeada) zc5u77z1)885O;>V$X({Ha({9+xjWoF?uiZARJH_LBU_fOzionTu5FoZxow55%JzwE zyUoALw%4}bcEI+%?U3z^?Y!-h?TYO;+cnz_+b!Eu+rKd&2FJV=Gbx6|OpcirD~&bA zM#WlUx!9W6jj@|zKabrS*D0=7T<^HPaRcHG#+`^e6?Z1?yuGtM+wQgJ*oWGE_B{J& zdx?FFeVl!~eWHDueYSmxeWiW1eXac?`+C29i~URccKc5IZu?&Q_x7Ldm+aT<*X=j$ zx9xZBPwf9XpaVMujtGa+VRASf$&Ln&Mvf+qW{xyRJ4Z)HXGd2@cSmo>U`M`VjKlBX z9a9|B9Mc_h90A7y$3n+q$5O{C$ES`j9p5;9avX6SbNu2s;kf9y?6~Uq-Eqy~zwY?U ziJS^2>(n|8&M2qFnc!^U?C9+3?BUFC_ICDj4s?2*CC-_yCax4$Csz+whO3vWkIU;C z;_|tMyGFQ{y0*HGxK6t+yRN$aa9wxZa@}$L>lV00Zi!p&*18SuD7V$kxjVbZx~ttE zyEnKuyZ5*cxW9KFav$-#PrA>z&$}C_c5T6v^ zB)(;QhxqP^8xl7rZc99n_*3HX#LJ1d6YnKHNPL|5H1SyyN>U`TNtz^mk}1iYWKH6d z+9!=jnxC{Y>D#2kNhgyoC0$9nk#s-lu}A8Wdty8Z9*-y4)4 Date: Thu, 31 Oct 2013 18:23:44 -0700 Subject: [PATCH 20/20] Rationalize response status code check. Ensure that all bona fide 2xx responses are treated in the same way that "200 OK" is. Previously, was explicitly checking for response code 200 (ClientResponse.Status.OK). Now, checks the family of the response to make sure it is successful (Family.SUCCESSFUL). This enables us to POST to resources that return 201 created - without having to handle a checked ApiException. --- src/main/resources/Java/apiInvoker.mustache | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/resources/Java/apiInvoker.mustache b/src/main/resources/Java/apiInvoker.mustache index 6dbd0213e19..30dc876a809 100644 --- a/src/main/resources/Java/apiInvoker.mustache +++ b/src/main/resources/Java/apiInvoker.mustache @@ -12,6 +12,7 @@ import com.sun.jersey.api.client.config.DefaultClientConfig; import com.sun.jersey.api.client.filter.LoggingFilter; import com.sun.jersey.api.client.WebResource.Builder; +import javax.ws.rs.core.Response.Status.Family; import javax.ws.rs.core.MediaType; import java.util.Map; @@ -123,7 +124,7 @@ public class ApiInvoker { else { throw new ApiException(500, "unknown method type " + method); } - if(response.getClientResponseStatus() == ClientResponse.Status.OK) { + if(response.getClientResponseStatus().getFamily() == Family.SUCCESSFUL) { return (String) response.getEntity(String.class); } else {