From ae8a123484468632375f88cf1ea53c9a957c44f8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 29 Jan 2017 12:15:39 +0800 Subject: [PATCH] [WIP][Scala] Finch generator (#3905) * Feature/objc tasks 2.3.0 (#3522) * change api and ApiClient to return cancellable NSURLSessionTasks instead of NSNumber * define a configuration protocol for custom configurations, which can be passed to api clients instead of a global configuration, provide a default implementation with a singleton option * integrate a workaround for a current JSONModel concurrency bug * update to new ISO8601 pod * add missing call to super * integrate new templates into codegen * updates documentation templates * updates petstore objc generated code * fixes objc client tests * [ObjC] Add version define and share default headers of each client * add finch generator and resource * update license, add errros * Fix problem with multitheard api client * fix some errors for finch * [finch] Remove license header * [finch] Remove finatra stuff, fix a few issues * WIP: Finch server generator * [finch] WIP: server generator impl This puts parameters (input/output) in the right format. Currently, this is done in the generator class using vendorExtensions, but should be refactored to imported templates to clean up. Previous commits of the server generator output to appropriate models/api directories. I've made no changes to this logic, but code currently generates to the root scala package directory. This will need to be fixed. There's also an issue with circe's and Option[Date] in the Order type. This issue will need to be resolved. As well, there's some unused imports to clean up. Initial implementation lacks support for custom imports, type mappings, etc. * [finch] Update api/model package and imports * [finch] Explicit import/type mappings * [finch] Regenerate example --- bin/finch-petstore-server.sh | 31 ++ .../codegen/languages/FinchServerCodegen.java | 320 +++++++++++ .../codegen/languages/ObjcClientCodegen.java | 11 +- .../languages/ScalatraServerCodegen.java | 1 - .../services/io.swagger.codegen.CodegenConfig | 1 + .../resources/finch/DataAccessor.mustache | 27 + .../src/main/resources/finch/JsonUtil.scala | 12 + .../src/main/resources/finch/README.mustache | 10 + .../src/main/resources/finch/Server.mustache | 39 ++ .../src/main/resources/finch/api.mustache | 74 +++ .../main/resources/finch/bodyParam.mustache | 1 + .../finch/bodyParamOperation.mustache | 3 + .../src/main/resources/finch/build.sbt | 61 ++ .../main/resources/finch/endpoint.mustache | 50 ++ .../src/main/resources/finch/errors.mustache | 27 + .../main/resources/finch/formParam.mustache | 1 + .../finch/formParamMustache.mustache | 3 + .../main/resources/finch/headerParam.mustache | 1 + .../finch/headerParamOperation.mustache | 3 + .../src/main/resources/finch/model.mustache | 30 + .../main/resources/finch/pathParam.mustache | 1 + .../resources/finch/project/build.properties | 1 + .../main/resources/finch/project/plugins.sbt | 7 + .../main/resources/finch/queryParam.mustache | 1 + .../finch/queryParamOperation.mustache | 13 + .../src/main/resources/finch/sbt | 525 ++++++++++++++++++ .../resources/objc/ApiClient-body.mustache | 400 +++++-------- .../resources/objc/ApiClient-header.mustache | 173 ++---- .../objc/BasicAuthTokenProvider-body.mustache | 19 + .../BasicAuthTokenProvider-header.mustache | 14 + .../objc/Configuration-protocol.mustache | 78 +++ ...che => DefaultConfiguration-body.mustache} | 44 +- ...e => DefaultConfiguration-header.mustache} | 11 +- .../objc/JSONResponseSerializer-body.mustache | 39 -- .../JSONResponseSerializer-header.mustache | 8 - ...JSONValueTransformer+ISO8601-body.mustache | 1 + ...ONValueTransformer+ISO8601-header.mustache | 1 - .../main/resources/objc/Logger-body.mustache | 3 +- .../main/resources/objc/Object-body.mustache | 29 + .../objc/QueryParamCollection-body.mustache | 12 +- .../src/main/resources/objc/README.mustache | 4 +- .../objc/ResponseDeserializer-body.mustache | 42 +- .../resources/objc/Sanitizer-body.mustache | 10 +- .../resources/objc/Sanitizer-header.mustache | 2 + .../src/main/resources/objc/api-body.mustache | 58 +- .../main/resources/objc/api-header.mustache | 21 +- .../main/resources/objc/api-protocol.mustache | 12 +- .../src/main/resources/objc/api_doc.mustache | 4 +- .../src/main/resources/objc/podspec.mustache | 10 +- .../src/main/resources/scalatra/build.sbt | 26 +- .../client/petstore/objc/core-data/README.md | 21 +- .../objc/core-data/SwaggerClient.podspec | 6 +- .../core-data/SwaggerClient/Api/SWGPetApi.h | 64 ++- .../core-data/SwaggerClient/Api/SWGPetApi.m | 146 ++--- .../core-data/SwaggerClient/Api/SWGStoreApi.h | 36 +- .../core-data/SwaggerClient/Api/SWGStoreApi.m | 86 +-- .../core-data/SwaggerClient/Api/SWGUserApi.h | 61 +- .../core-data/SwaggerClient/Api/SWGUserApi.m | 130 ++--- .../Core/JSONValueTransformer+ISO8601.h | 1 - .../Core/JSONValueTransformer+ISO8601.m | 1 + .../core-data/SwaggerClient/Core/SWGApi.h | 12 +- .../SwaggerClient/Core/SWGApiClient.h | 190 ++----- .../SwaggerClient/Core/SWGApiClient.m | 400 +++++-------- .../Core/SWGBasicAuthTokenProvider.h | 14 + .../Core/SWGBasicAuthTokenProvider.m | 19 + .../SwaggerClient/Core/SWGConfiguration.h | 135 ++--- .../Core/SWGDefaultConfiguration.h | 177 ++++++ ...figuration.m => SWGDefaultConfiguration.m} | 58 +- .../core-data/SwaggerClient/Core/SWGLogger.m | 3 +- .../core-data/SwaggerClient/Core/SWGObject.m | 29 + .../Core/SWGQueryParamCollection.m | 12 +- .../Core/SWGResponseDeserializer.m | 42 +- .../SwaggerClient/Core/SWGSanitizer.h | 2 + .../SwaggerClient/Core/SWGSanitizer.m | 10 +- .../SwaggerClient.xcodeproj/project.pbxproj | 75 ++- .../xcshareddata/xcschemes/All Tests.xcscheme | 55 +- .../xcschemes/SwaggerClient-Example.xcscheme | 13 +- .../SwaggerClient/SWGViewController.m | 4 +- .../SwaggerClient/SwaggerClient-Info.plist | 2 +- .../SwaggerClientTests/Tests/Tests-Info.plist | 2 +- .../client/petstore/objc/default/README.md | 21 +- .../objc/default/SwaggerClient.podspec | 6 +- .../default/SwaggerClient/Api/SWGPetApi.h | 64 ++- .../default/SwaggerClient/Api/SWGPetApi.m | 146 ++--- .../default/SwaggerClient/Api/SWGStoreApi.h | 36 +- .../default/SwaggerClient/Api/SWGStoreApi.m | 86 +-- .../default/SwaggerClient/Api/SWGUserApi.h | 61 +- .../default/SwaggerClient/Api/SWGUserApi.m | 130 ++--- .../Core/JSONValueTransformer+ISO8601.h | 1 - .../Core/JSONValueTransformer+ISO8601.m | 1 + .../objc/default/SwaggerClient/Core/SWGApi.h | 12 +- .../default/SwaggerClient/Core/SWGApiClient.h | 190 ++----- .../default/SwaggerClient/Core/SWGApiClient.m | 400 +++++-------- .../Core/SWGBasicAuthTokenProvider.h | 14 + .../Core/SWGBasicAuthTokenProvider.m | 19 + .../SwaggerClient/Core/SWGConfiguration.h | 135 ++--- .../Core/SWGDefaultConfiguration.h | 177 ++++++ ...figuration.m => SWGDefaultConfiguration.m} | 58 +- .../Core/SWGJSONResponseSerializer.m | 39 -- .../default/SwaggerClient/Core/SWGLogger.m | 3 +- .../default/SwaggerClient/Core/SWGObject.m | 29 + .../Core/SWGQueryParamCollection.m | 12 +- .../Core/SWGResponseDeserializer.m | 42 +- .../default/SwaggerClient/Core/SWGSanitizer.h | 2 + .../default/SwaggerClient/Core/SWGSanitizer.m | 10 +- .../SwaggerClient.xcodeproj/project.pbxproj | 75 ++- .../xcshareddata/xcschemes/All Tests.xcscheme | 55 +- .../xcschemes/SwaggerClient-Example.xcscheme | 13 +- .../SwaggerClient/SWGViewController.m | 4 +- .../SwaggerClient/SwaggerClient-Info.plist | 2 +- .../Tests/DeserializationTest.m | 12 + .../Tests/SWGApiClientTest.m | 7 +- .../SwaggerClientTests/Tests/Tests-Info.plist | 2 +- .../SwaggerClientTests/Tests/UserApiTest.m | 9 +- .../petstore/objc/default/docs/SWGPetApi.md | 40 +- .../petstore/objc/default/docs/SWGStoreApi.md | 10 +- .../petstore/objc/default/docs/SWGUserApi.md | 16 +- .../petstore/finch/.swagger-codegen-ignore | 23 + samples/server/petstore/finch/LICENSE | 201 +++++++ samples/server/petstore/finch/README.md | 10 + samples/server/petstore/finch/build.sbt | 61 ++ .../petstore/finch/project/build.properties | 1 + .../server/petstore/finch/project/plugins.sbt | 7 + samples/server/petstore/finch/sbt | 525 ++++++++++++++++++ .../finch/src/main/scala/DataAccessor.scala | 133 +++++ .../finch/src/main/scala/Server.scala | 36 ++ .../finch/src/main/scala/endpoint.scala | 48 ++ .../finch/src/main/scala/errors.scala | 27 + .../io/swagger/petstore/apis/PetApi.scala | 148 +++++ .../io/swagger/petstore/apis/StoreApi.scala | 95 ++++ .../io/swagger/petstore/apis/UserApi.scala | 149 +++++ .../swagger/petstore/models/ApiResponse.scala | 27 + .../io/swagger/petstore/models/Category.scala | 25 + .../io/swagger/petstore/models/Order.scala | 34 ++ .../io/swagger/petstore/models/Pet.scala | 36 ++ .../io/swagger/petstore/models/Tag.scala | 25 + .../io/swagger/petstore/models/User.scala | 37 ++ .../scala/com/wordnik/client/api/PetApi.scala | 8 +- .../com/wordnik/client/api/StoreApi.scala | 4 +- .../com/wordnik/client/api/UserApi.scala | 3 - 140 files changed, 5262 insertions(+), 2421 deletions(-) create mode 100755 bin/finch-petstore-server.sh create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala create mode 100644 modules/swagger-codegen/src/main/resources/finch/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/Server.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/build.sbt create mode 100644 modules/swagger-codegen/src/main/resources/finch/endpoint.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/errors.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/formParam.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/headerParam.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/pathParam.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/project/build.properties create mode 100644 modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt create mode 100644 modules/swagger-codegen/src/main/resources/finch/queryParam.mustache create mode 100644 modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache create mode 100755 modules/swagger-codegen/src/main/resources/finch/sbt create mode 100644 modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache rename modules/swagger-codegen/src/main/resources/objc/{Configuration-body.mustache => DefaultConfiguration-body.mustache} (73%) rename modules/swagger-codegen/src/main/resources/objc/{Configuration-header.mustache => DefaultConfiguration-header.mustache} (93%) delete mode 100644 modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache create mode 100644 samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.h create mode 100644 samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.m create mode 100644 samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.h rename samples/client/petstore/objc/core-data/SwaggerClient/Core/{SWGConfiguration.m => SWGDefaultConfiguration.m} (72%) create mode 100644 samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.h create mode 100644 samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.m create mode 100644 samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.h rename samples/client/petstore/objc/default/SwaggerClient/Core/{SWGConfiguration.m => SWGDefaultConfiguration.m} (72%) delete mode 100644 samples/client/petstore/objc/default/SwaggerClient/Core/SWGJSONResponseSerializer.m create mode 100644 samples/server/petstore/finch/.swagger-codegen-ignore create mode 100644 samples/server/petstore/finch/LICENSE create mode 100644 samples/server/petstore/finch/README.md create mode 100644 samples/server/petstore/finch/build.sbt create mode 100644 samples/server/petstore/finch/project/build.properties create mode 100644 samples/server/petstore/finch/project/plugins.sbt create mode 100644 samples/server/petstore/finch/sbt create mode 100644 samples/server/petstore/finch/src/main/scala/DataAccessor.scala create mode 100644 samples/server/petstore/finch/src/main/scala/Server.scala create mode 100644 samples/server/petstore/finch/src/main/scala/endpoint.scala create mode 100644 samples/server/petstore/finch/src/main/scala/errors.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala create mode 100644 samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala diff --git a/bin/finch-petstore-server.sh b/bin/finch-petstore-server.sh new file mode 100755 index 00000000000..9cf4eeb740d --- /dev/null +++ b/bin/finch-petstore-server.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +fi + +# if you've executed sbt assembly previously it will use that instead. +export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" +ags="generate $@ -t modules/swagger-codegen/src/main/resources/finch -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l finch -o samples/server/petstore/finch" + +java $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java new file mode 100644 index 00000000000..4a3eed3a01b --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FinchServerCodegen.java @@ -0,0 +1,320 @@ +package io.swagger.codegen.languages; + +import com.google.common.base.Strings; +import io.swagger.codegen.*; +import io.swagger.models.Model; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; + +import java.io.File; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; + +public class FinchServerCodegen extends DefaultCodegen implements CodegenConfig { + protected String invokerPackage = "io.swagger.petstore.client"; + protected String groupId = "io.swagger"; + protected String artifactId = "finch-server"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String packageName = "io.swagger.petstore"; + + public FinchServerCodegen() { + super(); + outputFolder = "generated-code/finch"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + embeddedTemplateDir = templateDir = "finch"; + + apiPackage = packageName + ".apis"; + modelPackage = packageName + ".models"; + + setReservedWordsLowerCase( + Arrays.asList( + // Scala + "abstract", "case", "catch", "class", "def", + "do", "else", "extends", "false", "final", + "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", + "object", "override", "package", "private", "protected", + "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", + "var", "while", "with", "yield", + // Scala-interop languages keywords + "abstract", "continue", "switch", "assert", + "default", "synchronized", "goto", + "break", "double", "implements", "byte", + "public", "throws", "enum", "instanceof", "transient", + "int", "short", "char", "interface", "static", + "void", "finally", "long", "strictfp", "volatile", "const", "float", + "native") + ); + + defaultIncludes = new HashSet( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + typeMapping = new HashMap(); + typeMapping.put("string", "String"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("integer", "Int"); + typeMapping.put("float", "Float"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("number", "BigDecimal"); + typeMapping.put("date-time", "LocalDateTime"); + typeMapping.put("date", "LocalDateTime"); + typeMapping.put("file", "File"); + typeMapping.put("array", "Seq"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Map"); + typeMapping.put("object", "Object"); + typeMapping.put("binary", "Array[Byte]"); + typeMapping.put("Date", "LocalDateTime"); + typeMapping.put("DateTime", "LocalDateTime"); + + additionalProperties.put("modelPackage", modelPackage()); + additionalProperties.put("apiPackage", apiPackage()); + additionalProperties.put("appName", "Swagger Sample"); + additionalProperties.put("appDescription", "A sample swagger server"); + additionalProperties.put("infoUrl", "http://swagger.io"); + additionalProperties.put("infoEmail", "apiteam@swagger.io"); + additionalProperties.put("licenseInfo", "Apache 2.0"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + } + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); + supportingFiles.add(new SupportingFile("Server.mustache", sourceFolder, "Server.scala")); + supportingFiles.add(new SupportingFile("DataAccessor.mustache", sourceFolder, "DataAccessor.scala")); + + supportingFiles.add(new SupportingFile("project/build.properties", "project", "build.properties")); + supportingFiles.add(new SupportingFile("project/plugins.sbt", "project", "plugins.sbt")); + supportingFiles.add(new SupportingFile("sbt", "", "sbt")); + + supportingFiles.add(new SupportingFile("endpoint.mustache", sourceFolder, "endpoint.scala")); + supportingFiles.add(new SupportingFile("errors.mustache", sourceFolder, "errors.scala")); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "Boolean", + "Double", + "Int", + "Integer", + "Long", + "Float", + "Any", + "AnyVal", + "AnyRef", + "Object") + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + + importMapping = new HashMap(); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "scala.collection.immutable.Map"); + importMapping.put("HashMap", "scala.collection.immutable.HashMap"); + importMapping.put("Seq", "scala.collection.immutable.Seq"); + importMapping.put("ArrayBuffer", "scala.collection.mutable.ArrayBuffer"); + importMapping.put("DateTime", "java.time.LocalDateTime"); + importMapping.put("LocalDateTime", "java.time.LocalDateTime"); + importMapping.put("LocalDate", "java.time.LocalDate"); + importMapping.put("LocalTime", "java.time.LocalTime"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Finch package name (e.g. io.swagger.petstore).") + .defaultValue(this.packageName)); + cliOptions.add(new CliOption(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC)); + cliOptions.add(new CliOption(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC)); + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "finch"; + } + + @Override + public String getHelp() { + return "Generates a Scala server application with Finch."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); + } + + /** + * Convert Swagger Model object to Codegen Model object + * + * @param name the name of the model + * @param model Swagger Model object + * @param allDefinitions a map of all Swagger models from the spec + * @return Codegen Model object + */ + @Override + public CodegenModel fromModel(String name, Model model, Map allDefinitions) { + CodegenModel codegenModel = super.fromModel(name, model, allDefinitions); + return codegenModel; + } + + @Override + public Map postProcessOperations(Map objs) { + Map operations = (Map) objs.get("operations"); + List operationList = (List) operations.get("operation"); + for (CodegenOperation op : operationList) { + op.httpMethod = op.httpMethod.toLowerCase(); + + String path = new String(op.path); + // remove first / + if (path.startsWith("/")) { + path = path.substring(1); + } + // remove last / + if (path.endsWith("/")) { + path = path.substring(0, path.length()-1); + } + + String[] items = path.split("/", -1); + String scalaPath = ""; + int pathParamIndex = 0; + + for (int i = 0; i < items.length; ++i) { + if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} + // find the datatype of the parameter + final CodegenParameter cp = op.pathParams.get(pathParamIndex); + + // TODO: Handle non-primitives… + scalaPath = scalaPath + cp.dataType.toLowerCase(); + + pathParamIndex++; + } else { + scalaPath = scalaPath + "\"" + items[i] + "\""; + } + + if (i != items.length -1) { + scalaPath = scalaPath + " :: "; + } + } + + for (CodegenParameter p : op.allParams) { + // TODO: This hacky, should be converted to mappings if possible to keep it clean. + // This could also be done using template imports + if(Boolean.TRUE.equals(p.isPrimitiveType)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType.toLowerCase()); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } else if(Boolean.TRUE.equals(p.isBodyParam)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "jsonBody["+ p.dataType + "]"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } else if(Boolean.TRUE.equals(p.isContainer) || Boolean.TRUE.equals(p.isListContainer)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "params(\""+ p.paramName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType.replaceAll("^[^\\[]+", "Seq")); + } else if(Boolean.TRUE.equals(p.isFile)) { + p.vendorExtensions.put("x-codegen-normalized-path-type", "fileUpload(\""+ p.paramName + "\")"); + p.vendorExtensions.put("x-codegen-normalized-input-type", "FileUpload"); + } else { + p.vendorExtensions.put("x-codegen-normalized-path-type", p.dataType); + p.vendorExtensions.put("x-codegen-normalized-input-type", p.dataType); + } + } + + op.vendorExtensions.put("x-codegen-path", scalaPath); + } + return objs; + } + + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = swaggerType; + } + return toModelName(type); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + +} diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java index 3da8c5b074b..4598113c370 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ObjcClientCodegen.java @@ -255,10 +255,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m")); supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h")); supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m")); - supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h")); supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h")); - supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m")); supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h")); supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m")); @@ -269,8 +267,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m")); supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m")); - supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m")); + supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h")); + supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m")); supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h")); supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java index cab432e5d17..065dd8409b5 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/ScalatraServerCodegen.java @@ -65,7 +65,6 @@ public class ScalatraServerCodegen extends AbstractScalaCodegen implements Codeg // mapped to String as a workaround typeMapping.put("binary", "String"); - additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appName", "Swagger Sample"); additionalProperties.put("appDescription", "A sample swagger server"); additionalProperties.put("infoUrl", "http://swagger.io"); diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 8da47e907a3..d283d5740ec 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -33,6 +33,7 @@ io.swagger.codegen.languages.Qt5CPPGenerator io.swagger.codegen.languages.RubyClientCodegen io.swagger.codegen.languages.ScalaClientCodegen io.swagger.codegen.languages.ScalatraServerCodegen +io.swagger.codegen.languages.FinchServerCodegen io.swagger.codegen.languages.SilexServerCodegen io.swagger.codegen.languages.SinatraServerCodegen io.swagger.codegen.languages.Rails5ServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache b/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache new file mode 100644 index 00000000000..e9700efc726 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/DataAccessor.mustache @@ -0,0 +1,27 @@ +package {{packageName}} + +// TODO: properly handle custom imports +import java.io._ +import java.util.Date + +import {{modelPackage}}._ + +trait DataAccessor { + // TODO: apiInfo -> apis -> operations = ??? + // NOTE: ??? throws a not implemented exception + +{{#apiInfo}} + {{#apis}} +{{#operations}} + {{#operation}} + /** + * {{{description}}} + * @return A {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} + */ + def {{baseName}}_{{operationId}}({{#allParams}}{{paramName}}: {{{dataType}}}{{^-last}}, {{/-last}}{{/allParams}}): {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} = ??? + + {{/operation}} +{{/operations}} + {{/apis}} +{{/apiInfo}} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala b/modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala new file mode 100644 index 00000000000..691a82f563b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/JsonUtil.scala @@ -0,0 +1,12 @@ +package json + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ + +object JsonUtil { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/README.mustache b/modules/swagger-codegen/src/main/resources/finch/README.mustache new file mode 100644 index 00000000000..327870827fd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/README.mustache @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled scalatra server. + +This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/Server.mustache b/modules/swagger-codegen/src/main/resources/finch/Server.mustache new file mode 100644 index 00000000000..97f0fb79a09 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/Server.mustache @@ -0,0 +1,39 @@ +package {{packageName}} + +import io.finch._ +import io.finch.circe._ +import io.circe.{Decoder, ObjectEncoder} +import io.circe.generic.auto._ +import io.circe.generic.semiauto +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import com.twitter.finagle.Http +import com.twitter.finagle.util.LoadService +import com.twitter.util.{Await, Future} + +{{#imports}}import {{import}} +{{/imports}} + +class Server { + + // Loads implementation defined in resources/META-INF/services/{{packageName}}.DataAccessor + val db = LoadService[DataAccessor]() match { + case accessor :: _ => accessor + case _ => new DataAccessor { } + } + + val service = endpoint.makeService(db) + + val server = Http.serve(":8080", service) //creates service + + def close(): Future[Unit] = { + Await.ready(server.close()) + } +} + +/** + * Launches the PetstoreAPI service when the system is ready. + */ +object Server extends Server with App { + Await.ready(server) +} diff --git a/modules/swagger-codegen/src/main/resources/finch/api.mustache b/modules/swagger-codegen/src/main/resources/finch/api.mustache new file mode 100644 index 00000000000..8758174f6d3 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/api.mustache @@ -0,0 +1,74 @@ +package {{apiPackage}} + +import java.io._ +import java.util.Date +import {{packageName}}._ +import {{modelPackage}}._ +{{#imports}}import {{import}} +{{/imports}} +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.{FileUpload, InMemoryFileUpload, OnDiskFileUpload} +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object {{classname}} { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + {{#operations}} + {{#operation}} + {{{operationId}}}(da){{^-last}} :+:{{/-last}} + {{/operation}} + {{/operations}} + + {{#operations}} + {{#operation}} + /** + * {{{description}}} + * @return And endpoint representing a {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} + */ + private def {{operationId}}(da: DataAccessor): Endpoint[{{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}] = + {{httpMethod}}({{{vendorExtensions.x-codegen-path}}} {{#allParams}}{{^isPathParam}} :: {{& vendorExtensions.x-codegen-normalized-path-type}}{{/isPathParam}}{{/allParams}}) { {{#hasParams}}({{#allParams}}{{paramName}}: {{{vendorExtensions.x-codegen-normalized-input-type}}}{{^-last}}, {{/-last}}{{/allParams}}) => {{/hasParams}} + {{#returnType}} + Ok(da.{{baseName}}_{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}})) + {{/returnType}} + {{^returnType}} + da.{{baseName}}_{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) + NoContent[Unit] + {{/returnType}} + } handle { + case e: Exception => BadRequest(e) + } + + {{/operation}} + {{/operations}} + + implicit private def fileUploadToFile(fileUpload: FileUpload) : File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmp{{classname}}", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache b/modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache new file mode 100644 index 00000000000..07a90aa23cb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/bodyParam.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache b/modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache new file mode 100644 index 00000000000..cfb2bf49d23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/bodyParamOperation.mustache @@ -0,0 +1,3 @@ + {{#isBodyParam}} + val {{paramName}} = parsedBody.extract[{{dataType}}] + {{/isBodyParam}} diff --git a/modules/swagger-codegen/src/main/resources/finch/build.sbt b/modules/swagger-codegen/src/main/resources/finch/build.sbt new file mode 100644 index 00000000000..b58544b46bd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/build.sbt @@ -0,0 +1,61 @@ +scalariformSettings + +organization := "io.swagger" + +name := "finch-sample" + +version := "0.1.0-SNAPSHOT" + +scalaVersion := "2.11.8" + +resolvers += Resolver.sonatypeRepo("snapshots") + +resolvers += "TM" at "http://maven.twttr.com" + +resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" + +resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" + +resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" + +Defaults.itSettings + +scalacOptions ++= Seq( + "-deprecation", + "-encoding", "UTF-8", + "-feature", + "-language:existentials", + "-language:higherKinds", + "-language:implicitConversions", + "-unchecked", + "-Yno-adapted-args", + "-Ywarn-dead-code", + "-Ywarn-numeric-widen", + "-Xfuture", + "-Xlint", +// "-Ywarn-unused-import", + "-language:postfixOps" +) + +lazy val `it-config-sbt-project` = project.in(file(".")).configs(IntegrationTest) + +libraryDependencies ++= Seq( + "com.github.finagle" %% "finch-core" % "0.12.0", + "com.github.finagle" %% "finch-circe" % "0.12.0", + "io.circe" %% "circe-generic" % "0.7.0", + "io.circe" %% "circe-java8" % "0.7.0", + "com.twitter" %% "util-core" % "6.40.0", + "com.github.finagle" %% "finch-test" % "0.12.0" % "test", + "org.scalacheck" %% "scalacheck" % "1.13.4" % "test", + "org.scalatest" %% "scalatest" % "3.0.0" % "test" +) + +assemblyMergeStrategy in assembly := { + case "application.conf" => MergeStrategy.concat + case "about.html" => MergeStrategy.discard + case x => + val oldStrategy = (assemblyMergeStrategy in assembly).value + oldStrategy(x) +} + +addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) diff --git a/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache b/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache new file mode 100644 index 00000000000..bb66defbe4f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/endpoint.mustache @@ -0,0 +1,50 @@ +package {{packageName}} + +import com.twitter.finagle.Service +import com.twitter.finagle.http.{Request, Response} +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import io.finch._, items._ +import io.circe.{Encoder, Json} +import io.finch.circe._ +import io.circe.generic.semiauto._ + +import {{apiPackage}}._ + +/** + * Provides the paths and endpoints for all the API's public service methods. + */ +object endpoint { + + def errorToJson(e: Exception): Json = e match { + case Error.NotPresent(_) => + Json.obj("error" -> Json.fromString("something_not_present")) + case Error.NotParsed(_, _, _) => + Json.obj("error" -> Json.fromString("something_not_parsed")) + case Error.NotValid(_, _) => + Json.obj("error" -> Json.fromString("something_not_valid")) + case error: PetstoreError => + Json.obj("error" -> Json.fromString(error.message)) + } + + implicit val ee: Encoder[Exception] = Encoder.instance { + case e: Error => errorToJson(e) + case Errors(nel) => Json.arr(nel.toList.map(errorToJson): _*) + } + + /** + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(da: DataAccessor): Service[Request, Response] = ( + {{#apiInfo}} + {{#apis}} + {{classname}}.endpoints(da) {{^-last}} :+:{{/-last}} + {{/apis}} + {{/apiInfo}} + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/errors.mustache b/modules/swagger-codegen/src/main/resources/finch/errors.mustache new file mode 100644 index 00000000000..eb90b48052a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/errors.mustache @@ -0,0 +1,27 @@ +package {{packageName}} + +/** + * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. + */ +abstract class PetstoreError(msg: String) extends Exception(msg) { + def message: String +} + +/** + * Thrown when the object given is invalid + * @param message An error message + */ +case class InvalidInput(message: String) extends PetstoreError(message) + +/** + * Thrown when the given object is missing a unique ID. + * @param message An error message + */ +case class MissingIdentifier(message: String) extends PetstoreError(message) + +/** + * Thrown when the given record does not exist in the database. + * @param message An error message + */ +case class RecordNotFound(message: String) extends PetstoreError(message) + diff --git a/modules/swagger-codegen/src/main/resources/finch/formParam.mustache b/modules/swagger-codegen/src/main/resources/finch/formParam.mustache new file mode 100644 index 00000000000..1afcf12ccc6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/formParam.mustache @@ -0,0 +1 @@ +{{#isFormParam}}formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache b/modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache new file mode 100644 index 00000000000..29c571ee2ef --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/formParamMustache.mustache @@ -0,0 +1,3 @@ + {{#isFormParam}} + val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}") + {{/isFormParam}} diff --git a/modules/swagger-codegen/src/main/resources/finch/headerParam.mustache b/modules/swagger-codegen/src/main/resources/finch/headerParam.mustache new file mode 100644 index 00000000000..798bb0fe6d5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/headerParam.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache b/modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache new file mode 100644 index 00000000000..7f8f5286392 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/headerParamOperation.mustache @@ -0,0 +1,3 @@ + {{#isHeaderParam}} + val {{paramName}} = request.getHeader("{{paramName}}") + {{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/model.mustache b/modules/swagger-codegen/src/main/resources/finch/model.mustache new file mode 100644 index 00000000000..dbb1489b3af --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/model.mustache @@ -0,0 +1,30 @@ +package {{modelPackage}} + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import {{packageName}}._ +{{#imports}}import {{import}} +{{/imports}} + +{{#models}} +{{#model}} +/** + * {{{description}}} +{{#vars}} + * @param {{name}} {{{description}}} +{{/vars}} + */ +case class {{classname}}({{#vars}}{{name}}: {{^required}}Option[{{{datatype}}}]{{/required}}{{#required}}{{{datatype}}}{{/required}}{{^-last}},{{/-last}} + {{/vars}}) + +object {{classname}} { + /** + * Creates the codec for converting {{classname}} from and to JSON. + */ + implicit val decoder: Decoder[{{classname}}] = deriveDecoder + implicit val encoder: ObjectEncoder[{{classname}}] = deriveEncoder +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/finch/pathParam.mustache b/modules/swagger-codegen/src/main/resources/finch/pathParam.mustache new file mode 100644 index 00000000000..ae72aa8ec74 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/pathParam.mustache @@ -0,0 +1 @@ +{{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/project/build.properties b/modules/swagger-codegen/src/main/resources/finch/project/build.properties new file mode 100644 index 00000000000..27e88aa115a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.13 diff --git a/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt b/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt new file mode 100644 index 00000000000..761afa5688e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/project/plugins.sbt @@ -0,0 +1,7 @@ +resolvers += Resolver.typesafeRepo("releases") + +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") + +// addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") + +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0") diff --git a/modules/swagger-codegen/src/main/resources/finch/queryParam.mustache b/modules/swagger-codegen/src/main/resources/finch/queryParam.mustache new file mode 100644 index 00000000000..79af702d0f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/queryParam.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache b/modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache new file mode 100644 index 00000000000..832bbed2030 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/queryParamOperation.mustache @@ -0,0 +1,13 @@ + {{#isQueryParam}} + {{#collectionFormat}}val {{paramName}}String = params.getAs[String]("{{paramName}}") + val {{paramName}} = if("{{collectionFormat}}".equals("default")) { + {{paramName}}String match { + case Some(str) => str.split(",") + case None => List() + } + } + else + List() + {{/collectionFormat}} + {{^collectionFormat}}val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}"){{/collectionFormat}} + {{/isQueryParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/finch/sbt b/modules/swagger-codegen/src/main/resources/finch/sbt new file mode 100755 index 00000000000..08e58821219 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/finch/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat < configuration; + +@property (nonatomic, strong) NSArray* downloadTaskResponseTypes; @end @implementation {{classPrefix}}ApiClient +#pragma mark - Singleton Methods + ++ (instancetype) sharedClient { + static {{classPrefix}}ApiClient *sharedClient = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedClient = [[self alloc] init]; + }); + return sharedClient; +} + +#pragma mark - Initialize Methods + - (instancetype)init { - NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host]; - return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; + return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; } - (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url configuration:[{{classPrefix}}DefaultConfiguration sharedConfig]]; +} + +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration { + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<{{classPrefix}}Configuration>)configuration { self = [super initWithBaseURL:url]; if (self) { - self.timeoutInterval = 60; - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - self.securityPolicy = [self customSecurityPolicy]; - self.responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; - self.sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; - // configure reachability - [self configureCacheReachibility]; + _configuration = configuration; + _timeoutInterval = 60; + _responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init]; + _sanitizer = [[{{classPrefix}}Sanitizer alloc] init]; + + _downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"]; + + AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer]; + SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer]; + _requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer, + @"application/x-www-form-urlencoded": afhttpRequestSerializer, + @"multipart/form-data": afhttpRequestSerializer + }; + self.securityPolicy = [self createSecurityPolicy]; + self.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; } -+ (void)initialize { - if (self == [{{classPrefix}}ApiClient class]) { - queuedRequests = [[NSMutableSet alloc] init]; - // initialize URL cache - [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - } -} +#pragma mark - Task Methods -#pragma mark - Setter Methods - -+ (void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { - reachabilityStatus = status; -} - -- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - [super setRequestSerializer:requestSerializer]; - requestSerializer.timeoutInterval = self.timeoutInterval; -} - -#pragma mark - Cache Methods - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(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]; -} - -#pragma mark - Request Methods - -+(NSUInteger)requestQueueSize { - return [queuedRequests count]; -} - -+(NSNumber*) nextRequestId { - @synchronized(self) { - return @(++requestId); - } -} - -+(NSNumber*) queueRequest { - NSNumber* requestId = [[self class] nextRequestId]; - {{classPrefix}}DebugLog(@"added %@ to request queue", requestId); - [queuedRequests addObject:requestId]; - return requestId; -} - -+(void) cancelRequest:(NSNumber*)requestId { - [queuedRequests removeObject:requestId]; -} - --(Boolean) executeRequestWithId:(NSNumber*) requestId { - NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - return [obj intValue] == [requestId intValue]; - }]; - - if (matchingItems.count == 1) { - {{classPrefix}}DebugLog(@"removed request id %@", requestId); - [queuedRequests removeObject:requestId]; - return YES; - } else { - return NO; - } -} - -#pragma mark - Reachability Methods - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(BOOL) getOfflineState { - return offlineState; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -- (void) configureCacheReachibility { - [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - {{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; - - // call the reachability block, if configured - if (reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - - [self.reachabilityManager startMonitoring]; -} - -#pragma mark - Operation Methods - -- (void) operationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { {{classPrefix}}DebugLogResponse(response, responseObject,request,error); - strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); return; @@ -204,20 +104,17 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); }]; - [op resume]; + + return task; } -- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } - strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response); +- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock { + + __block NSString * tempFolderPath = [self.configuration.tempFolderPath copy]; + + NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { {{classPrefix}}DebugLogResponse(response, responseObject,request,error); + if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -225,9 +122,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) } NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); + return; } - NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); - NSString * filename = {{classPrefix}}__fileNameForResponse(response); + + NSString *directory = tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = {{classPrefix}}__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; NSURL *file = [NSURL fileURLWithPath:filepath]; @@ -236,53 +135,37 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) completionBlock(file, nil); }]; - [op resume]; + + return task; } -#pragma mark - Perform Request Methods +#pragma mark - Perform Request Methods --(NSNumber*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - NSAssert(NO, @"Unsupported request type %@", requestContentType); - } +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; - } else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } + AFHTTPRequestSerializer * requestSerializer = [self requestSerializerForRequestContentType:requestContentType]; + + __weak id sanitizer = self.sanitizer; // sanitize parameters - pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; - queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; - headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; - formParams = [self.sanitizer sanitizeForSerialization:formParams]; + pathParams = [sanitizer sanitizeForSerialization:pathParams]; + queryParams = [sanitizer sanitizeForSerialization:queryParams]; + headerParams = [sanitizer sanitizeForSerialization:headerParams]; + formParams = [sanitizer sanitizeForSerialization:formParams]; if(![body isKindOfClass:[NSData class]]) { - body = [self.sanitizer sanitizeForSerialization:body]; + body = [sanitizer sanitizeForSerialization:body]; } // auth setting @@ -295,22 +178,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; - NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; if ([pathWithQueryParams hasPrefix:@"/"]) { pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; } NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + NSError *requestCreateError = nil; + NSMutableURLRequest * request = nil; if (files.count > 0) { - __weak __typeof(self)weakSelf = self; - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { + request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [weakSelf.sanitizer parameterToString:obj]; + NSString *objString = [sanitizer parameterToString:obj]; NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; @@ -318,76 +198,73 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSURL *filePath = (NSURL *)obj; [formData appendPartWithFileURL:filePath name:key error:nil]; }]; - } error:nil]; + } error:&requestCreateError]; } else { if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; + request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError]; } if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; + request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError]; } } - - // request cache - BOOL hasHeaderParams = [headerParams count] > 0; - if (offlineState) { - {{classPrefix}}DebugLog(@"%@ cache forced", resourcePath); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - {{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - {{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + if(!request) { + completionBlock(nil, requestCreateError); + return nil; } - if (hasHeaderParams){ + if ([headerParams count] > 0){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; [self postProcessRequest:request]; - NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + + NSURLSessionTask *task = nil; + + if ([self.downloadTaskResponseTypes containsObject:responseType]) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; - } - else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + } else { + __weak typeof(self) weakSelf = self; + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { NSError * serializationError; - id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ error = serializationError; } completionBlock(response, error); }]; } - return requestId; + + [task resume]; + + return task; +} + +-(AFHTTPRequestSerializer *)requestSerializerForRequestContentType:(NSString *)requestContentType { + AFHTTPRequestSerializer * serializer = self.requestSerializerForContentType[requestContentType]; + if(!serializer) { + NSAssert(NO, @"Unsupported request content type %@", requestContentType); + serializer = [AFHTTPRequestSerializer serializer]; + } + serializer.timeoutInterval = self.timeoutInterval; + return serializer; } //Added for easier override to modify request -(void)postProcessRequest:(NSMutableURLRequest *)request { - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + } #pragma mark - -- (NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { +- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { if(queryParams.count == 0) { return path; } @@ -445,9 +322,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) /** * Update header and query params based on authentication settings */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { +- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings { if ([authSettings count] == 0) { return; @@ -455,10 +330,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + + id<{{classPrefix}}Configuration> config = self.configuration; for (NSString *auth in authSettings) { - NSDictionary *authSetting = configurationAuthSettings[auth]; + NSDictionary *authSetting = config.authSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty continue; } @@ -476,10 +352,10 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (AFSecurityPolicy *) customSecurityPolicy { +- (AFSecurityPolicy *) createSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - {{classPrefix}}Configuration *config = [self configuration]; + id<{{classPrefix}}Configuration> config = self.configuration; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; @@ -497,8 +373,4 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) return securityPolicy; } -- ({{classPrefix}}Configuration*) configuration { - return [{{classPrefix}}Configuration sharedConfig]; -} - @end diff --git a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache index 0167cd52ec4..6cfcd2fae4c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ApiClient-header.mustache @@ -1,22 +1,10 @@ -#import -#import #import -#import "{{classPrefix}}JSONResponseSerializer.h" -#import "{{classPrefix}}JSONRequestSerializer.h" -#import "{{classPrefix}}QueryParamCollection.h" #import "{{classPrefix}}Configuration.h" #import "{{classPrefix}}ResponseDeserializer.h" #import "{{classPrefix}}Sanitizer.h" -#import "{{classPrefix}}Logger.h" {{>licenceInfo}} -{{#models}}{{#model}}#import "{{classname}}.h" -{{/model}}{{/models}} -{{^models}}#import "{{classPrefix}}Object.h"{{/models}} - -@class {{classPrefix}}Configuration; - /** * A key for `NSError` user info dictionaries. * @@ -24,117 +12,49 @@ */ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; + @interface {{classPrefix}}ApiClient : AFHTTPSessionManager -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, readonly) NSOperationQueue* queue; +@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration; -/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one {{classPrefix}}ApiClient instance per thread. -@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer; @property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer; -/** - * Clears Cache - */ -+(void)clearCache; + +@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; /** - * Turns on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` + * Gets client singleton instance */ -+(void)setCacheEnabled:(BOOL) enabled; ++ (instancetype) sharedClient; -/** - * Gets the request queue size - * - * @return The size of `queuedRequests` static variable. - */ -+(NSUInteger)requestQueueSize; - -/** - * Sets the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Gets if the client is unreachable - * - * @return The client offline state - */ -+(BOOL) getOfflineState; - -/** - * Sets the client reachability, this may be overridden by the reachability manager if reachability changes - * - * @param status The client reachability status. - */ -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; - -/** - * Gets the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; - -/** - * Generates request id and add it to the queue - * - * @return The next executed request id. - */ -+(NSNumber*) queueRequest; - -/** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * Customizes the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Sets the api client reachability strategy - */ -- (void)configureCacheReachibility; - -/** - * Sets header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be updated, passed by pointer to pointer. + * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; +- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; + + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ +- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration; + +/** +* Initializes the session manager with a configuration and url +* +* @param url The base url +* @param configuration The configuration implementation +*/ +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration; /** * Performs request @@ -150,35 +70,20 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey; * @param responseContentType Response content-type. * @param completionBlock The block will be executed when the request completed. * - * @return The request id. + * @return The created session task. */ --(NSNumber*) requestWithPath:(NSString*) path - method:(NSString*) method - pathParams:(NSDictionary *) pathParams - queryParams:(NSDictionary*) queryParams - formParams:(NSDictionary *) formParams - files:(NSDictionary *) files - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings:(NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - responseType:(NSString *) responseType - completionBlock:(void (^)(id, NSError *))completionBlock; - -/** - * Custom security policy - * - * @return AFSecurityPolicy - */ -- (AFSecurityPolicy *) customSecurityPolicy; - -/** - * {{classPrefix}}Configuration return sharedConfig - * - * @return {{classPrefix}}Configuration - */ -- ({{classPrefix}}Configuration*) configuration; - +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock; @end diff --git a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache new file mode 100644 index 00000000000..a928e5e8f4e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-body.mustache @@ -0,0 +1,19 @@ +#import "{{classPrefix}}BasicAuthTokenProvider.h" + +@implementation {{classPrefix}}BasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + + // return empty string if username and password are empty + if (username.length == 0 && password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache new file mode 100644 index 00000000000..dfb287568a0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/BasicAuthTokenProvider-header.mustache @@ -0,0 +1,14 @@ +/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface {{classPrefix}}BasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache new file mode 100644 index 00000000000..ffb6b6971f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/Configuration-protocol.mustache @@ -0,0 +1,78 @@ +#import + +@class {{classPrefix}}Logger; + +{{>licenceInfo}} + +static NSString * const k{{classPrefix}}APIVersion = @"{{podVersion}}"; + +@protocol {{classPrefix}}Configuration + +/** + * Api logger + */ +@property (readonly, nonatomic) {{classPrefix}}Logger *logger; + +/** + * Base url + */ +@property (readonly, nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + */ +@property (readonly, nonatomic) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + */ +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (readonly, nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (readonly, nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (readonly, nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (readonly, nonatomic) BOOL debug; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (readonly, nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (readonly, nonatomic) NSString *sslCaCert; + +/** + * Authentication Settings + */ +@property (readonly, nonatomic) NSDictionary *authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache similarity index 73% rename from modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache rename to modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache index 1aeca25dd3e..548383a7e1e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-body.mustache @@ -1,6 +1,8 @@ -#import "{{classPrefix}}Configuration.h" +#import "{{classPrefix}}DefaultConfiguration.h" +#import "{{classPrefix}}BasicAuthTokenProvider.h" +#import "{{classPrefix}}Logger.h" -@interface {{classPrefix}}Configuration () +@interface {{classPrefix}}DefaultConfiguration () @property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @@ -8,12 +10,12 @@ @end -@implementation {{classPrefix}}Configuration +@implementation {{classPrefix}}DefaultConfiguration #pragma mark - Singleton Methods + (instancetype) sharedConfig { - static {{classPrefix}}Configuration *shardConfig = nil; + static {{classPrefix}}DefaultConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; @@ -26,17 +28,16 @@ - (instancetype) init { self = [super init]; if (self) { - self.apiClient = nil; - self.host = @"{{basePath}}"; - self.username = @""; - self.password = @""; - self.accessToken= @""; - self.verifySSL = YES; - self.mutableApiKey = [NSMutableDictionary dictionary]; - self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}}; - self.logger = [{{classPrefix}}Logger sharedLogger]; + _host = @"{{basePath}}"; + _username = @""; + _password = @""; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + {{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}";{{/httpUserAgent}} + _logger = [{{classPrefix}}Logger sharedLogger]; } return self; } @@ -58,16 +59,9 @@ } - (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; + NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; + return basicAuthToken; } - (NSString *) getAccessToken { @@ -150,8 +144,6 @@ self.logger.enabled = debug; } - - - (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { if(!value) { [self.mutableDefaultHeaders removeObjectForKey:key]; diff --git a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache similarity index 93% rename from modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache rename to modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache index 13747889d69..fc1f88f3865 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Configuration-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/DefaultConfiguration-header.mustache @@ -1,23 +1,18 @@ #import -#import "{{classPrefix}}ApiClient.h" -#import "{{classPrefix}}Logger.h" +#import "{{classPrefix}}Configuration.h" {{>licenceInfo}} @class {{classPrefix}}ApiClient; -@interface {{classPrefix}}Configuration : NSObject +@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration> + /** * Default api logger */ @property (nonatomic, strong) {{classPrefix}}Logger * logger; -/** - * Default api client - */ -@property (nonatomic) {{classPrefix}}ApiClient *apiClient; - /** * Default base url */ diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache deleted file mode 100644 index 7fa5e7b19e0..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-body.mustache +++ /dev/null @@ -1,39 +0,0 @@ -#import "{{classPrefix}}JSONResponseSerializer.h" - -@implementation {{classPrefix}}JSONResponseSerializer - -/// -/// When customize a response serializer, -/// the serializer must conform the protocol `AFURLResponseSerialization` -/// and implements the protocol method `responseObjectForResponse:error:` -/// -/// @param response The response to be processed. -/// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the response data. -/// -/// @return The object decoded from the specified response data. -/// -- (id) responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { - NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; - - // if response data is not a valid json, return string of data. - if ([self isParseError:*error]) { - *error = nil; - NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - return responseString; - } - - return responseJson; -} - --(BOOL)isParseError:(NSError *)error { - return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; -} - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; -} - -@end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache deleted file mode 100644 index 360e4f9cdc5..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/JSONResponseSerializer-header.mustache +++ /dev/null @@ -1,8 +0,0 @@ -#import -#import - -{{>licenceInfo}} - -@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer - -@end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache index cec8bdeea27..b544a1dae58 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-body.mustache @@ -1,3 +1,4 @@ +#import #import "JSONValueTransformer+ISO8601.h" @implementation JSONValueTransformer (ISO8601) diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache index 2a8d5b0c9e7..f621e7184a9 100644 --- a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601-header.mustache @@ -1,5 +1,4 @@ #import -#import #import {{>licenceInfo}} diff --git a/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache index 9a8f7de2418..2bb03dd983a 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Logger-body.mustache @@ -17,8 +17,7 @@ #pragma mark - Log Methods -- (void)debugLog:(NSString *)method - message:(NSString *)format, ... { +- (void)debugLog:(NSString *)method message:(NSString *)format, ... { if (!self.isEnabled) { return; } diff --git a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache index b4599c34f3f..88df6d6c9ae 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Object-body.mustache @@ -2,6 +2,35 @@ @implementation {{classPrefix}}Object +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + /** * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. diff --git a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache index 23d0c8eaa86..b1c901dbffa 100644 --- a/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/QueryParamCollection-body.mustache @@ -5,11 +5,15 @@ @synthesize values = _values; @synthesize format = _format; -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format { - _values = values; - _format = format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + self = [super init]; + if (self) { + _values = values; + _format = format; + } + return self; } diff --git a/modules/swagger-codegen/src/main/resources/objc/README.mustache b/modules/swagger-codegen/src/main/resources/objc/README.mustache index 1b917176eaa..59300fd9d02 100644 --- a/modules/swagger-codegen/src/main/resources/objc/README.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/README.mustache @@ -47,7 +47,7 @@ Import the following: ```objc #import <{{podName}}/{{{classPrefix}}}ApiClient.h> -#import <{{podName}}/{{{classPrefix}}}Configuration.h> +#import <{{podName}}/{{{classPrefix}}}DefaultConfiguration.h> // load models {{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h> {{/model}}{{/models}}// load API classes for accessing endpoints @@ -66,7 +66,7 @@ Please follow the [installation procedure](#installation--usage) and then run th ```objc {{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} {{#hasAuthMethods}} -{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{classPrefix}}DefaultConfiguration *apiConfig = [{{classPrefix}}DefaultConfiguration sharedConfig]; {{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) [apiConfig setUsername:@"YOUR_USERNAME"]; [apiConfig setPassword:@"YOUR_PASSWORD"]; diff --git a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache index 4d303fc344f..056c8c6a6fb 100644 --- a/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/ResponseDeserializer-body.mustache @@ -16,6 +16,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; @property (nonatomic, strong) NSNumberFormatter* numberFormatter; @property (nonatomic, strong) NSArray *primitiveTypes; @property (nonatomic, strong) NSArray *basicReturnTypes; +@property (nonatomic, strong) NSArray *dataReturnTypes; @property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; @property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; @@ -33,7 +34,9 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; formatter.numberStyle = NSNumberFormatterDecimalStyle; _numberFormatter = formatter; _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _basicReturnTypes = @[@"NSObject", @"id"]; + _dataReturnTypes = @[@"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" options:NSRegularExpressionCaseInsensitive error:nil]; @@ -53,23 +56,36 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; #pragma mark - Deserialize methods - (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { - // return nil if data is nil or className is nil - if (!data || !className || [data isKindOfClass:[NSNull class]]) { + if (!data || !className) { return nil; } - // remove "*" from className, if ends with "*" if ([className hasSuffix:@"*"]) { className = [className substringToIndex:[className length] - 1]; } + if([self.dataReturnTypes containsObject:className]) { + return data; + } + id jsonData = nil; + if([data isKindOfClass:[NSData class]]) { + jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error]; + } else { + jsonData = data; + } + if(!jsonData) { + jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + } else if([jsonData isKindOfClass:[NSNull class]]) { + return nil; + } + // pure object if ([self.basicReturnTypes containsObject:className]) { - return data; + return jsonData; } // primitives if ([self.primitiveTypes containsObject:className]) { - return [self deserializePrimitiveValue:data class:className error:error]; + return [self deserializePrimitiveValue:jsonData class:className error:error]; } NSTextCheckingResult *match = nil; @@ -78,37 +94,37 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; + return [self deserializeArrayValue:jsonData innerType:innerType error:error]; } // list of primitives match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; + return [self deserializeArrayValue:jsonData innerType:innerType error:error]; } // map match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; + return [self deserializeDictionaryValue:jsonData valueType:valueType error:error]; } match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; + return [self deserializeDictionaryValue:jsonData valueType:valueType error:error]; } // model Class ModelClass = NSClassFromString(className); if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error]; } if(error) { - *error = [self unknownResponseErrorWithExpectedType:className data:data]; + *error = [self unknownResponseErrorWithExpectedType:className data:jsonData]; } return nil; } @@ -172,7 +188,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528; - (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { if ([className isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; + return [NSString stringWithFormat:@"%@",data]; } else if ([className isEqualToString:@"NSDate"]) { return [self deserializeDateValue:data error:error]; diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache index 00d74aaa1f7..465633a902c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-body.mustache @@ -3,6 +3,8 @@ #import "{{classPrefix}}QueryParamCollection.h" #import +NSString * const k{{classPrefix}}ApplicationJSONType = @"application/json"; + NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@"; static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;="; @@ -43,8 +45,6 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) { @implementation {{classPrefix}}Sanitizer -static NSString * kApplicationJSONType = @"application/json"; - -(instancetype)init { self = [super init]; if ( !self ) { @@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json"; NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; for (NSString *string in accepts) { if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { - return kApplicationJSONType; + return k{{classPrefix}}ApplicationJSONType; } [lowerAccepts addObject:[string lowercaseString]]; } @@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json"; */ - (NSString *) selectHeaderContentType:(NSArray *)contentTypes { if (contentTypes.count == 0) { - return kApplicationJSONType; + return k{{classPrefix}}ApplicationJSONType; } NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; for (NSString *string in contentTypes) { if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ - return kApplicationJSONType; + return k{{classPrefix}}ApplicationJSONType; } [lowerContentTypes addObject:[string lowercaseString]]; } diff --git a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache index f975018a020..b6e77edb3f3 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Sanitizer-header.mustache @@ -4,6 +4,8 @@ extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string); +extern NSString * const k{{classPrefix}}ApplicationJSONType; + @protocol {{classPrefix}}Sanitizer /** diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 4d3148bdbb6..80a047b80b2 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -1,13 +1,14 @@ {{#operations}} #import "{{classname}}.h" #import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}ApiClient.h" {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @interface {{classname}} () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -21,52 +22,31 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[{{classPrefix}}ApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[{{classPrefix}}ApiClient sharedClient]]; } -- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { + +-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static {{classname}} *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [{{classPrefix}}ApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -75,17 +55,11 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; /// /// {{{summary}}} /// {{{notes}}} -{{#allParams}} -/// @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} +/// {{#allParams}} @param {{paramName}} {{{description}}} {{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}} /// -{{/allParams}} -{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}} -{{/responses}} -{{#returnType}} -/// @return {{{returnType}}} -{{/returnType}} --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{operationId}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler { {{#allParams}} @@ -181,11 +155,11 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513; if(handler) { handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error); } - } - ]; + }]; } {{/operation}} +{{newline}} {{/operations}} @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache index 68c987633f4..266e7355fd6 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-header.mustache @@ -11,28 +11,23 @@ extern NSString* k{{classname}}ErrorDomain; extern NSInteger k{{classname}}MissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient NS_DESIGNATED_INITIALIZER; {{#operations}} {{#operation}} /// {{{summary}}} -{{#notes}} -/// {{{notes}}} -{{/notes}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} +/// {{/allParams}}{{#responses}} +/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}} /// -{{#allParams}} -/// @param {{paramName}} {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} -{{/allParams}} -{{#responses}} -/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}} -{{/responses}} -{{#returnType}} /// @return {{{returnType}}} -{{/returnType}} --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{operationId}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; +{{newline}} {{/operation}} {{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache index da87a712fa2..5651150589c 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-protocol.mustache @@ -1,20 +1,18 @@ #import -#import "{{classPrefix}}Object.h" -#import "{{classPrefix}}ApiClient.h" + +@class {{classPrefix}}ApiClient; {{>licenceInfo}} @protocol {{classPrefix}}Api -@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient; +@property(readonly, nonatomic, strong) {{classPrefix}}ApiClient *apiClient; --(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; - --(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); +-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -(NSString*) defaultHeaderForKey:(NSString*)key; --(NSUInteger) requestQueueSize; +-(NSDictionary *)defaultHeaders; @end diff --git a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache index 44fe31d6404..b17c155b50e 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api_doc.mustache @@ -12,7 +12,7 @@ Method | HTTP request | Description {{#operation}} # **{{{operationId}}}** ```objc --(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} +-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}} {{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler; ``` @@ -24,7 +24,7 @@ Method | HTTP request | Description ### Example ```objc {{#hasAuthMethods}} -{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig]; +{{classPrefix}}DefaultConfiguration *apiConfig = [{{classPrefix}}DefaultConfiguration sharedConfig]; {{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}}) [apiConfig setUsername:@"YOUR_USERNAME"]; [apiConfig setPassword:@"YOUR_PASSWORD"]; diff --git a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache index e9979f04ae2..88c4ab0613f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/podspec.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/podspec.mustache @@ -12,9 +12,9 @@ Pod::Spec.new do |s| s.version = "{{podVersion}}" {{#apiInfo}}{{#apis}}{{^hasMore}} s.summary = "{{appName}}" - s.description = <<-DESC +{{{#appDescription}}} s.description = <<-DESC {{{appDescription}}} - DESC + DESC{{{/appDescription}}} {{/hasMore}}{{/apis}}{{/apiInfo}} s.platform = :ios, '7.0' s.requires_arc = true @@ -22,7 +22,7 @@ Pod::Spec.new do |s| {{^useCoreData}}s.framework = 'SystemConfiguration'{{/useCoreData}}{{#useCoreData}}s.frameworks = 'SystemConfiguration', 'CoreData'{{/useCoreData}} s.homepage = "{{gitRepoURL}}" - s.license = "{{#license}}{{license}}{{/license}}{{^license}}Proprietary{{/license}}" + s.license = "{{#license}}{{license}}{{/license}}{{^license}}Apache License, Version 2.0{{/license}}" s.source = { :git => "{{gitRepoURL}}.git", :tag => "#{s.version}" } s.author = { "{{authorName}}" => "{{authorEmail}}" } @@ -30,8 +30,8 @@ Pod::Spec.new do |s| s.public_header_files = '{{podName}}/**/*.h' {{#useCoreData}} s.resources = '{{podName}}/**/*.{xcdatamodeld,xcdatamodel}'{{/useCoreData}} - s.dependency 'AFNetworking', '~> 3.1' - s.dependency 'JSONModel', '~> 1.4' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.6' end diff --git a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt index 00575312d85..9dc3cff3596 100644 --- a/modules/swagger-codegen/src/main/resources/scalatra/build.sbt +++ b/modules/swagger-codegen/src/main/resources/scalatra/build.sbt @@ -23,23 +23,12 @@ scalaVersion := "2.11.2" scalacOptions += "-language:postfixOps" libraryDependencies ++= Seq( - "org.scalatest" %% "scalatest" % "2.2.1" % "test", - "org.scalatra" %% "scalatra" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-scalate" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-json" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-swagger-ext" % "2.3.0.RC3", - "org.scalatra" %% "scalatra-slf4j" % "2.3.0.RC3", - "org.json4s" %% "json4s-jackson" % "3.2.10", - "org.json4s" %% "json4s-ext" % "3.2.10", - "commons-codec" % "commons-codec" % "1.7", - "net.databinder.dispatch" %% "dispatch-core" % "0.11.2", - //"net.databinder.dispatch" %% "json4s-jackson" % "0.11.2", - "net.databinder.dispatch" %% "dispatch-json4s-jackson" % "0.11.2", - "com.typesafe.akka" %% "akka-actor" % "2.3.6", - "org.eclipse.jetty" % "jetty-server" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty" % "jetty-webapp" % "9.2.3.v20140905" % "container;compile;test", - "org.eclipse.jetty.orbit" % "javax.servlet" % "3.0.0.v201112011016" % "container;compile;provided;test" artifacts (Artifact("javax.servlet", "jar", "jar")) + "com.github.finagle" %% "finch-core" % "0.9.2-SNAPSHOT" changing(), + "com.github.finagle" %% "finch-argonaut" % "0.9.2-SNAPSHOT" changing(), + "io.argonaut" %% "argonaut" % "6.1", + "com.github.finagle" %% "finch-test" % "0.9.2-SNAPSHOT" % "test,it" changing(), + "org.scalacheck" %% "scalacheck" % "1.12.5" % "test,it", + "org.scalatest" %% "scalatest" % "2.2.5" % "test,it" ) resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" @@ -48,6 +37,9 @@ resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/reposi resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" +resolvers += "TM" at "http://maven.twttr.com" + + ivyXML := diff --git a/samples/client/petstore/objc/core-data/README.md b/samples/client/petstore/objc/core-data/README.md index c59d5182287..eb7dc0b57a8 100644 --- a/samples/client/petstore/objc/core-data/README.md +++ b/samples/client/petstore/objc/core-data/README.md @@ -6,7 +6,8 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build package: io.swagger.codegen.languages.ObjcClientCodegen +- Build date: 2016-08-23T10:56:27.632+02:00 +- Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -39,7 +40,7 @@ Import the following: ```objc #import -#import +#import // load models #import #import @@ -55,7 +56,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. ## Getting Started @@ -63,7 +64,7 @@ Please follow the [installation procedure](#installation--usage) and then run th ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -123,12 +124,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -138,6 +133,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/objc/core-data/SwaggerClient.podspec b/samples/client/petstore/objc/core-data/SwaggerClient.podspec index 1a31e2e9a15..fd785a6255c 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient.podspec +++ b/samples/client/petstore/objc/core-data/SwaggerClient.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.frameworks = 'SystemConfiguration', 'CoreData' s.homepage = "https://github.com/swagger-api/swagger-codegen" - s.license = "Proprietary" + s.license = "Apache License, Version 2.0" s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } s.author = { "Swagger" => "apiteam@swagger.io" } @@ -30,8 +30,8 @@ Pod::Spec.new do |s| s.public_header_files = 'SwaggerClient/**/*.h' s.resources = 'SwaggerClient/**/*.{xcdatamodeld,xcdatamodel}' - s.dependency 'AFNetworking', '~> 3.1' - s.dependency 'JSONModel', '~> 1.4' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.6' end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h index 719d193130b..ade955b27f8 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.h @@ -12,99 +12,139 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - @interface SWGPetApi: NSObject extern NSString* kSWGPetApiErrorDomain; extern NSInteger kSWGPetApiMissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// Add a new pet to the store /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) +/// /// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; + /// Finds Pets by status -/// Multiple status values can be provided with comma separated strings +/// Multiple status values can be provided with comma seperated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid status value" +/// /// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// Finds Pets by tags -/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid tag value" +/// /// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found" +/// /// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; + /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// 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 (optional) /// @param status Updated status of the pet (optional) +/// /// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// +/// @return +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; + /// uploads an image /// /// /// @param petId ID of pet to update /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m index fb0421c81fd..0034dd69fc5 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGPetApi.m @@ -1,11 +1,12 @@ #import "SWGPetApi.h" #import "SWGQueryParamCollection.h" +#import "SWGApiClient.h" #import "SWGPet.h" @interface SWGPetApi () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -19,52 +20,31 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[SWGApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[SWGApiClient sharedClient]]; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static SWGPetApi *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [SWGApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -72,10 +52,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -123,19 +104,19 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Deletes a pet /// -/// @param petId Pet id to delete +/// @param petId Pet id to delete /// -/// @param apiKey (optional) +/// @param apiKey (optional) /// -/// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set @@ -200,19 +181,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Finds Pets by status -/// Multiple status values can be provided with comma separated strings -/// @param status Status values that need to be considered for filter (optional, default to available) +/// Multiple status values can be provided with comma seperated strings +/// @param status Status values that need to be considered for filter (optional, default to available) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid status value" -/// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -263,19 +242,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler((NSArray*)data, error); } - } - ]; + }]; } /// /// Finds Pets by tags -/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -/// @param tags Tags to filter by (optional) +/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// @param tags Tags to filter by (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid tag value" -/// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; @@ -326,20 +303,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler((NSArray*)data, error); } - } - ]; + }]; } /// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched +/// @param petId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found" -/// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +/// @returns SWGPet* +/// +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { @@ -378,7 +352,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -400,19 +374,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler((SWGPet*)data, error); } - } - ]; + }]; } /// /// Update an existing pet /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found", -/// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -460,21 +432,21 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet (optional) +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet (optional) +/// @param status Updated status of the pet (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler { @@ -543,21 +515,21 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server (optional) +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload (optional) +/// @param file file to upload (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler { @@ -624,9 +596,9 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h index 3e101bed9a7..92aeefb176e 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.h @@ -12,54 +12,78 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - @interface SWGStoreApi: NSObject extern NSString* kSWGStoreApiErrorDomain; extern NSInteger kSWGStoreApiMissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// @param orderId ID of the order that needs to be deleted +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// +/// @return +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; + /// Returns pet inventories by status /// Returns a map of status codes to quantities /// +/// /// code:200 message:"successful operation" +/// /// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; + /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// @param orderId ID of pet that needs to be fetched +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" +/// /// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid Order" +/// /// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m index b86920b29e2..2a17173f83a 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGStoreApi.m @@ -1,11 +1,12 @@ #import "SWGStoreApi.h" #import "SWGQueryParamCollection.h" +#import "SWGApiClient.h" #import "SWGOrder.h" @interface SWGStoreApi () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -19,52 +20,31 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[SWGApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[SWGApiClient sharedClient]]; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static SWGStoreApi *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [SWGApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -72,11 +52,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -/// @param orderId ID of the order that needs to be deleted +/// @param orderId ID of the order that needs to be deleted /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// @returns void +/// +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -137,16 +117,15 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// code:200 message:"successful operation" -/// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +/// @returns NSDictionary* +/// +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; @@ -193,20 +172,17 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler((NSDictionary*)data, error); } - } - ]; + }]; } /// /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -/// @param orderId ID of pet that needs to be fetched +/// @param orderId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" -/// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -267,19 +243,17 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler((SWGOrder*)data, error); } - } - ]; + }]; } /// /// Place an order for a pet /// -/// @param body order placed for purchasing the pet (optional) +/// @param body order placed for purchasing the pet (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid Order" -/// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; @@ -327,9 +301,9 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler((SWGOrder*)data, error); } - } - ]; + }]; } + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h index f0b5e37550b..2c35bdcb7b0 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.h @@ -12,90 +12,131 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - @interface SWGUserApi: NSObject extern NSString* kSWGUserApiErrorDomain; extern NSInteger kSWGUserApiMissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// Create user /// This can only be done by the logged in user. /// /// @param body Created user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// +/// @return +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted +/// /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; + /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" +/// /// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; + /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username/password supplied" +/// /// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; + /// Logs out current logged in user session /// /// +/// /// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// +/// @return +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; + /// Updated user /// This can only be done by the logged in user. /// /// @param username name that need to be deleted /// @param body Updated user object (optional) +/// /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m index df056030b75..e1acf3af007 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Api/SWGUserApi.m @@ -1,11 +1,12 @@ #import "SWGUserApi.h" #import "SWGQueryParamCollection.h" +#import "SWGApiClient.h" #import "SWGUser.h" @interface SWGUserApi () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -19,52 +20,31 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[SWGApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[SWGApiClient sharedClient]]; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static SWGUserApi *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [SWGApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -72,10 +52,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object (optional) +/// @param body Created user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// @returns void +/// +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; @@ -123,17 +104,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; @@ -181,17 +162,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; @@ -239,18 +220,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Delete user /// This can only be done by the logged in user. -/// @param username The name that needs to be deleted +/// @param username The name that needs to be deleted /// -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -311,20 +291,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" -/// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +/// @returns SWGUser* +/// +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -385,21 +362,19 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler((SWGUser*)data, error); } - } - ]; + }]; } /// /// Logs user into the system /// -/// @param username The user name for login (optional) +/// @param username The user name for login (optional) /// -/// @param password The password for login in clear text (optional) +/// @param password The password for login in clear text (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username/password supplied" -/// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +/// @returns NSString* +/// +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; @@ -453,15 +428,15 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler((NSString*)data, error); } - } - ]; + }]; } /// /// Logs out current logged in user session /// -/// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// @returns void +/// +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; @@ -508,20 +483,19 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object (optional) +/// @param body Updated user object (optional) /// -/// code:400 message:"Invalid user supplied", -/// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set @@ -584,9 +558,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } + @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.h index 8eac63eefb8..d5b3e9291bc 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.h @@ -1,5 +1,4 @@ #import -#import #import /** diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.m index cec8bdeea27..b544a1dae58 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/JSONValueTransformer+ISO8601.m @@ -1,3 +1,4 @@ +#import #import "JSONValueTransformer+ISO8601.h" @implementation JSONValueTransformer (ISO8601) diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApi.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApi.h index 49364ffb95c..bdc690332f5 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApi.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApi.h @@ -1,6 +1,6 @@ #import -#import "SWGObject.h" -#import "SWGApiClient.h" + +@class SWGApiClient; /** * Swagger Petstore @@ -17,15 +17,13 @@ @protocol SWGApi -@property(nonatomic, assign) SWGApiClient *apiClient; +@property(readonly, nonatomic, strong) SWGApiClient *apiClient; --(id) initWithApiClient:(SWGApiClient *)apiClient; - --(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -(NSString*) defaultHeaderForKey:(NSString*)key; --(NSUInteger) requestQueueSize; +-(NSDictionary *)defaultHeaders; @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h index 8869aa5fbe6..cec2428f4b9 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.h @@ -1,13 +1,7 @@ -#import -#import #import -#import "SWGJSONResponseSerializer.h" -#import "SWGJSONRequestSerializer.h" -#import "SWGQueryParamCollection.h" #import "SWGConfiguration.h" #import "SWGResponseDeserializer.h" #import "SWGSanitizer.h" -#import "SWGLogger.h" /** * Swagger Petstore @@ -19,19 +13,20 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - -#import "SWGCategory.h" -#import "SWGOrder.h" -#import "SWGPet.h" -#import "SWGTag.h" -#import "SWGUser.h" - - - -@class SWGConfiguration; - /** * A key for `NSError` user info dictionaries. * @@ -39,117 +34,49 @@ */ extern NSString *const SWGResponseObjectErrorKey; + @interface SWGApiClient : AFHTTPSessionManager -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, readonly) NSOperationQueue* queue; +@property (nonatomic, strong, readonly) id configuration; -/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one SWGApiClient instance per thread. -@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, strong) id responseDeserializer; @property(nonatomic, strong) id sanitizer; -/** - * Clears Cache - */ -+(void)clearCache; + +@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; /** - * Turns on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` + * Gets client singleton instance */ -+(void)setCacheEnabled:(BOOL) enabled; ++ (instancetype) sharedClient; -/** - * Gets the request queue size - * - * @return The size of `queuedRequests` static variable. - */ -+(NSUInteger)requestQueueSize; - -/** - * Sets the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Gets if the client is unreachable - * - * @return The client offline state - */ -+(BOOL) getOfflineState; - -/** - * Sets the client reachability, this may be overridden by the reachability manager if reachability changes - * - * @param status The client reachability status. - */ -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; - -/** - * Gets the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; - -/** - * Generates request id and add it to the queue - * - * @return The next executed request id. - */ -+(NSNumber*) queueRequest; - -/** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * Customizes the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Sets the api client reachability strategy - */ -- (void)configureCacheReachibility; - -/** - * Sets header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be updated, passed by pointer to pointer. + * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; +- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; + + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ +- (instancetype)initWithConfiguration:(id)configuration; + +/** +* Initializes the session manager with a configuration and url +* +* @param url The base url +* @param configuration The configuration implementation +*/ +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration; /** * Performs request @@ -165,35 +92,20 @@ extern NSString *const SWGResponseObjectErrorKey; * @param responseContentType Response content-type. * @param completionBlock The block will be executed when the request completed. * - * @return The request id. + * @return The created session task. */ --(NSNumber*) requestWithPath:(NSString*) path - method:(NSString*) method - pathParams:(NSDictionary *) pathParams - queryParams:(NSDictionary*) queryParams - formParams:(NSDictionary *) formParams - files:(NSDictionary *) files - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings:(NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - responseType:(NSString *) responseType - completionBlock:(void (^)(id, NSError *))completionBlock; - -/** - * Custom security policy - * - * @return AFSecurityPolicy - */ -- (AFSecurityPolicy *) customSecurityPolicy; - -/** - * SWGConfiguration return sharedConfig - * - * @return SWGConfiguration - */ -- (SWGConfiguration*) configuration; - +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock; @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m index c3c1bc453c4..f757e139d0e 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGApiClient.m @@ -1,14 +1,13 @@ + +#import "SWGLogger.h" #import "SWGApiClient.h" +#import "SWGJSONRequestSerializer.h" +#import "SWGQueryParamCollection.h" +#import "SWGDefaultConfiguration.h" NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; -static NSUInteger requestId = 0; -static bool offlineState = false; -static NSMutableSet * queuedRequests = nil; -static bool cacheEnabled = false; -static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; -static void (^reachabilityChangeBlock)(int); - +static NSString * const kSWGContentDispositionKey = @"Content-Disposition"; static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { if(![response isKindOfClass:[NSHTTPURLResponse class]]) { @@ -19,179 +18,80 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSDictionary * headers = SWG__headerFieldsForResponse(response); - if(!headers[@"Content-Disposition"]) { + if(!headers[kSWGContentDispositionKey]) { return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; } NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = headers[@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil]; + NSString *contentDispositionHeader = headers[kSWGContentDispositionKey]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])]; return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; } @interface SWGApiClient () -@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; +@property (nonatomic, strong, readwrite) id configuration; + +@property (nonatomic, strong) NSArray* downloadTaskResponseTypes; @end @implementation SWGApiClient +#pragma mark - Singleton Methods + ++ (instancetype) sharedClient { + static SWGApiClient *sharedClient = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedClient = [[self alloc] init]; + }); + return sharedClient; +} + +#pragma mark - Initialize Methods + - (instancetype)init { - NSString *baseUrl = [[SWGConfiguration sharedConfig] host]; - return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; + return [self initWithConfiguration:[SWGDefaultConfiguration sharedConfig]]; } - (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url configuration:[SWGDefaultConfiguration sharedConfig]]; +} + +- (instancetype)initWithConfiguration:(id)configuration { + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration { self = [super initWithBaseURL:url]; if (self) { - self.timeoutInterval = 60; - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - self.securityPolicy = [self customSecurityPolicy]; - self.responseDeserializer = [[SWGResponseDeserializer alloc] init]; - self.sanitizer = [[SWGSanitizer alloc] init]; - // configure reachability - [self configureCacheReachibility]; + _configuration = configuration; + _timeoutInterval = 60; + _responseDeserializer = [[SWGResponseDeserializer alloc] init]; + _sanitizer = [[SWGSanitizer alloc] init]; + + _downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"]; + + AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer]; + SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer]; + _requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer, + @"application/x-www-form-urlencoded": afhttpRequestSerializer, + @"multipart/form-data": afhttpRequestSerializer + }; + self.securityPolicy = [self createSecurityPolicy]; + self.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; } -+ (void)initialize { - if (self == [SWGApiClient class]) { - queuedRequests = [[NSMutableSet alloc] init]; - // initialize URL cache - [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - } -} +#pragma mark - Task Methods -#pragma mark - Setter Methods - -+ (void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { - reachabilityStatus = status; -} - -- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - [super setRequestSerializer:requestSerializer]; - requestSerializer.timeoutInterval = self.timeoutInterval; -} - -#pragma mark - Cache Methods - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(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]; -} - -#pragma mark - Request Methods - -+(NSUInteger)requestQueueSize { - return [queuedRequests count]; -} - -+(NSNumber*) nextRequestId { - @synchronized(self) { - return @(++requestId); - } -} - -+(NSNumber*) queueRequest { - NSNumber* requestId = [[self class] nextRequestId]; - SWGDebugLog(@"added %@ to request queue", requestId); - [queuedRequests addObject:requestId]; - return requestId; -} - -+(void) cancelRequest:(NSNumber*)requestId { - [queuedRequests removeObject:requestId]; -} - --(Boolean) executeRequestWithId:(NSNumber*) requestId { - NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - return [obj intValue] == [requestId intValue]; - }]; - - if (matchingItems.count == 1) { - SWGDebugLog(@"removed request id %@", requestId); - [queuedRequests removeObject:requestId]; - return YES; - } else { - return NO; - } -} - -#pragma mark - Reachability Methods - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(BOOL) getOfflineState { - return offlineState; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -- (void) configureCacheReachibility { - [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; - - // call the reachability block, if configured - if (reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - - [self.reachabilityManager startMonitoring]; -} - -#pragma mark - Operation Methods - -- (void) operationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { SWGDebugLogResponse(response, responseObject,request,error); - strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); return; @@ -204,20 +104,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); }]; - [op resume]; + + return task; } -- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } - strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); +- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock { + + __block NSString * tempFolderPath = [self.configuration.tempFolderPath copy]; + + NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { SWGDebugLogResponse(response, responseObject,request,error); + if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -225,9 +122,11 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); + return; } - NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); - NSString * filename = SWG__fileNameForResponse(response); + + NSString *directory = tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = SWG__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; NSURL *file = [NSURL fileURLWithPath:filepath]; @@ -236,53 +135,37 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { completionBlock(file, nil); }]; - [op resume]; + + return task; } -#pragma mark - Perform Request Methods +#pragma mark - Perform Request Methods --(NSNumber*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [SWGJSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - NSAssert(NO, @"Unsupported request type %@", requestContentType); - } +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [SWGJSONResponseSerializer serializer]; - } else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } + AFHTTPRequestSerializer * requestSerializer = [self requestSerializerForRequestContentType:requestContentType]; + + __weak id sanitizer = self.sanitizer; // sanitize parameters - pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; - queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; - headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; - formParams = [self.sanitizer sanitizeForSerialization:formParams]; + pathParams = [sanitizer sanitizeForSerialization:pathParams]; + queryParams = [sanitizer sanitizeForSerialization:queryParams]; + headerParams = [sanitizer sanitizeForSerialization:headerParams]; + formParams = [sanitizer sanitizeForSerialization:formParams]; if(![body isKindOfClass:[NSData class]]) { - body = [self.sanitizer sanitizeForSerialization:body]; + body = [sanitizer sanitizeForSerialization:body]; } // auth setting @@ -295,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; - NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; if ([pathWithQueryParams hasPrefix:@"/"]) { pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; } NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + NSError *requestCreateError = nil; + NSMutableURLRequest * request = nil; if (files.count > 0) { - __weak __typeof(self)weakSelf = self; - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { + request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [weakSelf.sanitizer parameterToString:obj]; + NSString *objString = [sanitizer parameterToString:obj]; NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; @@ -318,76 +198,73 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSURL *filePath = (NSURL *)obj; [formData appendPartWithFileURL:filePath name:key error:nil]; }]; - } error:nil]; + } error:&requestCreateError]; } else { if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; + request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError]; } if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; + request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError]; } } - - // request cache - BOOL hasHeaderParams = [headerParams count] > 0; - if (offlineState) { - SWGDebugLog(@"%@ cache forced", resourcePath); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - SWGDebugLog(@"%@ cache enabled", resourcePath); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - SWGDebugLog(@"%@ cache disabled", resourcePath); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + if(!request) { + completionBlock(nil, requestCreateError); + return nil; } - if (hasHeaderParams){ + if ([headerParams count] > 0){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; [self postProcessRequest:request]; - NSNumber* requestId = [SWGApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + + NSURLSessionTask *task = nil; + + if ([self.downloadTaskResponseTypes containsObject:responseType]) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; - } - else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + } else { + __weak typeof(self) weakSelf = self; + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { NSError * serializationError; - id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ error = serializationError; } completionBlock(response, error); }]; } - return requestId; + + [task resume]; + + return task; +} + +-(AFHTTPRequestSerializer *)requestSerializerForRequestContentType:(NSString *)requestContentType { + AFHTTPRequestSerializer * serializer = self.requestSerializerForContentType[requestContentType]; + if(!serializer) { + NSAssert(NO, @"Unsupported request content type %@", requestContentType); + serializer = [AFHTTPRequestSerializer serializer]; + } + serializer.timeoutInterval = self.timeoutInterval; + return serializer; } //Added for easier override to modify request -(void)postProcessRequest:(NSMutableURLRequest *)request { - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + } #pragma mark - -- (NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { +- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { if(queryParams.count == 0) { return path; } @@ -445,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { /** * Update header and query params based on authentication settings */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { +- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings { if ([authSettings count] == 0) { return; @@ -455,10 +330,11 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + + id config = self.configuration; for (NSString *auth in authSettings) { - NSDictionary *authSetting = configurationAuthSettings[auth]; + NSDictionary *authSetting = config.authSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty continue; } @@ -476,10 +352,10 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (AFSecurityPolicy *) customSecurityPolicy { +- (AFSecurityPolicy *) createSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - SWGConfiguration *config = [self configuration]; + id config = self.configuration; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; @@ -497,8 +373,4 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return securityPolicy; } -- (SWGConfiguration*) configuration { - return [SWGConfiguration sharedConfig]; -} - @end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.h new file mode 100644 index 00000000000..6c50d3750b4 --- /dev/null +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.h @@ -0,0 +1,14 @@ +/** The `SWGBasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface SWGBasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.m new file mode 100644 index 00000000000..3788009ec58 --- /dev/null +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGBasicAuthTokenProvider.m @@ -0,0 +1,19 @@ +#import "SWGBasicAuthTokenProvider.h" + +@implementation SWGBasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + + // return empty string if username and password are empty + if (username.length == 0 && password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h index 81d33fda278..864d87d2535 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.h @@ -1,6 +1,6 @@ #import -#import "SWGApiClient.h" -#import "SWGLogger.h" + +@class SWGLogger; /** * Swagger Petstore @@ -12,160 +12,89 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ +static NSString * const kSWGAPIVersion = @"1.0.0"; -@class SWGApiClient; - -@interface SWGConfiguration : NSObject +@protocol SWGConfiguration /** - * Default api logger + * Api logger */ -@property (nonatomic, strong) SWGLogger * logger; +@property (readonly, nonatomic) SWGLogger *logger; /** - * Default api client + * Base url */ -@property (nonatomic) SWGApiClient *apiClient; - -/** - * Default base url - */ -@property (nonatomic) NSString *host; +@property (readonly, nonatomic) NSString *host; /** * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ -@property (readonly, nonatomic, strong) NSDictionary *apiKey; +@property (readonly, nonatomic) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ -@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; /** * Username for HTTP Basic Authentication */ - @property (nonatomic) NSString *username; +@property (readonly, nonatomic) NSString *username; /** * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *password; +@property (readonly, nonatomic) NSString *password; /** * Access token for OAuth */ -@property (nonatomic) NSString *accessToken; +@property (readonly, nonatomic) NSString *accessToken; /** * Temp folder for file download */ -@property (nonatomic) NSString *tempFolderPath; +@property (readonly, nonatomic) NSString *tempFolderPath; /** * Debug switch, default false */ -@property (nonatomic) BOOL debug; - -/** - * Gets configuration singleton instance - */ -+ (instancetype) sharedConfig; +@property (readonly, nonatomic) BOOL debug; /** * SSL/TLS verification * Set this to NO to skip verifying SSL certificate when calling API from https server */ -@property (nonatomic) BOOL verifySSL; +@property (readonly, nonatomic) BOOL verifySSL; /** * SSL/TLS verification * Set this to customize the certificate file to verify the peer */ -@property (nonatomic) NSString *sslCaCert; +@property (readonly, nonatomic) NSString *sslCaCert; /** - * Sets API key - * - * To remove a apiKey for an identifier, just set the apiKey to nil. - * - * @param apiKey API key or token. - * @param identifier API key identifier (authentication schema). - * + * Authentication Settings */ -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; - -/** - * Removes api key - * - * @param identifier API key identifier. - */ -- (void) removeApiKey:(NSString *)identifier; - -/** - * Sets the prefix for API key - * - * @param prefix API key prefix. - * @param identifier API key identifier. - */ -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; - -/** - * Removes api key prefix - * - * @param identifier API key identifier. - */ -- (void) removeApiKeyPrefix:(NSString *)identifier; - -/** - * Gets API key (with prefix if set) - */ -- (NSString *) getApiKeyWithPrefix:(NSString *) key; - -/** - * Gets Basic Auth token - */ -- (NSString *) getBasicAuthToken; - -/** - * Gets OAuth access token - */ -- (NSString *) getAccessToken; - -/** - * Gets Authentication Settings - */ -- (NSDictionary *) authSettings; +@property (readonly, nonatomic) NSDictionary *authSettings; /** * Default headers for all services */ @property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; -/** -* Removes header from defaultHeaders -* -* @param key Header name. -*/ --(void) removeDefaultHeaderForKey:(NSString*)key; - -/** -* Sets the header for key -* -* @param value Value for header name -* @param key Header name -*/ --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; - -/** -* @param key Header key name. -*/ --(NSString*) defaultHeaderForKey:(NSString*)key; - -@end +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.h new file mode 100644 index 00000000000..48cedd5d558 --- /dev/null +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.h @@ -0,0 +1,177 @@ +#import +#import "SWGConfiguration.h" + +/** +* Swagger Petstore +* This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@class SWGApiClient; + +@interface SWGDefaultConfiguration : NSObject + + +/** + * Default api logger + */ +@property (nonatomic, strong) SWGLogger * logger; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Gets configuration singleton instance + */ ++ (instancetype) sharedConfig; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + +/** + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * + */ +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Removes api key + * + * @param identifier API key identifier. + */ +- (void) removeApiKey:(NSString *)identifier; + +/** + * Sets the prefix for API key + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) + */ +- (NSString *) getApiKeyWithPrefix:(NSString *) key; + +/** + * Gets Basic Auth token + */ +- (NSString *) getBasicAuthToken; + +/** + * Gets OAuth access token + */ +- (NSString *) getAccessToken; + +/** + * Gets Authentication Settings + */ +- (NSDictionary *) authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + +@end diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m similarity index 72% rename from samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m rename to samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m index b21290068a1..705580e9a54 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGConfiguration.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGDefaultConfiguration.m @@ -1,6 +1,8 @@ -#import "SWGConfiguration.h" +#import "SWGDefaultConfiguration.h" +#import "SWGBasicAuthTokenProvider.h" +#import "SWGLogger.h" -@interface SWGConfiguration () +@interface SWGDefaultConfiguration () @property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @@ -8,12 +10,12 @@ @end -@implementation SWGConfiguration +@implementation SWGDefaultConfiguration #pragma mark - Singleton Methods + (instancetype) sharedConfig { - static SWGConfiguration *shardConfig = nil; + static SWGDefaultConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; @@ -26,17 +28,16 @@ - (instancetype) init { self = [super init]; if (self) { - self.apiClient = nil; - self.host = @"http://petstore.swagger.io/v2"; - self.username = @""; - self.password = @""; - self.accessToken= @""; - self.verifySSL = YES; - self.mutableApiKey = [NSMutableDictionary dictionary]; - self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders[@"User-Agent"] = [NSString stringWithFormat:@"Swagger-Codegen/1.0.0/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; - self.logger = [SWGLogger sharedLogger]; + _host = @"http://petstore.swagger.io/v2"; + _username = @""; + _password = @""; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + + _logger = [SWGLogger sharedLogger]; } return self; } @@ -58,16 +59,9 @@ } - (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; + NSString *basicAuthToken = [SWGBasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; + return basicAuthToken; } - (NSString *) getAccessToken { @@ -110,13 +104,6 @@ - (NSDictionary *) authSettings { return @{ - @"api_key": - @{ - @"type": @"api_key", - @"in": @"header", - @"key": @"api_key", - @"value": [self getApiKeyWithPrefix:@"api_key"] - }, @"petstore_auth": @{ @"type": @"oauth", @@ -124,6 +111,13 @@ @"key": @"Authorization", @"value": [self getAccessToken] }, + @"api_key": + @{ + @"type": @"api_key", + @"in": @"header", + @"key": @"api_key", + @"value": [self getApiKeyWithPrefix:@"api_key"] + }, }; } @@ -135,8 +129,6 @@ self.logger.enabled = debug; } - - - (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { if(!value) { [self.mutableDefaultHeaders removeObjectForKey:key]; diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGLogger.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGLogger.m index 322ae9678d7..2a96e5ec54d 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGLogger.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGLogger.m @@ -17,8 +17,7 @@ #pragma mark - Log Methods -- (void)debugLog:(NSString *)method - message:(NSString *)format, ... { +- (void)debugLog:(NSString *)method message:(NSString *)format, ... { if (!self.isEnabled) { return; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGObject.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGObject.m index 8085c404f7e..db970d34669 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGObject.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGObject.m @@ -2,6 +2,35 @@ @implementation SWGObject +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + /** * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m index 83303045185..9aa8a091762 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m @@ -5,11 +5,15 @@ @synthesize values = _values; @synthesize format = _format; -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format { - _values = values; - _format = format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + self = [super init]; + if (self) { + _values = values; + _format = format; + } + return self; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m index 6ac9f75e818..46d4b460fc7 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGResponseDeserializer.m @@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; @property (nonatomic, strong) NSNumberFormatter* numberFormatter; @property (nonatomic, strong) NSArray *primitiveTypes; @property (nonatomic, strong) NSArray *basicReturnTypes; +@property (nonatomic, strong) NSArray *dataReturnTypes; @property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; @property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; @@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; formatter.numberStyle = NSNumberFormatterDecimalStyle; _numberFormatter = formatter; _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _basicReturnTypes = @[@"NSObject", @"id"]; + _dataReturnTypes = @[@"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" options:NSRegularExpressionCaseInsensitive error:nil]; @@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; #pragma mark - Deserialize methods - (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { - // return nil if data is nil or className is nil - if (!data || !className || [data isKindOfClass:[NSNull class]]) { + if (!data || !className) { return nil; } - // remove "*" from className, if ends with "*" if ([className hasSuffix:@"*"]) { className = [className substringToIndex:[className length] - 1]; } + if([self.dataReturnTypes containsObject:className]) { + return data; + } + id jsonData = nil; + if([data isKindOfClass:[NSData class]]) { + jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error]; + } else { + jsonData = data; + } + if(!jsonData) { + jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + } else if([jsonData isKindOfClass:[NSNull class]]) { + return nil; + } + // pure object if ([self.basicReturnTypes containsObject:className]) { - return data; + return jsonData; } // primitives if ([self.primitiveTypes containsObject:className]) { - return [self deserializePrimitiveValue:data class:className error:error]; + return [self deserializePrimitiveValue:jsonData class:className error:error]; } NSTextCheckingResult *match = nil; @@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; + return [self deserializeArrayValue:jsonData innerType:innerType error:error]; } // list of primitives match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; + return [self deserializeArrayValue:jsonData innerType:innerType error:error]; } // map match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; + return [self deserializeDictionaryValue:jsonData valueType:valueType error:error]; } match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; + return [self deserializeDictionaryValue:jsonData valueType:valueType error:error]; } // model Class ModelClass = NSClassFromString(className); if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error]; } if(error) { - *error = [self unknownResponseErrorWithExpectedType:className data:data]; + *error = [self unknownResponseErrorWithExpectedType:className data:jsonData]; } return nil; } @@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; - (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { if ([className isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; + return [NSString stringWithFormat:@"%@",data]; } else if ([className isEqualToString:@"NSDate"]) { return [self deserializeDateValue:data error:error]; diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.h b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.h index b7cd3a6cb18..28e84d83714 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.h +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.h @@ -15,6 +15,8 @@ extern NSString * SWGPercentEscapedStringFromString(NSString *string); +extern NSString * const kSWGApplicationJSONType; + @protocol SWGSanitizer /** diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.m index a74f72afbe3..49ff6ed014a 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGSanitizer.m @@ -3,6 +3,8 @@ #import "SWGQueryParamCollection.h" #import +NSString * const kSWGApplicationJSONType = @"application/json"; + NSString * SWGPercentEscapedStringFromString(NSString *string) { static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@"; static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;="; @@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { @implementation SWGSanitizer -static NSString * kApplicationJSONType = @"application/json"; - -(instancetype)init { self = [super init]; if ( !self ) { @@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json"; NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; for (NSString *string in accepts) { if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { - return kApplicationJSONType; + return kSWGApplicationJSONType; } [lowerAccepts addObject:[string lowercaseString]]; } @@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json"; */ - (NSString *) selectHeaderContentType:(NSArray *)contentTypes { if (contentTypes.count == 0) { - return kApplicationJSONType; + return kSWGApplicationJSONType; } NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; for (NSString *string in contentTypes) { if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ - return kApplicationJSONType; + return kSWGApplicationJSONType; } [lowerContentTypes addObject:[string lowercaseString]]; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 68c3e696436..7ee3eb8862d 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -214,12 +214,13 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */; buildPhases = ( - 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */, + 799E7E29D924C30424DFBA28 /* [CP] Check Pods Manifest.lock */, 6003F586195388D20070C39A /* Sources */, 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, - 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */, - 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */, + 429AF5C69E165ED75311B4B0 /* [CP] Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* [CP] Embed Pods Frameworks */, + FF3F107CF27E0A54D86C49F5 /* Embed Pods Frameworks */, ); buildRules = ( ); @@ -234,12 +235,13 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */; buildPhases = ( - 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */, + 7B069562A9F91E498732474F /* [CP] Check Pods Manifest.lock */, 6003F5AA195388D20070C39A /* Sources */, 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, - E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */, - 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */, + E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* [CP] Embed Pods Frameworks */, + AA7CAD658C61D6EBA222B5F8 /* Embed Pods Frameworks */, ); buildRules = ( ); @@ -258,7 +260,7 @@ isa = PBXProject; attributes = { CLASSPREFIX = SWG; - LastUpgradeCheck = 0510; + LastUpgradeCheck = 0730; ORGANIZATIONNAME = geekerzp; }; buildConfigurationList = 6003F585195388D10070C39A /* Build configuration list for PBXProject "SwaggerClient" */; @@ -303,14 +305,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = { + 111D7956304BD6E860AA8709 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -318,14 +320,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = { + 183E54C09C54DAEB54B2546F /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -333,14 +335,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = { + 429AF5C69E165ED75311B4B0 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -348,14 +350,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = { + 799E7E29D924C30424DFBA28 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -363,14 +365,14 @@ 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; }; - 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = { + 7B069562A9F91E498732474F /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -378,14 +380,29 @@ 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; }; - E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = { + AA7CAD658C61D6EBA222B5F8 /* Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -393,6 +410,21 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-resources.sh\"\n"; showEnvVarsInLog = 0; }; + FF3F107CF27E0A54D86C49F5 /* Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -463,6 +495,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; @@ -527,6 +560,7 @@ GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch"; INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist"; MODULE_NAME = ExampleApp; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; @@ -542,6 +576,7 @@ GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch"; INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist"; MODULE_NAME = ExampleApp; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; @@ -563,6 +598,7 @@ "$(inherited)", ); INFOPLIST_FILE = "Tests/Tests-Info.plist"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = xctest; }; @@ -580,6 +616,7 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch"; INFOPLIST_FILE = "Tests/Tests-Info.plist"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = xctest; }; diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme index 5c68411bb2d..24c1ef20c79 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme @@ -1,11 +1,17 @@ - + + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> + buildConfiguration = "Debug" + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES"> - + + + + buildConfiguration = "Debug" + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + debugServiceExtension = "internal" + allowLocationSimulation = "YES"> + + + + + + + + + + + + diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme index d34e508f438..29c43710dff 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme @@ -1,6 +1,6 @@ + shouldUseLaunchSchemeArgsEnv = "YES"> @@ -48,15 +48,18 @@ ReferencedContainer = "container:SwaggerClient.xcodeproj"> + + @@ -72,10 +75,10 @@ diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SWGViewController.m index 7f8e3d67881..d1ee531e2f0 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -10,7 +10,7 @@ #import #import #import -#import +#import @interface SWGViewController () @@ -22,7 +22,7 @@ { [super viewDidLoad]; - SWGConfiguration *config = [SWGConfiguration sharedConfig]; + SWGDefaultConfiguration *config = [SWGDefaultConfiguration sharedConfig]; config.debug = YES; SWGPetApi *api = [[SWGPetApi alloc] init]; diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist index e21b2835ad7..0c641d12c14 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist @@ -9,7 +9,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/samples/client/petstore/objc/core-data/SwaggerClientTests/Tests/Tests-Info.plist b/samples/client/petstore/objc/core-data/SwaggerClientTests/Tests/Tests-Info.plist index 41520eda89e..169b6f710ec 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClientTests/Tests/Tests-Info.plist +++ b/samples/client/petstore/objc/core-data/SwaggerClientTests/Tests/Tests-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType diff --git a/samples/client/petstore/objc/default/README.md b/samples/client/petstore/objc/default/README.md index c59d5182287..dc09ad22254 100644 --- a/samples/client/petstore/objc/default/README.md +++ b/samples/client/petstore/objc/default/README.md @@ -6,7 +6,8 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi - API version: 1.0.0 - Package version: -- Build package: io.swagger.codegen.languages.ObjcClientCodegen +- Build date: 2016-08-23T10:56:26.470+02:00 +- Build package: class io.swagger.codegen.languages.ObjcClientCodegen ## Requirements @@ -39,7 +40,7 @@ Import the following: ```objc #import -#import +#import // load models #import #import @@ -55,7 +56,7 @@ Import the following: ## Recommendation -It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issues. +It's recommended to create an instance of ApiClient per thread in a multi-threaded environment to avoid any potential issue. ## Getting Started @@ -63,7 +64,7 @@ Please follow the [installation procedure](#installation--usage) and then run th ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -123,12 +124,6 @@ Class | Method | HTTP request | Description ## Documentation For Authorization -## api_key - -- **Type**: API key -- **API key parameter name**: api_key -- **Location**: HTTP header - ## petstore_auth - **Type**: OAuth @@ -138,6 +133,12 @@ Class | Method | HTTP request | Description - **write:pets**: modify pets in your account - **read:pets**: read your pets +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + ## Author diff --git a/samples/client/petstore/objc/default/SwaggerClient.podspec b/samples/client/petstore/objc/default/SwaggerClient.podspec index 2587bd3375a..32d8e336da7 100644 --- a/samples/client/petstore/objc/default/SwaggerClient.podspec +++ b/samples/client/petstore/objc/default/SwaggerClient.podspec @@ -22,7 +22,7 @@ Pod::Spec.new do |s| s.framework = 'SystemConfiguration' s.homepage = "https://github.com/swagger-api/swagger-codegen" - s.license = "Proprietary" + s.license = "Apache License, Version 2.0" s.source = { :git => "https://github.com/swagger-api/swagger-codegen.git", :tag => "#{s.version}" } s.author = { "Swagger" => "apiteam@swagger.io" } @@ -30,8 +30,8 @@ Pod::Spec.new do |s| s.public_header_files = 'SwaggerClient/**/*.h' - s.dependency 'AFNetworking', '~> 3.1' - s.dependency 'JSONModel', '~> 1.4' + s.dependency 'AFNetworking', '~> 3' + s.dependency 'JSONModel', '~> 1.2' s.dependency 'ISO8601', '~> 0.6' end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h index 719d193130b..ade955b27f8 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.h @@ -12,99 +12,139 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - @interface SWGPetApi: NSObject extern NSString* kSWGPetApiErrorDomain; extern NSInteger kSWGPetApiMissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// Add a new pet to the store /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// Deletes a pet /// /// /// @param petId Pet id to delete /// @param apiKey (optional) +/// /// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; + /// Finds Pets by status -/// Multiple status values can be provided with comma separated strings +/// Multiple status values can be provided with comma seperated strings /// /// @param status Status values that need to be considered for filter (optional) (default to available) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid status value" +/// /// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// Finds Pets by tags -/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. +/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// @param tags Tags to filter by (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid tag value" +/// /// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; + /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// @param petId ID of pet that needs to be fetched +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found" +/// /// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; + /// Update an existing pet /// /// /// @param body Pet object that needs to be added to the store (optional) +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Pet not found", /// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// +/// @return +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; + /// 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 (optional) /// @param status Updated status of the pet (optional) +/// /// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// +/// @return +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; + /// uploads an image /// /// /// @param petId ID of pet to update /// @param additionalMetadata Additional data to pass to server (optional) /// @param file file to upload (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// +/// @return +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m index fb0421c81fd..0034dd69fc5 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGPetApi.m @@ -1,11 +1,12 @@ #import "SWGPetApi.h" #import "SWGQueryParamCollection.h" +#import "SWGApiClient.h" #import "SWGPet.h" @interface SWGPetApi () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -19,52 +20,31 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[SWGApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[SWGApiClient sharedClient]]; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static SWGPetApi *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [SWGApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -72,10 +52,11 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; /// /// Add a new pet to the store /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) addPetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -123,19 +104,19 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Deletes a pet /// -/// @param petId Pet id to delete +/// @param petId Pet id to delete /// -/// @param apiKey (optional) +/// @param apiKey (optional) /// -/// code:400 message:"Invalid pet value" --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'petId' is set @@ -200,19 +181,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Finds Pets by status -/// Multiple status values can be provided with comma separated strings -/// @param status Status values that need to be considered for filter (optional, default to available) +/// Multiple status values can be provided with comma seperated strings +/// @param status Status values that need to be considered for filter (optional, default to available) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid status value" -/// @return NSArray* --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"]; @@ -263,19 +242,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler((NSArray*)data, error); } - } - ]; + }]; } /// /// Finds Pets by tags -/// Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. -/// @param tags Tags to filter by (optional) +/// Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. +/// @param tags Tags to filter by (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid tag value" -/// @return NSArray* --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +/// @returns NSArray* +/// +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"]; @@ -326,20 +303,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler((NSArray*)data, error); } - } - ]; + }]; } /// /// Find pet by ID /// Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions -/// @param petId ID of pet that needs to be fetched +/// @param petId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found" -/// @return SWGPet* --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +/// @returns SWGPet* +/// +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler { // verify the required parameter 'petId' is set if (petId == nil) { @@ -378,7 +352,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]]; // Authentication setting - NSArray *authSettings = @[@"api_key", @"petstore_auth"]; + NSArray *authSettings = @[@"petstore_auth", @"api_key"]; id bodyParam = nil; NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; @@ -400,19 +374,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler((SWGPet*)data, error); } - } - ]; + }]; } /// /// Update an existing pet /// -/// @param body Pet object that needs to be added to the store (optional) +/// @param body Pet object that needs to be added to the store (optional) /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Pet not found", -/// code:405 message:"Validation exception" --(NSNumber*) updatePetWithBody: (SWGPet*) body +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"]; @@ -460,21 +432,21 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Updates a pet in the store with form data /// -/// @param petId ID of pet that needs to be updated +/// @param petId ID of pet that needs to be updated /// -/// @param name Updated name of the pet (optional) +/// @param name Updated name of the pet (optional) /// -/// @param status Updated status of the pet (optional) +/// @param status Updated status of the pet (optional) /// -/// code:405 message:"Invalid input" --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +/// @returns void +/// +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler { @@ -543,21 +515,21 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// uploads an image /// -/// @param petId ID of pet to update +/// @param petId ID of pet to update /// -/// @param additionalMetadata Additional data to pass to server (optional) +/// @param additionalMetadata Additional data to pass to server (optional) /// -/// @param file file to upload (optional) +/// @param file file to upload (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +/// @returns void +/// +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler { @@ -624,9 +596,9 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h index 3e101bed9a7..92aeefb176e 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.h @@ -12,54 +12,78 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - @interface SWGStoreApi: NSObject extern NSString* kSWGStoreApiErrorDomain; extern NSInteger kSWGStoreApiMissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// @param orderId ID of the order that needs to be deleted +/// /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// +/// @return +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; + /// Returns pet inventories by status /// Returns a map of status codes to quantities /// +/// /// code:200 message:"successful operation" +/// /// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; + /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// @param orderId ID of pet that needs to be fetched +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid ID supplied", /// code:404 message:"Order not found" +/// /// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + /// Place an order for a pet /// /// /// @param body order placed for purchasing the pet (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid Order" +/// /// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m index b86920b29e2..2a17173f83a 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGStoreApi.m @@ -1,11 +1,12 @@ #import "SWGStoreApi.h" #import "SWGQueryParamCollection.h" +#import "SWGApiClient.h" #import "SWGOrder.h" @interface SWGStoreApi () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -19,52 +20,31 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[SWGApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[SWGApiClient sharedClient]]; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static SWGStoreApi *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [SWGApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -72,11 +52,11 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; /// /// Delete purchase order by ID /// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors -/// @param orderId ID of the order that needs to be deleted +/// @param orderId ID of the order that needs to be deleted /// -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +/// @returns void +/// +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -137,16 +117,15 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Returns pet inventories by status /// Returns a map of status codes to quantities -/// code:200 message:"successful operation" -/// @return NSDictionary* --(NSNumber*) getInventoryWithCompletionHandler: +/// @returns NSDictionary* +/// +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"]; @@ -193,20 +172,17 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler((NSDictionary*)data, error); } - } - ]; + }]; } /// /// Find purchase order by ID /// For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions -/// @param orderId ID of pet that needs to be fetched +/// @param orderId ID of pet that needs to be fetched /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid ID supplied", -/// code:404 message:"Order not found" -/// @return SWGOrder* --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { // verify the required parameter 'orderId' is set if (orderId == nil) { @@ -267,19 +243,17 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler((SWGOrder*)data, error); } - } - ]; + }]; } /// /// Place an order for a pet /// -/// @param body order placed for purchasing the pet (optional) +/// @param body order placed for purchasing the pet (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid Order" -/// @return SWGOrder* --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +/// @returns SWGOrder* +/// +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"]; @@ -327,9 +301,9 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513; if(handler) { handler((SWGOrder*)data, error); } - } - ]; + }]; } + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h index f0b5e37550b..2c35bdcb7b0 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.h @@ -12,90 +12,131 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - @interface SWGUserApi: NSObject extern NSString* kSWGUserApiErrorDomain; extern NSInteger kSWGUserApiMissingParamErrorCode; -+(instancetype) sharedAPI; +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER; /// Create user /// This can only be done by the logged in user. /// /// @param body Created user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// +/// @return +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Creates list of users with given input array /// /// /// @param body List of user object (optional) +/// /// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// +/// @return +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; + /// Delete user /// This can only be done by the logged in user. /// /// @param username The name that needs to be deleted +/// /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; + /// Get user by user name /// /// /// @param username The name that needs to be fetched. Use user1 for testing. +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username supplied", /// code:404 message:"User not found" +/// /// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; + /// Logs user into the system /// /// /// @param username The user name for login (optional) /// @param password The password for login in clear text (optional) +/// /// code:200 message:"successful operation", /// code:400 message:"Invalid username/password supplied" +/// /// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; + /// Logs out current logged in user session /// /// +/// /// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// +/// @return +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; + /// Updated user /// This can only be done by the logged in user. /// /// @param username name that need to be deleted /// @param body Updated user object (optional) +/// /// code:400 message:"Invalid user supplied", /// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// +/// @return +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m index df056030b75..e1acf3af007 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Api/SWGUserApi.m @@ -1,11 +1,12 @@ #import "SWGUserApi.h" #import "SWGQueryParamCollection.h" +#import "SWGApiClient.h" #import "SWGUser.h" @interface SWGUserApi () -@property (nonatomic, strong) NSMutableDictionary *defaultHeaders; +@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders; @end @@ -19,52 +20,31 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; #pragma mark - Initialize methods - (instancetype) init { - self = [super init]; - if (self) { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; - if (config.apiClient == nil) { - config.apiClient = [[SWGApiClient alloc] init]; - } - _apiClient = config.apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; - } - return self; + return [self initWithApiClient:[SWGApiClient sharedClient]]; } -- (id) initWithApiClient:(SWGApiClient *)apiClient { + +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient { self = [super init]; if (self) { _apiClient = apiClient; - _defaultHeaders = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; } return self; } #pragma mark - -+ (instancetype)sharedAPI { - static SWGUserApi *sharedAPI; - static dispatch_once_t once; - dispatch_once(&once, ^{ - sharedAPI = [[self alloc] init]; - }); - return sharedAPI; -} - -(NSString*) defaultHeaderForKey:(NSString*)key { - return self.defaultHeaders[key]; -} - --(void) addHeader:(NSString*)value forKey:(NSString*)key { - [self setDefaultHeaderValue:value forKey:key]; + return self.mutableDefaultHeaders[key]; } -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key { - [self.defaultHeaders setValue:value forKey:key]; + [self.mutableDefaultHeaders setValue:value forKey:key]; } --(NSUInteger) requestQueueSize { - return [SWGApiClient requestQueueSize]; +-(NSDictionary *)defaultHeaders { + return self.mutableDefaultHeaders; } #pragma mark - Api Methods @@ -72,10 +52,11 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; /// /// Create user /// This can only be done by the logged in user. -/// @param body Created user object (optional) +/// @param body Created user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUserWithBody: (SWGUser*) body +/// @returns void +/// +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"]; @@ -123,17 +104,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"]; @@ -181,17 +162,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Creates list of users with given input array /// -/// @param body List of user object (optional) +/// @param body List of user object (optional) /// -/// code:0 message:"successful operation" --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +/// @returns void +/// +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"]; @@ -239,18 +220,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Delete user /// This can only be done by the logged in user. -/// @param username The name that needs to be deleted +/// @param username The name that needs to be deleted /// -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" --(NSNumber*) deleteUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -311,20 +291,17 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Get user by user name /// -/// @param username The name that needs to be fetched. Use user1 for testing. +/// @param username The name that needs to be fetched. Use user1 for testing. /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username supplied", -/// code:404 message:"User not found" -/// @return SWGUser* --(NSNumber*) getUserByNameWithUsername: (NSString*) username +/// @returns SWGUser* +/// +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler { // verify the required parameter 'username' is set if (username == nil) { @@ -385,21 +362,19 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler((SWGUser*)data, error); } - } - ]; + }]; } /// /// Logs user into the system /// -/// @param username The user name for login (optional) +/// @param username The user name for login (optional) /// -/// @param password The password for login in clear text (optional) +/// @param password The password for login in clear text (optional) /// -/// code:200 message:"successful operation", -/// code:400 message:"Invalid username/password supplied" -/// @return NSString* --(NSNumber*) loginUserWithUsername: (NSString*) username +/// @returns NSString* +/// +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"]; @@ -453,15 +428,15 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler((NSString*)data, error); } - } - ]; + }]; } /// /// Logs out current logged in user session /// -/// code:0 message:"successful operation" --(NSNumber*) logoutUserWithCompletionHandler: +/// @returns void +/// +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler { NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"]; @@ -508,20 +483,19 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } /// /// Updated user /// This can only be done by the logged in user. -/// @param username name that need to be deleted +/// @param username name that need to be deleted /// -/// @param body Updated user object (optional) +/// @param body Updated user object (optional) /// -/// code:400 message:"Invalid user supplied", -/// code:404 message:"User not found" --(NSNumber*) updateUserWithUsername: (NSString*) username +/// @returns void +/// +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler { // verify the required parameter 'username' is set @@ -584,9 +558,9 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513; if(handler) { handler(error); } - } - ]; + }]; } + @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.h index 8eac63eefb8..d5b3e9291bc 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.h @@ -1,5 +1,4 @@ #import -#import #import /** diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.m index cec8bdeea27..b544a1dae58 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/JSONValueTransformer+ISO8601.m @@ -1,3 +1,4 @@ +#import #import "JSONValueTransformer+ISO8601.h" @implementation JSONValueTransformer (ISO8601) diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApi.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApi.h index 49364ffb95c..bdc690332f5 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApi.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApi.h @@ -1,6 +1,6 @@ #import -#import "SWGObject.h" -#import "SWGApiClient.h" + +@class SWGApiClient; /** * Swagger Petstore @@ -17,15 +17,13 @@ @protocol SWGApi -@property(nonatomic, assign) SWGApiClient *apiClient; +@property(readonly, nonatomic, strong) SWGApiClient *apiClient; --(id) initWithApiClient:(SWGApiClient *)apiClient; - --(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:"); +-(instancetype) initWithApiClient:(SWGApiClient *)apiClient; -(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; -(NSString*) defaultHeaderForKey:(NSString*)key; --(NSUInteger) requestQueueSize; +-(NSDictionary *)defaultHeaders; @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h index 8869aa5fbe6..cec2428f4b9 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.h @@ -1,13 +1,7 @@ -#import -#import #import -#import "SWGJSONResponseSerializer.h" -#import "SWGJSONRequestSerializer.h" -#import "SWGQueryParamCollection.h" #import "SWGConfiguration.h" #import "SWGResponseDeserializer.h" #import "SWGSanitizer.h" -#import "SWGLogger.h" /** * Swagger Petstore @@ -19,19 +13,20 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ - -#import "SWGCategory.h" -#import "SWGOrder.h" -#import "SWGPet.h" -#import "SWGTag.h" -#import "SWGUser.h" - - - -@class SWGConfiguration; - /** * A key for `NSError` user info dictionaries. * @@ -39,117 +34,49 @@ */ extern NSString *const SWGResponseObjectErrorKey; + @interface SWGApiClient : AFHTTPSessionManager -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, readonly) NSOperationQueue* queue; +@property (nonatomic, strong, readonly) id configuration; -/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one SWGApiClient instance per thread. -@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; @property(nonatomic, strong) id responseDeserializer; @property(nonatomic, strong) id sanitizer; -/** - * Clears Cache - */ -+(void)clearCache; + +@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer *>* requestSerializerForContentType; /** - * Turns on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` + * Gets client singleton instance */ -+(void)setCacheEnabled:(BOOL) enabled; ++ (instancetype) sharedClient; -/** - * Gets the request queue size - * - * @return The size of `queuedRequests` static variable. - */ -+(NSUInteger)requestQueueSize; - -/** - * Sets the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Gets if the client is unreachable - * - * @return The client offline state - */ -+(BOOL) getOfflineState; - -/** - * Sets the client reachability, this may be overridden by the reachability manager if reachability changes - * - * @param status The client reachability status. - */ -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status; - -/** - * Gets the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Gets the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; - -/** - * Generates request id and add it to the queue - * - * @return The next executed request id. - */ -+(NSNumber*) queueRequest; - -/** - * Removes request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * Customizes the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Sets the api client reachability strategy - */ -- (void)configureCacheReachibility; - -/** - * Sets header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; /** * Updates header parameters and query parameters for authentication * - * @param headers The header parameter will be updated, passed by pointer to pointer. + * @param headers The header parameter will be udpated, passed by pointer to pointer. * @param querys The query parameters will be updated, passed by pointer to pointer. * @param authSettings The authentication names NSArray. */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; +- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings; + + +/** + * Initializes the session manager with a configuration. + * + * @param configuration The configuration implementation + */ +- (instancetype)initWithConfiguration:(id)configuration; + +/** +* Initializes the session manager with a configuration and url +* +* @param url The base url +* @param configuration The configuration implementation +*/ +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration; /** * Performs request @@ -165,35 +92,20 @@ extern NSString *const SWGResponseObjectErrorKey; * @param responseContentType Response content-type. * @param completionBlock The block will be executed when the request completed. * - * @return The request id. + * @return The created session task. */ --(NSNumber*) requestWithPath:(NSString*) path - method:(NSString*) method - pathParams:(NSDictionary *) pathParams - queryParams:(NSDictionary*) queryParams - formParams:(NSDictionary *) formParams - files:(NSDictionary *) files - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings:(NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - responseType:(NSString *) responseType - completionBlock:(void (^)(id, NSError *))completionBlock; - -/** - * Custom security policy - * - * @return AFSecurityPolicy - */ -- (AFSecurityPolicy *) customSecurityPolicy; - -/** - * SWGConfiguration return sharedConfig - * - * @return SWGConfiguration - */ -- (SWGConfiguration*) configuration; - +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock; @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m index c3c1bc453c4..f757e139d0e 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGApiClient.m @@ -1,14 +1,13 @@ + +#import "SWGLogger.h" #import "SWGApiClient.h" +#import "SWGJSONRequestSerializer.h" +#import "SWGQueryParamCollection.h" +#import "SWGDefaultConfiguration.h" NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject"; -static NSUInteger requestId = 0; -static bool offlineState = false; -static NSMutableSet * queuedRequests = nil; -static bool cacheEnabled = false; -static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; -static void (^reachabilityChangeBlock)(int); - +static NSString * const kSWGContentDispositionKey = @"Content-Disposition"; static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { if(![response isKindOfClass:[NSHTTPURLResponse class]]) { @@ -19,179 +18,80 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) { static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSDictionary * headers = SWG__headerFieldsForResponse(response); - if(!headers[@"Content-Disposition"]) { + if(!headers[kSWGContentDispositionKey]) { return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; } NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; - NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern - options:NSRegularExpressionCaseInsensitive - error:nil]; - NSString *contentDispositionHeader = headers[@"Content-Disposition"]; - NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader - options:0 - range:NSMakeRange(0, [contentDispositionHeader length])]; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil]; + NSString *contentDispositionHeader = headers[kSWGContentDispositionKey]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])]; return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; } @interface SWGApiClient () -@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders; +@property (nonatomic, strong, readwrite) id configuration; + +@property (nonatomic, strong) NSArray* downloadTaskResponseTypes; @end @implementation SWGApiClient +#pragma mark - Singleton Methods + ++ (instancetype) sharedClient { + static SWGApiClient *sharedClient = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + sharedClient = [[self alloc] init]; + }); + return sharedClient; +} + +#pragma mark - Initialize Methods + - (instancetype)init { - NSString *baseUrl = [[SWGConfiguration sharedConfig] host]; - return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; + return [self initWithConfiguration:[SWGDefaultConfiguration sharedConfig]]; } - (instancetype)initWithBaseURL:(NSURL *)url { + return [self initWithBaseURL:url configuration:[SWGDefaultConfiguration sharedConfig]]; +} + +- (instancetype)initWithConfiguration:(id)configuration { + return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id)configuration { self = [super initWithBaseURL:url]; if (self) { - self.timeoutInterval = 60; - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - self.securityPolicy = [self customSecurityPolicy]; - self.responseDeserializer = [[SWGResponseDeserializer alloc] init]; - self.sanitizer = [[SWGSanitizer alloc] init]; - // configure reachability - [self configureCacheReachibility]; + _configuration = configuration; + _timeoutInterval = 60; + _responseDeserializer = [[SWGResponseDeserializer alloc] init]; + _sanitizer = [[SWGSanitizer alloc] init]; + + _downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"]; + + AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer]; + SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer]; + _requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer, + @"application/x-www-form-urlencoded": afhttpRequestSerializer, + @"multipart/form-data": afhttpRequestSerializer + }; + self.securityPolicy = [self createSecurityPolicy]; + self.responseSerializer = [AFHTTPResponseSerializer serializer]; } return self; } -+ (void)initialize { - if (self == [SWGApiClient class]) { - queuedRequests = [[NSMutableSet alloc] init]; - // initialize URL cache - [self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - } -} +#pragma mark - Task Methods -#pragma mark - Setter Methods - -+ (void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+ (void) setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status { - reachabilityStatus = status; -} - -- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -- (void)setRequestSerializer:(AFHTTPRequestSerializer *)requestSerializer { - [super setRequestSerializer:requestSerializer]; - requestSerializer.timeoutInterval = self.timeoutInterval; -} - -#pragma mark - Cache Methods - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(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]; -} - -#pragma mark - Request Methods - -+(NSUInteger)requestQueueSize { - return [queuedRequests count]; -} - -+(NSNumber*) nextRequestId { - @synchronized(self) { - return @(++requestId); - } -} - -+(NSNumber*) queueRequest { - NSNumber* requestId = [[self class] nextRequestId]; - SWGDebugLog(@"added %@ to request queue", requestId); - [queuedRequests addObject:requestId]; - return requestId; -} - -+(void) cancelRequest:(NSNumber*)requestId { - [queuedRequests removeObject:requestId]; -} - --(Boolean) executeRequestWithId:(NSNumber*) requestId { - NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - return [obj intValue] == [requestId intValue]; - }]; - - if (matchingItems.count == 1) { - SWGDebugLog(@"removed request id %@", requestId); - [queuedRequests removeObject:requestId]; - return YES; - } else { - return NO; - } -} - -#pragma mark - Reachability Methods - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(BOOL) getOfflineState { - return offlineState; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -- (void) configureCacheReachibility { - [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status)); - [SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable]; - - // call the reachability block, if configured - if (reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - - [self.reachabilityManager startMonitoring]; -} - -#pragma mark - Operation Methods - -- (void) operationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } +- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock { + + NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { SWGDebugLogResponse(response, responseObject,request,error); - strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); if(!error) { completionBlock(responseObject, nil); return; @@ -204,20 +104,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); }]; - [op resume]; + + return task; } -- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request - requestId: (NSNumber *) requestId - completionBlock: (void (^)(id, NSError *))completionBlock { - __weak __typeof(self)weakSelf = self; - NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { - __strong __typeof(weakSelf)strongSelf = weakSelf; - if (![strongSelf executeRequestWithId:requestId]) { - return; - } - strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response); +- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock { + + __block NSString * tempFolderPath = [self.configuration.tempFolderPath copy]; + + NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) { SWGDebugLogResponse(response, responseObject,request,error); + if(error) { NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; if (responseObject) { @@ -225,9 +122,11 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { } NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; completionBlock(nil, augmentedError); + return; } - NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory(); - NSString * filename = SWG__fileNameForResponse(response); + + NSString *directory = tempFolderPath ?: NSTemporaryDirectory(); + NSString *filename = SWG__fileNameForResponse(response); NSString *filepath = [directory stringByAppendingPathComponent:filename]; NSURL *file = [NSURL fileURLWithPath:filepath]; @@ -236,53 +135,37 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { completionBlock(file, nil); }]; - [op resume]; + + return task; } -#pragma mark - Perform Request Methods +#pragma mark - Perform Request Methods --(NSNumber*) requestWithPath: (NSString*) path - method: (NSString*) method - pathParams: (NSDictionary *) pathParams - queryParams: (NSDictionary*) queryParams - formParams: (NSDictionary *) formParams - files: (NSDictionary *) files - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - responseType: (NSString *) responseType - completionBlock: (void (^)(id, NSError *))completionBlock { - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [SWGJSONRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else if ([requestContentType isEqualToString:@"multipart/form-data"]) { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - } - else { - self.requestSerializer = [AFHTTPRequestSerializer serializer]; - NSAssert(NO, @"Unsupported request type %@", requestContentType); - } +- (NSURLSessionTask*) requestWithPath: (NSString*) path + method: (NSString*) method + pathParams: (NSDictionary *) pathParams + queryParams: (NSDictionary*) queryParams + formParams: (NSDictionary *) formParams + files: (NSDictionary *) files + body: (id) body + headerParams: (NSDictionary*) headerParams + authSettings: (NSArray *) authSettings + requestContentType: (NSString*) requestContentType + responseContentType: (NSString*) responseContentType + responseType: (NSString *) responseType + completionBlock: (void (^)(id, NSError *))completionBlock { - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [SWGJSONResponseSerializer serializer]; - } else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } + AFHTTPRequestSerializer * requestSerializer = [self requestSerializerForRequestContentType:requestContentType]; + + __weak id sanitizer = self.sanitizer; // sanitize parameters - pathParams = [self.sanitizer sanitizeForSerialization:pathParams]; - queryParams = [self.sanitizer sanitizeForSerialization:queryParams]; - headerParams = [self.sanitizer sanitizeForSerialization:headerParams]; - formParams = [self.sanitizer sanitizeForSerialization:formParams]; + pathParams = [sanitizer sanitizeForSerialization:pathParams]; + queryParams = [sanitizer sanitizeForSerialization:queryParams]; + headerParams = [sanitizer sanitizeForSerialization:headerParams]; + formParams = [sanitizer sanitizeForSerialization:formParams]; if(![body isKindOfClass:[NSData class]]) { - body = [self.sanitizer sanitizeForSerialization:body]; + body = [sanitizer sanitizeForSerialization:body]; } // auth setting @@ -295,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString]; }]; - NSMutableURLRequest * request = nil; - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams]; if ([pathWithQueryParams hasPrefix:@"/"]) { pathWithQueryParams = [pathWithQueryParams substringFromIndex:1]; } NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; + + NSError *requestCreateError = nil; + NSMutableURLRequest * request = nil; if (files.count > 0) { - __weak __typeof(self)weakSelf = self; - request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" - URLString:urlString - parameters:nil - constructingBodyWithBlock:^(id formData) { + request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id formData) { [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { - NSString *objString = [weakSelf.sanitizer parameterToString:obj]; + NSString *objString = [sanitizer parameterToString:obj]; NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding]; [formData appendPartWithFormData:data name:key]; }]; @@ -318,76 +198,73 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSURL *filePath = (NSURL *)obj; [formData appendPartWithFileURL:filePath name:key error:nil]; }]; - } error:nil]; + } error:&requestCreateError]; } else { if (formParams) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:formParams - error:nil]; + request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError]; } if (body) { - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; + request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError]; } } - - // request cache - BOOL hasHeaderParams = [headerParams count] > 0; - if (offlineState) { - SWGDebugLog(@"%@ cache forced", resourcePath); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - SWGDebugLog(@"%@ cache enabled", resourcePath); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - SWGDebugLog(@"%@ cache disabled", resourcePath); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + if(!request) { + completionBlock(nil, requestCreateError); + return nil; } - if (hasHeaderParams){ + if ([headerParams count] > 0){ for(NSString * key in [headerParams keyEnumerator]){ [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; } } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + [requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; [self postProcessRequest:request]; - NSNumber* requestId = [SWGApiClient queueRequest]; - if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) { - [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + + NSURLSessionTask *task = nil; + + if ([self.downloadTaskResponseTypes containsObject:responseType]) { + task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { completionBlock(data, error); }]; - } - else { - [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + } else { + __weak typeof(self) weakSelf = self; + task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) { NSError * serializationError; - id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError]; + id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError]; + if(!response && !error){ error = serializationError; } completionBlock(response, error); }]; } - return requestId; + + [task resume]; + + return task; +} + +-(AFHTTPRequestSerializer *)requestSerializerForRequestContentType:(NSString *)requestContentType { + AFHTTPRequestSerializer * serializer = self.requestSerializerForContentType[requestContentType]; + if(!serializer) { + NSAssert(NO, @"Unsupported request content type %@", requestContentType); + serializer = [AFHTTPRequestSerializer serializer]; + } + serializer.timeoutInterval = self.timeoutInterval; + return serializer; } //Added for easier override to modify request -(void)postProcessRequest:(NSMutableURLRequest *)request { - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; + } #pragma mark - -- (NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { +- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams { if(queryParams.count == 0) { return path; } @@ -445,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { /** * Update header and query params based on authentication settings */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { +- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings { if ([authSettings count] == 0) { return; @@ -455,10 +330,11 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - NSDictionary* configurationAuthSettings = [[self configuration] authSettings]; + + id config = self.configuration; for (NSString *auth in authSettings) { - NSDictionary *authSetting = configurationAuthSettings[auth]; + NSDictionary *authSetting = config.authSettings[auth]; + if(!authSetting) { // auth setting is set only if the key is non-empty continue; } @@ -476,10 +352,10 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; } -- (AFSecurityPolicy *) customSecurityPolicy { +- (AFSecurityPolicy *) createSecurityPolicy { AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone]; - SWGConfiguration *config = [self configuration]; + id config = self.configuration; if (config.sslCaCert) { NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert]; @@ -497,8 +373,4 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) { return securityPolicy; } -- (SWGConfiguration*) configuration { - return [SWGConfiguration sharedConfig]; -} - @end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.h new file mode 100644 index 00000000000..6c50d3750b4 --- /dev/null +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.h @@ -0,0 +1,14 @@ +/** The `SWGBasicAuthTokenProvider` class creates a basic auth token from username and password. + * + * NOTE: This class is auto generated by the swagger code generator program. + * https://github.com/swagger-api/swagger-codegen + * Do not edit the class manually. + */ + +#import + +@interface SWGBasicAuthTokenProvider : NSObject + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password; + +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.m new file mode 100644 index 00000000000..3788009ec58 --- /dev/null +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGBasicAuthTokenProvider.m @@ -0,0 +1,19 @@ +#import "SWGBasicAuthTokenProvider.h" + +@implementation SWGBasicAuthTokenProvider + ++ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password { + + // return empty string if username and password are empty + if (username.length == 0 && password.length == 0){ + return @""; + } + + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +@end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h index 81d33fda278..864d87d2535 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.h @@ -1,6 +1,6 @@ #import -#import "SWGApiClient.h" -#import "SWGLogger.h" + +@class SWGLogger; /** * Swagger Petstore @@ -12,160 +12,89 @@ * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. */ +static NSString * const kSWGAPIVersion = @"1.0.0"; -@class SWGApiClient; - -@interface SWGConfiguration : NSObject +@protocol SWGConfiguration /** - * Default api logger + * Api logger */ -@property (nonatomic, strong) SWGLogger * logger; +@property (readonly, nonatomic) SWGLogger *logger; /** - * Default api client + * Base url */ -@property (nonatomic) SWGApiClient *apiClient; - -/** - * Default base url - */ -@property (nonatomic) NSString *host; +@property (readonly, nonatomic) NSString *host; /** * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. */ -@property (readonly, nonatomic, strong) NSDictionary *apiKey; +@property (readonly, nonatomic) NSDictionary *apiKey; /** * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. */ -@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; +@property (readonly, nonatomic) NSDictionary *apiKeyPrefix; /** * Username for HTTP Basic Authentication */ - @property (nonatomic) NSString *username; +@property (readonly, nonatomic) NSString *username; /** * Password for HTTP Basic Authentication */ -@property (nonatomic) NSString *password; +@property (readonly, nonatomic) NSString *password; /** * Access token for OAuth */ -@property (nonatomic) NSString *accessToken; +@property (readonly, nonatomic) NSString *accessToken; /** * Temp folder for file download */ -@property (nonatomic) NSString *tempFolderPath; +@property (readonly, nonatomic) NSString *tempFolderPath; /** * Debug switch, default false */ -@property (nonatomic) BOOL debug; - -/** - * Gets configuration singleton instance - */ -+ (instancetype) sharedConfig; +@property (readonly, nonatomic) BOOL debug; /** * SSL/TLS verification * Set this to NO to skip verifying SSL certificate when calling API from https server */ -@property (nonatomic) BOOL verifySSL; +@property (readonly, nonatomic) BOOL verifySSL; /** * SSL/TLS verification * Set this to customize the certificate file to verify the peer */ -@property (nonatomic) NSString *sslCaCert; +@property (readonly, nonatomic) NSString *sslCaCert; /** - * Sets API key - * - * To remove a apiKey for an identifier, just set the apiKey to nil. - * - * @param apiKey API key or token. - * @param identifier API key identifier (authentication schema). - * + * Authentication Settings */ -- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; - -/** - * Removes api key - * - * @param identifier API key identifier. - */ -- (void) removeApiKey:(NSString *)identifier; - -/** - * Sets the prefix for API key - * - * @param prefix API key prefix. - * @param identifier API key identifier. - */ -- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; - -/** - * Removes api key prefix - * - * @param identifier API key identifier. - */ -- (void) removeApiKeyPrefix:(NSString *)identifier; - -/** - * Gets API key (with prefix if set) - */ -- (NSString *) getApiKeyWithPrefix:(NSString *) key; - -/** - * Gets Basic Auth token - */ -- (NSString *) getBasicAuthToken; - -/** - * Gets OAuth access token - */ -- (NSString *) getAccessToken; - -/** - * Gets Authentication Settings - */ -- (NSDictionary *) authSettings; +@property (readonly, nonatomic) NSDictionary *authSettings; /** * Default headers for all services */ @property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; -/** -* Removes header from defaultHeaders -* -* @param key Header name. -*/ --(void) removeDefaultHeaderForKey:(NSString*)key; - -/** -* Sets the header for key -* -* @param value Value for header name -* @param key Header name -*/ --(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; - -/** -* @param key Header key name. -*/ --(NSString*) defaultHeaderForKey:(NSString*)key; - -@end +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.h new file mode 100644 index 00000000000..48cedd5d558 --- /dev/null +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.h @@ -0,0 +1,177 @@ +#import +#import "SWGConfiguration.h" + +/** +* Swagger Petstore +* This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters +* +* OpenAPI spec version: 1.0.0 +* Contact: apiteam@wordnik.com +* +* NOTE: This class is auto generated by the swagger code generator program. +* https://github.com/swagger-api/swagger-codegen.git +* Do not edit the class manually. +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +@class SWGApiClient; + +@interface SWGDefaultConfiguration : NSObject + + +/** + * Default api logger + */ +@property (nonatomic, strong) SWGLogger * logger; + +/** + * Default base url + */ +@property (nonatomic) NSString *host; + +/** + * Api key values for Api Key type Authentication + * + * To add or remove api key, use `setApiKey:forApiKeyIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKey; + +/** + * Api key prefix values to be prepend to the respective api key + * + * To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`. + */ +@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; + +/** + * Username for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Access token for OAuth + */ +@property (nonatomic) NSString *accessToken; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Gets configuration singleton instance + */ ++ (instancetype) sharedConfig; + +/** + * SSL/TLS verification + * Set this to NO to skip verifying SSL certificate when calling API from https server + */ +@property (nonatomic) BOOL verifySSL; + +/** + * SSL/TLS verification + * Set this to customize the certificate file to verify the peer + */ +@property (nonatomic) NSString *sslCaCert; + +/** + * Sets API key + * + * To remove a apiKey for an identifier, just set the apiKey to nil. + * + * @param apiKey API key or token. + * @param identifier API key identifier (authentication schema). + * + */ +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier; + +/** + * Removes api key + * + * @param identifier API key identifier. + */ +- (void) removeApiKey:(NSString *)identifier; + +/** + * Sets the prefix for API key + * + * @param apiKeyPrefix API key prefix. + * @param identifier API key identifier. + */ +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier; + +/** + * Removes api key prefix + * + * @param identifier API key identifier. + */ +- (void) removeApiKeyPrefix:(NSString *)identifier; + +/** + * Gets API key (with prefix if set) + */ +- (NSString *) getApiKeyWithPrefix:(NSString *) key; + +/** + * Gets Basic Auth token + */ +- (NSString *) getBasicAuthToken; + +/** + * Gets OAuth access token + */ +- (NSString *) getAccessToken; + +/** + * Gets Authentication Settings + */ +- (NSDictionary *) authSettings; + +/** +* Default headers for all services +*/ +@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders; + +/** +* Removes header from defaultHeaders +* +* @param Header name. +*/ +-(void) removeDefaultHeaderForKey:(NSString*)key; + +/** +* Sets the header for key +* +* @param value Value for header name +* @param key Header name +*/ +-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key; + +/** +* @param Header key name. +*/ +-(NSString*) defaultHeaderForKey:(NSString*)key; + +@end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m similarity index 72% rename from samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m rename to samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m index b21290068a1..705580e9a54 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGConfiguration.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGDefaultConfiguration.m @@ -1,6 +1,8 @@ -#import "SWGConfiguration.h" +#import "SWGDefaultConfiguration.h" +#import "SWGBasicAuthTokenProvider.h" +#import "SWGLogger.h" -@interface SWGConfiguration () +@interface SWGDefaultConfiguration () @property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders; @property (nonatomic, strong) NSMutableDictionary *mutableApiKey; @@ -8,12 +10,12 @@ @end -@implementation SWGConfiguration +@implementation SWGDefaultConfiguration #pragma mark - Singleton Methods + (instancetype) sharedConfig { - static SWGConfiguration *shardConfig = nil; + static SWGDefaultConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; @@ -26,17 +28,16 @@ - (instancetype) init { self = [super init]; if (self) { - self.apiClient = nil; - self.host = @"http://petstore.swagger.io/v2"; - self.username = @""; - self.password = @""; - self.accessToken= @""; - self.verifySSL = YES; - self.mutableApiKey = [NSMutableDictionary dictionary]; - self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders = [NSMutableDictionary dictionary]; - self.mutableDefaultHeaders[@"User-Agent"] = [NSString stringWithFormat:@"Swagger-Codegen/1.0.0/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]; - self.logger = [SWGLogger sharedLogger]; + _host = @"http://petstore.swagger.io/v2"; + _username = @""; + _password = @""; + _accessToken= @""; + _verifySSL = YES; + _mutableApiKey = [NSMutableDictionary dictionary]; + _mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + _mutableDefaultHeaders = [NSMutableDictionary dictionary]; + + _logger = [SWGLogger sharedLogger]; } return self; } @@ -58,16 +59,9 @@ } - (NSString *) getBasicAuthToken { - // return empty string if username and password are empty - if (self.username.length == 0 && self.password.length == 0){ - return @""; - } - NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; - NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; - basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; - - return basicAuthCredentials; + NSString *basicAuthToken = [SWGBasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password]; + return basicAuthToken; } - (NSString *) getAccessToken { @@ -110,13 +104,6 @@ - (NSDictionary *) authSettings { return @{ - @"api_key": - @{ - @"type": @"api_key", - @"in": @"header", - @"key": @"api_key", - @"value": [self getApiKeyWithPrefix:@"api_key"] - }, @"petstore_auth": @{ @"type": @"oauth", @@ -124,6 +111,13 @@ @"key": @"Authorization", @"value": [self getAccessToken] }, + @"api_key": + @{ + @"type": @"api_key", + @"in": @"header", + @"key": @"api_key", + @"value": [self getApiKeyWithPrefix:@"api_key"] + }, }; } @@ -135,8 +129,6 @@ self.logger.enabled = debug; } - - - (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key { if(!value) { [self.mutableDefaultHeaders removeObjectForKey:key]; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGJSONResponseSerializer.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGJSONResponseSerializer.m deleted file mode 100644 index 73c696d341a..00000000000 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGJSONResponseSerializer.m +++ /dev/null @@ -1,39 +0,0 @@ -#import "SWGJSONResponseSerializer.h" - -@implementation SWGJSONResponseSerializer - -/// -/// When customize a response serializer, -/// the serializer must conform the protocol `AFURLResponseSerialization` -/// and implements the protocol method `responseObjectForResponse:error:` -/// -/// @param response The response to be processed. -/// @param data The response data to be decoded. -/// @param error The error that occurred while attempting to decode the response data. -/// -/// @return The object decoded from the specified response data. -/// -- (id) responseObjectForResponse:(NSURLResponse *)response - data:(NSData *)data - error:(NSError *__autoreleasing *)error { - NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error]; - - // if response data is not a valid json, return string of data. - if ([self isParseError:*error]) { - *error = nil; - NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; - return responseString; - } - - return responseJson; -} - --(BOOL)isParseError:(NSError *)error { - return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840; -} - -+ (instancetype)serializer { - return [self serializerWithReadingOptions:NSJSONReadingAllowFragments]; -} - -@end diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGLogger.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGLogger.m index 322ae9678d7..2a96e5ec54d 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGLogger.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGLogger.m @@ -17,8 +17,7 @@ #pragma mark - Log Methods -- (void)debugLog:(NSString *)method - message:(NSString *)format, ... { +- (void)debugLog:(NSString *)method message:(NSString *)format, ... { if (!self.isEnabled) { return; } diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGObject.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGObject.m index 8085c404f7e..db970d34669 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGObject.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGObject.m @@ -2,6 +2,35 @@ @implementation SWGObject +/** + * Workaround for JSONModel multithreading issues + * https://github.com/icanzilb/JSONModel/issues/441 + */ +- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err { + static NSMutableSet *classNames; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + classNames = [NSMutableSet new]; + }); + + BOOL initSync; + @synchronized([self class]) + { + NSString *className = NSStringFromClass([self class]); + initSync = ![classNames containsObject:className]; + if(initSync) + { + [classNames addObject:className]; + self = [super initWithDictionary:dict error:err]; + } + } + if(!initSync) + { + self = [super initWithDictionary:dict error:err]; + } + return self; +} + /** * Gets the string presentation of the object. * This method will be called when logging model object using `NSLog`. diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m index 83303045185..9aa8a091762 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m @@ -5,11 +5,15 @@ @synthesize values = _values; @synthesize format = _format; -- (id) initWithValuesAndFormat: (NSArray*) values - format: (NSString*) format { - _values = values; - _format = format; +- (id)initWithValuesAndFormat:(NSArray *)values + format:(NSString *)format { + self = [super init]; + if (self) { + _values = values; + _format = format; + } + return self; } diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m index 6ac9f75e818..46d4b460fc7 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGResponseDeserializer.m @@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; @property (nonatomic, strong) NSNumberFormatter* numberFormatter; @property (nonatomic, strong) NSArray *primitiveTypes; @property (nonatomic, strong) NSArray *basicReturnTypes; +@property (nonatomic, strong) NSArray *dataReturnTypes; @property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression; @property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression; @@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; formatter.numberStyle = NSNumberFormatterDecimalStyle; _numberFormatter = formatter; _primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; - _basicReturnTypes = @[@"NSObject", @"id", @"NSData"]; + _basicReturnTypes = @[@"NSObject", @"id"]; + _dataReturnTypes = @[@"NSData"]; + _arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>" options:NSRegularExpressionCaseInsensitive error:nil]; @@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; #pragma mark - Deserialize methods - (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error { - // return nil if data is nil or className is nil - if (!data || !className || [data isKindOfClass:[NSNull class]]) { + if (!data || !className) { return nil; } - // remove "*" from className, if ends with "*" if ([className hasSuffix:@"*"]) { className = [className substringToIndex:[className length] - 1]; } + if([self.dataReturnTypes containsObject:className]) { + return data; + } + id jsonData = nil; + if([data isKindOfClass:[NSData class]]) { + jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error]; + } else { + jsonData = data; + } + if(!jsonData) { + jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + } else if([jsonData isKindOfClass:[NSNull class]]) { + return nil; + } + // pure object if ([self.basicReturnTypes containsObject:className]) { - return data; + return jsonData; } // primitives if ([self.primitiveTypes containsObject:className]) { - return [self deserializePrimitiveValue:data class:className error:error]; + return [self deserializePrimitiveValue:jsonData class:className error:error]; } NSTextCheckingResult *match = nil; @@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; + return [self deserializeArrayValue:jsonData innerType:innerType error:error]; } // list of primitives match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]]; - return [self deserializeArrayValue:data innerType:innerType error:error]; + return [self deserializeArrayValue:jsonData innerType:innerType error:error]; } // map match = [self.dictPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; + return [self deserializeDictionaryValue:jsonData valueType:valueType error:error]; } match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range]; if (match) { NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]]; - return [self deserializeDictionaryValue:data valueType:valueType error:error]; + return [self deserializeDictionaryValue:jsonData valueType:valueType error:error]; } // model Class ModelClass = NSClassFromString(className); if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { - return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error]; + return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error]; } if(error) { - *error = [self unknownResponseErrorWithExpectedType:className data:data]; + *error = [self unknownResponseErrorWithExpectedType:className data:jsonData]; } return nil; } @@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528; - (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error { if ([className isEqualToString:@"NSString"]) { - return [NSString stringWithString:data]; + return [NSString stringWithFormat:@"%@",data]; } else if ([className isEqualToString:@"NSDate"]) { return [self deserializeDateValue:data error:error]; diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.h b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.h index b7cd3a6cb18..28e84d83714 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.h +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.h @@ -15,6 +15,8 @@ extern NSString * SWGPercentEscapedStringFromString(NSString *string); +extern NSString * const kSWGApplicationJSONType; + @protocol SWGSanitizer /** diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.m index a74f72afbe3..49ff6ed014a 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGSanitizer.m @@ -3,6 +3,8 @@ #import "SWGQueryParamCollection.h" #import +NSString * const kSWGApplicationJSONType = @"application/json"; + NSString * SWGPercentEscapedStringFromString(NSString *string) { static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@"; static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;="; @@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) { @implementation SWGSanitizer -static NSString * kApplicationJSONType = @"application/json"; - -(instancetype)init { self = [super init]; if ( !self ) { @@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json"; NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; for (NSString *string in accepts) { if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) { - return kApplicationJSONType; + return kSWGApplicationJSONType; } [lowerAccepts addObject:[string lowercaseString]]; } @@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json"; */ - (NSString *) selectHeaderContentType:(NSArray *)contentTypes { if (contentTypes.count == 0) { - return kApplicationJSONType; + return kSWGApplicationJSONType; } NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; for (NSString *string in contentTypes) { if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){ - return kApplicationJSONType; + return kSWGApplicationJSONType; } [lowerContentTypes addObject:[string lowercaseString]]; } diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj index 25e7b5a2d2c..1cf9ba5a2c3 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/project.pbxproj @@ -232,12 +232,13 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */; buildPhases = ( - 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */, + 799E7E29D924C30424DFBA28 /* [CP] Check Pods Manifest.lock */, 6003F586195388D20070C39A /* Sources */, 6003F587195388D20070C39A /* Frameworks */, 6003F588195388D20070C39A /* Resources */, - 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */, - 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */, + 429AF5C69E165ED75311B4B0 /* [CP] Copy Pods Resources */, + 183E54C09C54DAEB54B2546F /* [CP] Embed Pods Frameworks */, + DA8DD6AAE903F2CD38F2D9D5 /* Embed Pods Frameworks */, ); buildRules = ( ); @@ -252,12 +253,13 @@ isa = PBXNativeTarget; buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */; buildPhases = ( - 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */, + 7B069562A9F91E498732474F /* [CP] Check Pods Manifest.lock */, 6003F5AA195388D20070C39A /* Sources */, 6003F5AB195388D20070C39A /* Frameworks */, 6003F5AC195388D20070C39A /* Resources */, - E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */, - 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */, + E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */, + 111D7956304BD6E860AA8709 /* [CP] Embed Pods Frameworks */, + FD42985CC653969FE997DEC9 /* Embed Pods Frameworks */, ); buildRules = ( ); @@ -276,7 +278,7 @@ isa = PBXProject; attributes = { CLASSPREFIX = SWG; - LastUpgradeCheck = 0510; + LastUpgradeCheck = 0730; ORGANIZATIONNAME = geekerzp; }; buildConfigurationList = 6003F585195388D10070C39A /* Build configuration list for PBXProject "SwaggerClient" */; @@ -321,14 +323,14 @@ /* End PBXResourcesBuildPhase section */ /* Begin PBXShellScriptBuildPhase section */ - 111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = { + 111D7956304BD6E860AA8709 /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -336,14 +338,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = { + 183E54C09C54DAEB54B2546F /* [CP] Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Embed Pods Frameworks"; + name = "[CP] Embed Pods Frameworks"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -351,14 +353,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; - 429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = { + 429AF5C69E165ED75311B4B0 /* [CP] Copy Pods Resources */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -366,14 +368,14 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n"; showEnvVarsInLog = 0; }; - 799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = { + 799E7E29D924C30424DFBA28 /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -381,14 +383,14 @@ 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; }; - 7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = { + 7B069562A9F91E498732474F /* [CP] Check Pods Manifest.lock */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Check Pods Manifest.lock"; + name = "[CP] Check Pods Manifest.lock"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -396,14 +398,29 @@ 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; }; - E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = { + DA8DD6AAE903F2CD38F2D9D5 /* Embed Pods Frameworks */ = { isa = PBXShellScriptBuildPhase; buildActionMask = 2147483647; files = ( ); inputPaths = ( ); - name = "📦 Copy Pods Resources"; + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "[CP] Copy Pods Resources"; outputPaths = ( ); runOnlyForDeploymentPostprocessing = 0; @@ -411,6 +428,21 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-resources.sh\"\n"; showEnvVarsInLog = 0; }; + FD42985CC653969FE997DEC9 /* Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Embed Pods Frameworks"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -487,6 +519,7 @@ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; COPY_PHASE_STRIP = NO; + ENABLE_TESTABILITY = YES; GCC_C_LANGUAGE_STANDARD = gnu99; GCC_DYNAMIC_NO_PIC = NO; GCC_OPTIMIZATION_LEVEL = 0; @@ -551,6 +584,7 @@ GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch"; INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist"; MODULE_NAME = ExampleApp; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; @@ -566,6 +600,7 @@ GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch"; INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist"; MODULE_NAME = ExampleApp; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = app; }; @@ -587,6 +622,7 @@ "$(inherited)", ); INFOPLIST_FILE = "Tests/Tests-Info.plist"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = xctest; }; @@ -604,6 +640,7 @@ GCC_PRECOMPILE_PREFIX_HEADER = YES; GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch"; INFOPLIST_FILE = "Tests/Tests-Info.plist"; + PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}"; PRODUCT_NAME = "$(TARGET_NAME)"; WRAPPER_EXTENSION = xctest; }; diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme index 5c68411bb2d..24c1ef20c79 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/All Tests.xcscheme @@ -1,11 +1,17 @@ - + + buildForProfiling = "YES" + buildForArchiving = "YES" + buildForAnalyzing = "YES"> + buildConfiguration = "Debug" + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + shouldUseLaunchSchemeArgsEnv = "YES"> - + + + + buildConfiguration = "Debug" + selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" + selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" + launchStyle = "0" + useCustomWorkingDirectory = "NO" + ignoresPersistentStateOnLaunch = "NO" + debugDocumentVersioning = "YES" + debugServiceExtension = "internal" + allowLocationSimulation = "YES"> + + + + + + + + + + + + diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme index d34e508f438..29c43710dff 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient.xcodeproj/xcshareddata/xcschemes/SwaggerClient-Example.xcscheme @@ -1,6 +1,6 @@ + shouldUseLaunchSchemeArgsEnv = "YES"> @@ -48,15 +48,18 @@ ReferencedContainer = "container:SwaggerClient.xcodeproj"> + + @@ -72,10 +75,10 @@ diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SWGViewController.m b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SWGViewController.m index 7f8e3d67881..d1ee531e2f0 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SWGViewController.m +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SWGViewController.m @@ -10,7 +10,7 @@ #import #import #import -#import +#import @interface SWGViewController () @@ -22,7 +22,7 @@ { [super viewDidLoad]; - SWGConfiguration *config = [SWGConfiguration sharedConfig]; + SWGDefaultConfiguration *config = [SWGDefaultConfiguration sharedConfig]; config.debug = YES; SWGPetApi *api = [[SWGPetApi alloc] init]; diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist index e21b2835ad7..0c641d12c14 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist +++ b/samples/client/petstore/objc/default/SwaggerClientTests/SwaggerClient/SwaggerClient-Info.plist @@ -9,7 +9,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundleName diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/DeserializationTest.m b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/DeserializationTest.m index 6077ab42981..d24f349419c 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/DeserializationTest.m +++ b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/DeserializationTest.m @@ -250,4 +250,16 @@ XCTAssertTrue([result isEqual:@NO]); } +- (void)testDeserializeStringData { + NSString *data = @"1233"; + + NSError* error; + NSString * returnValue = [apiClient.responseDeserializer deserialize:[data dataUsingEncoding:NSUTF8StringEncoding] class:@"NSString*" error:&error]; + XCTAssertTrue([returnValue isEqual:data]); + + NSNumber *returnNumber = [apiClient.responseDeserializer deserialize:[data dataUsingEncoding:NSUTF8StringEncoding] class:@"NSNumber*" error:&error]; + XCTAssertTrue([returnNumber isEqual:@1233]); +} + + @end diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/SWGApiClientTest.m b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/SWGApiClientTest.m index 335e4f50bb2..7e78cae4840 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/SWGApiClientTest.m +++ b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/SWGApiClientTest.m @@ -2,6 +2,9 @@ #import #import #import +#import +#import +#import @interface SWGApiClientTest : XCTestCase @@ -86,7 +89,7 @@ } - (void)testConfiguration { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; + SWGDefaultConfiguration *config = [SWGDefaultConfiguration sharedConfig]; [config setApiKey:@"123456" forApiKeyIdentifier:@"api_key"]; [config setApiKeyPrefix:@"PREFIX" forApiKeyPrefixIdentifier:@"api_key"]; config.username = @"test_username"; @@ -113,7 +116,7 @@ } - (void)testGetBasicAuthToken { - SWGConfiguration *config = [SWGConfiguration sharedConfig]; + SWGDefaultConfiguration *config = [SWGDefaultConfiguration sharedConfig]; config.username = @"test_username"; config.password = @"test_password"; diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/Tests-Info.plist b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/Tests-Info.plist index 41520eda89e..169b6f710ec 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/Tests-Info.plist +++ b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/Tests-Info.plist @@ -7,7 +7,7 @@ CFBundleExecutable ${EXECUTABLE_NAME} CFBundleIdentifier - org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier} + $(PRODUCT_BUNDLE_IDENTIFIER) CFBundleInfoDictionaryVersion 6.0 CFBundlePackageType diff --git a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/UserApiTest.m b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/UserApiTest.m index e9123647b75..dd895d705aa 100644 --- a/samples/client/petstore/objc/default/SwaggerClientTests/Tests/UserApiTest.m +++ b/samples/client/petstore/objc/default/SwaggerClientTests/Tests/UserApiTest.m @@ -30,14 +30,7 @@ if (!output) { XCTFail(@"response can't be nil"); } - - NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"logged in user" - options:0 - error:nil]; - NSTextCheckingResult *match = [regex firstMatchInString:output - options:0 - range:NSMakeRange(0, [output length])]; - XCTAssertNotNil(match); + XCTAssertTrue([output rangeOfString:@"logged in user"].location != NSNotFound); [expectation fulfill]; }]; diff --git a/samples/client/petstore/objc/default/docs/SWGPetApi.md b/samples/client/petstore/objc/default/docs/SWGPetApi.md index 9971ffff450..48048c3816e 100644 --- a/samples/client/petstore/objc/default/docs/SWGPetApi.md +++ b/samples/client/petstore/objc/default/docs/SWGPetApi.md @@ -16,7 +16,7 @@ Method | HTTP request | Description # **addPet** ```objc --(NSNumber*) addPetWithBody: (SWGPet*) body +-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; ``` @@ -26,7 +26,7 @@ Add a new pet to the store ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -68,7 +68,7 @@ void (empty response body) # **deletePet** ```objc --(NSNumber*) deletePetWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId apiKey: (NSString*) apiKey completionHandler: (void (^)(NSError* error)) handler; ``` @@ -79,7 +79,7 @@ Deletes a pet ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -124,7 +124,7 @@ void (empty response body) # **findPetsByStatus** ```objc --(NSNumber*) findPetsByStatusWithStatus: (NSArray*) status +-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray*) status completionHandler: (void (^)(NSArray* output, NSError* error)) handler; ``` @@ -134,7 +134,7 @@ Multiple status values can be provided with comma separated strings ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -179,7 +179,7 @@ Name | Type | Description | Notes # **findPetsByTags** ```objc --(NSNumber*) findPetsByTagsWithTags: (NSArray*) tags +-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray*) tags completionHandler: (void (^)(NSArray* output, NSError* error)) handler; ``` @@ -189,7 +189,7 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -234,7 +234,7 @@ Name | Type | Description | Notes # **getPetById** ```objc --(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId completionHandler: (void (^)(SWGPet* output, NSError* error)) handler; ``` @@ -244,16 +244,16 @@ Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error cond ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; + +// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) +[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed //[apiConfig setApiKeyPrefix:@"Bearer" forApiKeyIdentifier:@"api_key"]; -// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) -[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; - NSNumber* petId = @789; // ID of pet that needs to be fetched @@ -283,7 +283,7 @@ Name | Type | Description | Notes ### Authorization -[api_key](../README.md#api_key), [petstore_auth](../README.md#petstore_auth) +[petstore_auth](../README.md#petstore_auth), [api_key](../README.md#api_key) ### HTTP request headers @@ -294,7 +294,7 @@ Name | Type | Description | Notes # **updatePet** ```objc --(NSNumber*) updatePetWithBody: (SWGPet*) body +-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body completionHandler: (void (^)(NSError* error)) handler; ``` @@ -304,7 +304,7 @@ Update an existing pet ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -346,7 +346,7 @@ void (empty response body) # **updatePetWithForm** ```objc --(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId +-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId name: (NSString*) name status: (NSString*) status completionHandler: (void (^)(NSError* error)) handler; @@ -358,7 +358,7 @@ Updates a pet in the store with form data ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; @@ -406,7 +406,7 @@ void (empty response body) # **uploadFile** ```objc --(NSNumber*) uploadFileWithPetId: (NSNumber*) petId +-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId additionalMetadata: (NSString*) additionalMetadata file: (NSURL*) file completionHandler: (void (^)(NSError* error)) handler; @@ -418,7 +418,7 @@ uploads an image ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth) [apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"]; diff --git a/samples/client/petstore/objc/default/docs/SWGStoreApi.md b/samples/client/petstore/objc/default/docs/SWGStoreApi.md index 12bcef79a40..3124b5c6458 100644 --- a/samples/client/petstore/objc/default/docs/SWGStoreApi.md +++ b/samples/client/petstore/objc/default/docs/SWGStoreApi.md @@ -12,7 +12,7 @@ Method | HTTP request | Description # **deleteOrder** ```objc --(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId +-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId completionHandler: (void (^)(NSError* error)) handler; ``` @@ -59,7 +59,7 @@ No authorization required # **getInventory** ```objc --(NSNumber*) getInventoryWithCompletionHandler: +-(NSURLSessionTask*) getInventoryWithCompletionHandler: (void (^)(NSDictionary* output, NSError* error)) handler; ``` @@ -69,7 +69,7 @@ Returns a map of status codes to quantities ### Example ```objc -SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig]; +SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig]; // Configure API key authorization: (authentication scheme: api_key) [apiConfig setApiKey:@"YOUR_API_KEY" forApiKeyIdentifier:@"api_key"]; @@ -112,7 +112,7 @@ This endpoint does not need any parameter. # **getOrderById** ```objc --(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId +-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; ``` @@ -162,7 +162,7 @@ No authorization required # **placeOrder** ```objc --(NSNumber*) placeOrderWithBody: (SWGOrder*) body +-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler; ``` diff --git a/samples/client/petstore/objc/default/docs/SWGUserApi.md b/samples/client/petstore/objc/default/docs/SWGUserApi.md index c7a62f3b3c4..bffba171129 100644 --- a/samples/client/petstore/objc/default/docs/SWGUserApi.md +++ b/samples/client/petstore/objc/default/docs/SWGUserApi.md @@ -16,7 +16,7 @@ Method | HTTP request | Description # **createUser** ```objc --(NSNumber*) createUserWithBody: (SWGUser*) body +-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; ``` @@ -63,7 +63,7 @@ No authorization required # **createUsersWithArrayInput** ```objc --(NSNumber*) createUsersWithArrayInputWithBody: (NSArray*) body +-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; ``` @@ -110,7 +110,7 @@ No authorization required # **createUsersWithListInput** ```objc --(NSNumber*) createUsersWithListInputWithBody: (NSArray*) body +-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray*) body completionHandler: (void (^)(NSError* error)) handler; ``` @@ -157,7 +157,7 @@ No authorization required # **deleteUser** ```objc --(NSNumber*) deleteUserWithUsername: (NSString*) username +-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username completionHandler: (void (^)(NSError* error)) handler; ``` @@ -204,7 +204,7 @@ No authorization required # **getUserByName** ```objc --(NSNumber*) getUserByNameWithUsername: (NSString*) username +-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username completionHandler: (void (^)(SWGUser* output, NSError* error)) handler; ``` @@ -254,7 +254,7 @@ No authorization required # **loginUser** ```objc --(NSNumber*) loginUserWithUsername: (NSString*) username +-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username password: (NSString*) password completionHandler: (void (^)(NSString* output, NSError* error)) handler; ``` @@ -308,7 +308,7 @@ No authorization required # **logoutUser** ```objc --(NSNumber*) logoutUserWithCompletionHandler: +-(NSURLSessionTask*) logoutUserWithCompletionHandler: (void (^)(NSError* error)) handler; ``` @@ -351,7 +351,7 @@ No authorization required # **updateUser** ```objc --(NSNumber*) updateUserWithUsername: (NSString*) username +-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username body: (SWGUser*) body completionHandler: (void (^)(NSError* error)) handler; ``` diff --git a/samples/server/petstore/finch/.swagger-codegen-ignore b/samples/server/petstore/finch/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/server/petstore/finch/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/finch/LICENSE b/samples/server/petstore/finch/LICENSE new file mode 100644 index 00000000000..8dada3edaf5 --- /dev/null +++ b/samples/server/petstore/finch/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/samples/server/petstore/finch/README.md b/samples/server/petstore/finch/README.md new file mode 100644 index 00000000000..327870827fd --- /dev/null +++ b/samples/server/petstore/finch/README.md @@ -0,0 +1,10 @@ +# Swagger generated server + +## Overview +This server was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the +[OpenAPI-Spec](https://github.com/swagger-api/swagger-core/wiki) from a remote server, you can easily generate a server stub. This +is an example of building a swagger-enabled scalatra server. + +This example uses the [scalatra](http://scalatra.org/) framework. To see how to make this your own, look here: + +[README](https://github.com/swagger-api/swagger-codegen/tree/master/samples/server-generator/scalatra) \ No newline at end of file diff --git a/samples/server/petstore/finch/build.sbt b/samples/server/petstore/finch/build.sbt new file mode 100644 index 00000000000..b58544b46bd --- /dev/null +++ b/samples/server/petstore/finch/build.sbt @@ -0,0 +1,61 @@ +scalariformSettings + +organization := "io.swagger" + +name := "finch-sample" + +version := "0.1.0-SNAPSHOT" + +scalaVersion := "2.11.8" + +resolvers += Resolver.sonatypeRepo("snapshots") + +resolvers += "TM" at "http://maven.twttr.com" + +resolvers += "Local Maven Repository" at "file://"+Path.userHome.absolutePath+"/.m2/repository" + +resolvers += "Sonatype OSS Snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" + +resolvers += "Sonatype OSS Releases" at "http://oss.sonatype.org/content/repositories/releases/" + +Defaults.itSettings + +scalacOptions ++= Seq( + "-deprecation", + "-encoding", "UTF-8", + "-feature", + "-language:existentials", + "-language:higherKinds", + "-language:implicitConversions", + "-unchecked", + "-Yno-adapted-args", + "-Ywarn-dead-code", + "-Ywarn-numeric-widen", + "-Xfuture", + "-Xlint", +// "-Ywarn-unused-import", + "-language:postfixOps" +) + +lazy val `it-config-sbt-project` = project.in(file(".")).configs(IntegrationTest) + +libraryDependencies ++= Seq( + "com.github.finagle" %% "finch-core" % "0.12.0", + "com.github.finagle" %% "finch-circe" % "0.12.0", + "io.circe" %% "circe-generic" % "0.7.0", + "io.circe" %% "circe-java8" % "0.7.0", + "com.twitter" %% "util-core" % "6.40.0", + "com.github.finagle" %% "finch-test" % "0.12.0" % "test", + "org.scalacheck" %% "scalacheck" % "1.13.4" % "test", + "org.scalatest" %% "scalatest" % "3.0.0" % "test" +) + +assemblyMergeStrategy in assembly := { + case "application.conf" => MergeStrategy.concat + case "about.html" => MergeStrategy.discard + case x => + val oldStrategy = (assemblyMergeStrategy in assembly).value + oldStrategy(x) +} + +addCompilerPlugin("org.scalamacros" % "paradise" % "2.1.0" cross CrossVersion.full) diff --git a/samples/server/petstore/finch/project/build.properties b/samples/server/petstore/finch/project/build.properties new file mode 100644 index 00000000000..27e88aa115a --- /dev/null +++ b/samples/server/petstore/finch/project/build.properties @@ -0,0 +1 @@ +sbt.version=0.13.13 diff --git a/samples/server/petstore/finch/project/plugins.sbt b/samples/server/petstore/finch/project/plugins.sbt new file mode 100644 index 00000000000..761afa5688e --- /dev/null +++ b/samples/server/petstore/finch/project/plugins.sbt @@ -0,0 +1,7 @@ +resolvers += Resolver.typesafeRepo("releases") + +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.3") + +// addSbtPlugin("com.typesafe.sbt" % "sbt-native-packager" % "1.1.4") + +addSbtPlugin("org.scalariform" % "sbt-scalariform" % "1.6.0") diff --git a/samples/server/petstore/finch/sbt b/samples/server/petstore/finch/sbt new file mode 100644 index 00000000000..08e58821219 --- /dev/null +++ b/samples/server/petstore/finch/sbt @@ -0,0 +1,525 @@ +#!/usr/bin/env bash +# +# A more capable sbt runner, coincidentally also called sbt. +# Author: Paul Phillips + +# todo - make this dynamic +declare -r sbt_release_version="0.13.6" +declare -r sbt_unreleased_version="0.13.6" +declare -r buildProps="project/build.properties" + +declare sbt_jar sbt_dir sbt_create sbt_version +declare scala_version sbt_explicit_version +declare verbose noshare batch trace_level log_level +declare sbt_saved_stty debugUs + +echoerr () { echo >&2 "$@"; } +vlog () { [[ -n "$verbose" ]] && echoerr "$@"; } + +# spaces are possible, e.g. sbt.version = 0.13.0 +build_props_sbt () { + [[ -r "$buildProps" ]] && \ + grep '^sbt\.version' "$buildProps" | tr '=' ' ' | awk '{ print $2; }' +} + +update_build_props_sbt () { + local ver="$1" + local old="$(build_props_sbt)" + + [[ -r "$buildProps" ]] && [[ "$ver" != "$old" ]] && { + perl -pi -e "s/^sbt\.version\b.*\$/sbt.version=${ver}/" "$buildProps" + grep -q '^sbt.version[ =]' "$buildProps" || printf "\nsbt.version=%s\n" "$ver" >> "$buildProps" + + vlog "!!!" + vlog "!!! Updated file $buildProps setting sbt.version to: $ver" + vlog "!!! Previous value was: $old" + vlog "!!!" + } +} + +set_sbt_version () { + sbt_version="${sbt_explicit_version:-$(build_props_sbt)}" + [[ -n "$sbt_version" ]] || sbt_version=$sbt_release_version + export sbt_version +} + +# restore stty settings (echo in particular) +onSbtRunnerExit() { + [[ -n "$sbt_saved_stty" ]] || return + vlog "" + vlog "restoring stty: $sbt_saved_stty" + stty "$sbt_saved_stty" + unset sbt_saved_stty +} + +# save stty and trap exit, to ensure echo is reenabled if we are interrupted. +trap onSbtRunnerExit EXIT +sbt_saved_stty="$(stty -g 2>/dev/null)" +vlog "Saved stty: $sbt_saved_stty" + +# this seems to cover the bases on OSX, and someone will +# have to tell me about the others. +get_script_path () { + local path="$1" + [[ -L "$path" ]] || { echo "$path" ; return; } + + local target="$(readlink "$path")" + if [[ "${target:0:1}" == "/" ]]; then + echo "$target" + else + echo "${path%/*}/$target" + fi +} + +die() { + echo "Aborting: $@" + exit 1 +} + +make_url () { + version="$1" + + case "$version" in + 0.7.*) echo "http://simple-build-tool.googlecode.com/files/sbt-launch-0.7.7.jar" ;; + 0.10.* ) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + 0.11.[12]) echo "$sbt_launch_repo/org.scala-tools.sbt/sbt-launch/$version/sbt-launch.jar" ;; + *) echo "$sbt_launch_repo/org.scala-sbt/sbt-launch/$version/sbt-launch.jar" ;; + esac +} + +init_default_option_file () { + local overriding_var="${!1}" + local default_file="$2" + if [[ ! -r "$default_file" && "$overriding_var" =~ ^@(.*)$ ]]; then + local envvar_file="${BASH_REMATCH[1]}" + if [[ -r "$envvar_file" ]]; then + default_file="$envvar_file" + fi + fi + echo "$default_file" +} + +declare -r cms_opts="-XX:+CMSClassUnloadingEnabled -XX:+UseConcMarkSweepGC" +declare -r jit_opts="-XX:ReservedCodeCacheSize=256m -XX:+TieredCompilation" +declare -r default_jvm_opts_common="-Xms512m -Xmx1536m -Xss2m $jit_opts $cms_opts" +declare -r noshare_opts="-Dsbt.global.base=project/.sbtboot -Dsbt.boot.directory=project/.boot -Dsbt.ivy.home=project/.ivy" +declare -r latest_28="2.8.2" +declare -r latest_29="2.9.3" +declare -r latest_210="2.10.4" +declare -r latest_211="2.11.2" + +declare -r script_path="$(get_script_path "$BASH_SOURCE")" +declare -r script_name="${script_path##*/}" + +# some non-read-onlies set with defaults +declare java_cmd="java" +declare sbt_opts_file="$(init_default_option_file SBT_OPTS .sbtopts)" +declare jvm_opts_file="$(init_default_option_file JVM_OPTS .jvmopts)" +declare sbt_launch_repo="http://typesafe.artifactoryonline.com/typesafe/ivy-releases" + +# pull -J and -D options to give to java. +declare -a residual_args +declare -a java_args +declare -a scalac_args +declare -a sbt_commands + +# args to jvm/sbt via files or environment variables +declare -a extra_jvm_opts extra_sbt_opts + +# if set, use JAVA_HOME over java found in path +[[ -e "$JAVA_HOME/bin/java" ]] && java_cmd="$JAVA_HOME/bin/java" + +# directory to store sbt launchers +declare sbt_launch_dir="$HOME/.sbt/launchers" +[[ -d "$sbt_launch_dir" ]] || mkdir -p "$sbt_launch_dir" +[[ -w "$sbt_launch_dir" ]] || sbt_launch_dir="$(mktemp -d -t sbt_extras_launchers.XXXXXX)" + +java_version () { + local version=$("$java_cmd" -version 2>&1 | grep -e 'java version' | awk '{ print $3 }' | tr -d \") + vlog "Detected Java version: $version" + echo "${version:2:1}" +} + +# MaxPermSize critical on pre-8 jvms but incurs noisy warning on 8+ +default_jvm_opts () { + local v="$(java_version)" + if [[ $v -ge 8 ]]; then + echo "$default_jvm_opts_common" + else + echo "-XX:MaxPermSize=384m $default_jvm_opts_common" + fi +} + +build_props_scala () { + if [[ -r "$buildProps" ]]; then + versionLine="$(grep '^build.scala.versions' "$buildProps")" + versionString="${versionLine##build.scala.versions=}" + echo "${versionString%% .*}" + fi +} + +execRunner () { + # print the arguments one to a line, quoting any containing spaces + vlog "# Executing command line:" && { + for arg; do + if [[ -n "$arg" ]]; then + if printf "%s\n" "$arg" | grep -q ' '; then + printf >&2 "\"%s\"\n" "$arg" + else + printf >&2 "%s\n" "$arg" + fi + fi + done + vlog "" + } + + [[ -n "$batch" ]] && exec /dev/null; then + curl --fail --silent "$url" --output "$jar" + elif which wget >/dev/null; then + wget --quiet -O "$jar" "$url" + fi + } && [[ -r "$jar" ]] +} + +acquire_sbt_jar () { + sbt_url="$(jar_url "$sbt_version")" + sbt_jar="$(jar_file "$sbt_version")" + + [[ -r "$sbt_jar" ]] || download_url "$sbt_url" "$sbt_jar" +} + +usage () { + cat < display stack traces with a max of frames (default: -1, traces suppressed) + -debug-inc enable debugging log for the incremental compiler + -no-colors disable ANSI color codes + -sbt-create start sbt even if current directory contains no sbt project + -sbt-dir path to global settings/plugins directory (default: ~/.sbt/) + -sbt-boot path to shared boot directory (default: ~/.sbt/boot in 0.11+) + -ivy path to local Ivy repository (default: ~/.ivy2) + -no-share use all local caches; no sharing + -offline put sbt in offline mode + -jvm-debug Turn on JVM debugging, open at the given port. + -batch Disable interactive mode + -prompt Set the sbt prompt; in expr, 's' is the State and 'e' is Extracted + + # sbt version (default: sbt.version from $buildProps if present, otherwise $sbt_release_version) + -sbt-force-latest force the use of the latest release of sbt: $sbt_release_version + -sbt-version use the specified version of sbt (default: $sbt_release_version) + -sbt-dev use the latest pre-release version of sbt: $sbt_unreleased_version + -sbt-jar use the specified jar as the sbt launcher + -sbt-launch-dir directory to hold sbt launchers (default: ~/.sbt/launchers) + -sbt-launch-repo repo url for downloading sbt launcher jar (default: $sbt_launch_repo) + + # scala version (default: as chosen by sbt) + -28 use $latest_28 + -29 use $latest_29 + -210 use $latest_210 + -211 use $latest_211 + -scala-home use the scala build at the specified directory + -scala-version use the specified version of scala + -binary-version use the specified scala version when searching for dependencies + + # java version (default: java from PATH, currently $(java -version 2>&1 | grep version)) + -java-home alternate JAVA_HOME + + # passing options to the jvm - note it does NOT use JAVA_OPTS due to pollution + # The default set is used if JVM_OPTS is unset and no -jvm-opts file is found + $(default_jvm_opts) + JVM_OPTS environment variable holding either the jvm args directly, or + the reference to a file containing jvm args if given path is prepended by '@' (e.g. '@/etc/jvmopts') + Note: "@"-file is overridden by local '.jvmopts' or '-jvm-opts' argument. + -jvm-opts file containing jvm args (if not given, .jvmopts in project root is used if present) + -Dkey=val pass -Dkey=val directly to the jvm + -J-X pass option -X directly to the jvm (-J is stripped) + + # passing options to sbt, OR to this runner + SBT_OPTS environment variable holding either the sbt args directly, or + the reference to a file containing sbt args if given path is prepended by '@' (e.g. '@/etc/sbtopts') + Note: "@"-file is overridden by local '.sbtopts' or '-sbt-opts' argument. + -sbt-opts file containing sbt args (if not given, .sbtopts in project root is used if present) + -S-X add -X to sbt's scalacOptions (-S is stripped) +EOM +} + +addJava () { + vlog "[addJava] arg = '$1'" + java_args=( "${java_args[@]}" "$1" ) +} +addSbt () { + vlog "[addSbt] arg = '$1'" + sbt_commands=( "${sbt_commands[@]}" "$1" ) +} +setThisBuild () { + vlog "[addBuild] args = '$@'" + local key="$1" && shift + addSbt "set $key in ThisBuild := $@" +} + +addScalac () { + vlog "[addScalac] arg = '$1'" + scalac_args=( "${scalac_args[@]}" "$1" ) +} +addResidual () { + vlog "[residual] arg = '$1'" + residual_args=( "${residual_args[@]}" "$1" ) +} +addResolver () { + addSbt "set resolvers += $1" +} +addDebugger () { + addJava "-Xdebug" + addJava "-Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=$1" +} +setScalaVersion () { + [[ "$1" == *"-SNAPSHOT" ]] && addResolver 'Resolver.sonatypeRepo("snapshots")' + addSbt "++ $1" +} + +process_args () +{ + require_arg () { + local type="$1" + local opt="$2" + local arg="$3" + + if [[ -z "$arg" ]] || [[ "${arg:0:1}" == "-" ]]; then + die "$opt requires <$type> argument" + fi + } + while [[ $# -gt 0 ]]; do + case "$1" in + -h|-help) usage; exit 1 ;; + -v) verbose=true && shift ;; + -d) addSbt "--debug" && shift ;; + -w) addSbt "--warn" && shift ;; + -q) addSbt "--error" && shift ;; + -x) debugUs=true && shift ;; + -trace) require_arg integer "$1" "$2" && trace_level="$2" && shift 2 ;; + -ivy) require_arg path "$1" "$2" && addJava "-Dsbt.ivy.home=$2" && shift 2 ;; + -no-colors) addJava "-Dsbt.log.noformat=true" && shift ;; + -no-share) noshare=true && shift ;; + -sbt-boot) require_arg path "$1" "$2" && addJava "-Dsbt.boot.directory=$2" && shift 2 ;; + -sbt-dir) require_arg path "$1" "$2" && sbt_dir="$2" && shift 2 ;; + -debug-inc) addJava "-Dxsbt.inc.debug=true" && shift ;; + -offline) addSbt "set offline := true" && shift ;; + -jvm-debug) require_arg port "$1" "$2" && addDebugger "$2" && shift 2 ;; + -batch) batch=true && shift ;; + -prompt) require_arg "expr" "$1" "$2" && setThisBuild shellPrompt "(s => { val e = Project.extract(s) ; $2 })" && shift 2 ;; + + -sbt-create) sbt_create=true && shift ;; + -sbt-jar) require_arg path "$1" "$2" && sbt_jar="$2" && shift 2 ;; + -sbt-version) require_arg version "$1" "$2" && sbt_explicit_version="$2" && shift 2 ;; + -sbt-force-latest) sbt_explicit_version="$sbt_release_version" && shift ;; + -sbt-dev) sbt_explicit_version="$sbt_unreleased_version" && shift ;; + -sbt-launch-dir) require_arg path "$1" "$2" && sbt_launch_dir="$2" && shift 2 ;; + -sbt-launch-repo) require_arg path "$1" "$2" && sbt_launch_repo="$2" && shift 2 ;; + -scala-version) require_arg version "$1" "$2" && setScalaVersion "$2" && shift 2 ;; + -binary-version) require_arg version "$1" "$2" && setThisBuild scalaBinaryVersion "\"$2\"" && shift 2 ;; + -scala-home) require_arg path "$1" "$2" && setThisBuild scalaHome "Some(file(\"$2\"))" && shift 2 ;; + -java-home) require_arg path "$1" "$2" && java_cmd="$2/bin/java" && shift 2 ;; + -sbt-opts) require_arg path "$1" "$2" && sbt_opts_file="$2" && shift 2 ;; + -jvm-opts) require_arg path "$1" "$2" && jvm_opts_file="$2" && shift 2 ;; + + -D*) addJava "$1" && shift ;; + -J*) addJava "${1:2}" && shift ;; + -S*) addScalac "${1:2}" && shift ;; + -28) setScalaVersion "$latest_28" && shift ;; + -29) setScalaVersion "$latest_29" && shift ;; + -210) setScalaVersion "$latest_210" && shift ;; + -211) setScalaVersion "$latest_211" && shift ;; + + *) addResidual "$1" && shift ;; + esac + done +} + +# process the direct command line arguments +process_args "$@" + +# skip #-styled comments and blank lines +readConfigFile() { + while read line; do + [[ $line =~ ^# ]] || [[ -z $line ]] || echo "$line" + done < "$1" +} + +# if there are file/environment sbt_opts, process again so we +# can supply args to this runner +if [[ -r "$sbt_opts_file" ]]; then + vlog "Using sbt options defined in file $sbt_opts_file" + while read opt; do extra_sbt_opts+=("$opt"); done < <(readConfigFile "$sbt_opts_file") +elif [[ -n "$SBT_OPTS" && ! ("$SBT_OPTS" =~ ^@.*) ]]; then + vlog "Using sbt options defined in variable \$SBT_OPTS" + extra_sbt_opts=( $SBT_OPTS ) +else + vlog "No extra sbt options have been defined" +fi + +[[ -n "${extra_sbt_opts[*]}" ]] && process_args "${extra_sbt_opts[@]}" + +# reset "$@" to the residual args +set -- "${residual_args[@]}" +argumentCount=$# + +# set sbt version +set_sbt_version + +# only exists in 0.12+ +setTraceLevel() { + case "$sbt_version" in + "0.7."* | "0.10."* | "0.11."* ) echoerr "Cannot set trace level in sbt version $sbt_version" ;; + *) setThisBuild traceLevel $trace_level ;; + esac +} + +# set scalacOptions if we were given any -S opts +[[ ${#scalac_args[@]} -eq 0 ]] || addSbt "set scalacOptions in ThisBuild += \"${scalac_args[@]}\"" + +# Update build.properties on disk to set explicit version - sbt gives us no choice +[[ -n "$sbt_explicit_version" ]] && update_build_props_sbt "$sbt_explicit_version" +vlog "Detected sbt version $sbt_version" + +[[ -n "$scala_version" ]] && vlog "Overriding scala version to $scala_version" + +# no args - alert them there's stuff in here +(( argumentCount > 0 )) || { + vlog "Starting $script_name: invoke with -help for other options" + residual_args=( shell ) +} + +# verify this is an sbt dir or -create was given +[[ -r ./build.sbt || -d ./project || -n "$sbt_create" ]] || { + cat < apis -> operations = ??? + // NOTE: ??? throws a not implemented exception + + /** + * + * @return A Unit + */ + def Pet_addPet(body: Pet): Unit = ??? + + /** + * + * @return A Unit + */ + def Pet_deletePet(petId: Long, apiKey: String): Unit = ??? + + /** + * + * @return A Seq[Pet] + */ + def Pet_findPetsByStatus(status: Seq[String]): Seq[Pet] = ??? + + /** + * + * @return A Seq[Pet] + */ + def Pet_findPetsByTags(tags: Seq[String]): Seq[Pet] = ??? + + /** + * + * @return A Pet + */ + def Pet_getPetById(petId: Long): Pet = ??? + + /** + * + * @return A Unit + */ + def Pet_updatePet(body: Pet): Unit = ??? + + /** + * + * @return A Unit + */ + def Pet_updatePetWithForm(petId: Long, name: String, status: String): Unit = ??? + + /** + * + * @return A ApiResponse + */ + def Pet_uploadFile(petId: Long, additionalMetadata: String, file: File): ApiResponse = ??? + + /** + * + * @return A Unit + */ + def Store_deleteOrder(orderId: String): Unit = ??? + + /** + * + * @return A Map[String, Int] + */ + def Store_getInventory(): Map[String, Int] = ??? + + /** + * + * @return A Order + */ + def Store_getOrderById(orderId: Long): Order = ??? + + /** + * + * @return A Order + */ + def Store_placeOrder(body: Order): Order = ??? + + /** + * + * @return A Unit + */ + def User_createUser(body: User): Unit = ??? + + /** + * + * @return A Unit + */ + def User_createUsersWithArrayInput(body: Seq[User]): Unit = ??? + + /** + * + * @return A Unit + */ + def User_createUsersWithListInput(body: Seq[User]): Unit = ??? + + /** + * + * @return A Unit + */ + def User_deleteUser(username: String): Unit = ??? + + /** + * + * @return A User + */ + def User_getUserByName(username: String): User = ??? + + /** + * + * @return A String + */ + def User_loginUser(username: String, password: String): String = ??? + + /** + * + * @return A Unit + */ + def User_logoutUser(): Unit = ??? + + /** + * + * @return A Unit + */ + def User_updateUser(username: String, body: User): Unit = ??? + +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/Server.scala b/samples/server/petstore/finch/src/main/scala/Server.scala new file mode 100644 index 00000000000..716b6eae52e --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/Server.scala @@ -0,0 +1,36 @@ +package io.swagger.petstore + +import io.finch._ +import io.finch.circe._ +import io.circe.{ Decoder, ObjectEncoder } +import io.circe.generic.auto._ +import io.circe.generic.semiauto +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import com.twitter.finagle.Http +import com.twitter.finagle.util.LoadService +import com.twitter.util.{ Await, Future } + +class Server { + + // Loads implementation defined in resources/META-INF/services/io.swagger.petstore.DataAccessor + val db = LoadService[DataAccessor]() match { + case accessor :: _ => accessor + case _ => new DataAccessor {} + } + + val service = endpoint.makeService(db) + + val server = Http.serve(":8080", service) //creates service + + def close(): Future[Unit] = { + Await.ready(server.close()) + } +} + +/** + * Launches the PetstoreAPI service when the system is ready. + */ +object Server extends Server with App { + Await.ready(server) +} diff --git a/samples/server/petstore/finch/src/main/scala/endpoint.scala b/samples/server/petstore/finch/src/main/scala/endpoint.scala new file mode 100644 index 00000000000..df0093b7b13 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/endpoint.scala @@ -0,0 +1,48 @@ +package io.swagger.petstore + +import com.twitter.finagle.Service +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.FileUpload +import com.twitter.util.Future +import io.finch._, items._ +import io.circe.{ Encoder, Json } +import io.finch.circe._ +import io.circe.generic.semiauto._ + +import io.swagger.petstore.apis._ + +/** + * Provides the paths and endpoints for all the API's public service methods. + */ +object endpoint { + + def errorToJson(e: Exception): Json = e match { + case Error.NotPresent(_) => + Json.obj("error" -> Json.fromString("something_not_present")) + case Error.NotParsed(_, _, _) => + Json.obj("error" -> Json.fromString("something_not_parsed")) + case Error.NotValid(_, _) => + Json.obj("error" -> Json.fromString("something_not_valid")) + case error: PetstoreError => + Json.obj("error" -> Json.fromString(error.message)) + } + + implicit val ee: Encoder[Exception] = Encoder.instance { + case e: Error => errorToJson(e) + case Errors(nel) => Json.arr(nel.toList.map(errorToJson): _*) + } + + /** + * Compiles together all the endpoints relating to public service methods. + * + * @return A service that contains all provided endpoints of the API. + */ + def makeService(da: DataAccessor): Service[Request, Response] = ( + PetApi.endpoints(da) :+: + StoreApi.endpoints(da) :+: + UserApi.endpoints(da) + ).handle({ + case e: PetstoreError => NotFound(e) + }).toService + +} \ No newline at end of file diff --git a/samples/server/petstore/finch/src/main/scala/errors.scala b/samples/server/petstore/finch/src/main/scala/errors.scala new file mode 100644 index 00000000000..69e3831c15d --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/errors.scala @@ -0,0 +1,27 @@ +package io.swagger.petstore + +/** + * The parent error from which most PetstoreAPI errors extend. Thrown whenever something in the api goes wrong. + */ +abstract class PetstoreError(msg: String) extends Exception(msg) { + def message: String +} + +/** + * Thrown when the object given is invalid + * @param message An error message + */ +case class InvalidInput(message: String) extends PetstoreError(message) + +/** + * Thrown when the given object is missing a unique ID. + * @param message An error message + */ +case class MissingIdentifier(message: String) extends PetstoreError(message) + +/** + * Thrown when the given record does not exist in the database. + * @param message An error message + */ +case class RecordNotFound(message: String) extends PetstoreError(message) + diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala new file mode 100644 index 00000000000..420279685d3 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/PetApi.scala @@ -0,0 +1,148 @@ +package io.swagger.petstore.apis + +import java.io._ +import java.util.Date +import io.swagger.petstore._ +import io.swagger.petstore.models._ +import io.swagger.petstore.models.Pet +import java.io.File +import io.swagger.petstore.models.ApiResponse +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.{ FileUpload, InMemoryFileUpload, OnDiskFileUpload } +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object PetApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + addPet(da) :+: + deletePet(da) :+: + findPetsByStatus(da) :+: + findPetsByTags(da) :+: + getPetById(da) :+: + updatePet(da) :+: + updatePetWithForm(da) :+: + uploadFile(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def addPet(da: DataAccessor): Endpoint[Unit] = + post("pet" :: jsonBody[Pet]) { (body: Pet) => + da.Pet_addPet(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def deletePet(da: DataAccessor): Endpoint[Unit] = + delete("pet" :: long :: string) { (petId: Long, apiKey: String) => + da.Pet_deletePet(petId, apiKey) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Seq[Pet] + */ + private def findPetsByStatus(da: DataAccessor): Endpoint[Seq[Pet]] = + get("pet" :: "findByStatus" :: params("status")) { (status: Seq[String]) => + Ok(da.Pet_findPetsByStatus(status)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Seq[Pet] + */ + private def findPetsByTags(da: DataAccessor): Endpoint[Seq[Pet]] = + get("pet" :: "findByTags" :: params("tags")) { (tags: Seq[String]) => + Ok(da.Pet_findPetsByTags(tags)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Pet + */ + private def getPetById(da: DataAccessor): Endpoint[Pet] = + get("pet" :: long) { (petId: Long) => + Ok(da.Pet_getPetById(petId)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updatePet(da: DataAccessor): Endpoint[Unit] = + put("pet" :: jsonBody[Pet]) { (body: Pet) => + da.Pet_updatePet(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updatePetWithForm(da: DataAccessor): Endpoint[Unit] = + post("pet" :: long :: string :: string) { (petId: Long, name: String, status: String) => + da.Pet_updatePetWithForm(petId, name, status) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a ApiResponse + */ + private def uploadFile(da: DataAccessor): Endpoint[ApiResponse] = + post("pet" :: long :: "uploadImage" :: string :: fileUpload("file")) { (petId: Long, additionalMetadata: String, file: FileUpload) => + Ok(da.Pet_uploadFile(petId, additionalMetadata, file)) + } handle { + case e: Exception => BadRequest(e) + } + + implicit private def fileUploadToFile(fileUpload: FileUpload): File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmpPetApi", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala new file mode 100644 index 00000000000..38dda7b4786 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/StoreApi.scala @@ -0,0 +1,95 @@ +package io.swagger.petstore.apis + +import java.io._ +import java.util.Date +import io.swagger.petstore._ +import io.swagger.petstore.models._ +import io.swagger.petstore.models.Order +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.{ FileUpload, InMemoryFileUpload, OnDiskFileUpload } +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object StoreApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + deleteOrder(da) :+: + getInventory(da) :+: + getOrderById(da) :+: + placeOrder(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def deleteOrder(da: DataAccessor): Endpoint[Unit] = + delete("store" :: "order" :: string) { (orderId: String) => + da.Store_deleteOrder(orderId) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Map[String, Int] + */ + private def getInventory(da: DataAccessor): Endpoint[Map[String, Int]] = + get("store" :: "inventory") { + Ok(da.Store_getInventory()) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Order + */ + private def getOrderById(da: DataAccessor): Endpoint[Order] = + get("store" :: "order" :: long) { (orderId: Long) => + Ok(da.Store_getOrderById(orderId)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Order + */ + private def placeOrder(da: DataAccessor): Endpoint[Order] = + post("store" :: "order" :: jsonBody[Order]) { (body: Order) => + Ok(da.Store_placeOrder(body)) + } handle { + case e: Exception => BadRequest(e) + } + + implicit private def fileUploadToFile(fileUpload: FileUpload): File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmpStoreApi", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala new file mode 100644 index 00000000000..560509a349c --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/apis/UserApi.scala @@ -0,0 +1,149 @@ +package io.swagger.petstore.apis + +import java.io._ +import java.util.Date +import io.swagger.petstore._ +import io.swagger.petstore.models._ +import io.swagger.petstore.models.User +import scala.collection.immutable.Seq +import io.finch.circe._ +import io.circe.generic.semiauto._ +import com.twitter.concurrent.AsyncStream +import com.twitter.finagle.Service +import com.twitter.finagle.Http +import com.twitter.finagle.http.{ Request, Response } +import com.twitter.finagle.http.exp.Multipart.{ FileUpload, InMemoryFileUpload, OnDiskFileUpload } +import com.twitter.util.Future +import com.twitter.io.Buf +import io.finch._, items._ +import java.io.File + +object UserApi { + /** + * Compiles all service endpoints. + * @return Bundled compilation of all service endpoints. + */ + def endpoints(da: DataAccessor) = + createUser(da) :+: + createUsersWithArrayInput(da) :+: + createUsersWithListInput(da) :+: + deleteUser(da) :+: + getUserByName(da) :+: + loginUser(da) :+: + logoutUser(da) :+: + updateUser(da) + + /** + * + * @return And endpoint representing a Unit + */ + private def createUser(da: DataAccessor): Endpoint[Unit] = + post("user" :: jsonBody[User]) { (body: User) => + da.User_createUser(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def createUsersWithArrayInput(da: DataAccessor): Endpoint[Unit] = + post("user" :: "createWithArray" :: jsonBody[Seq[User]]) { (body: Seq[User]) => + da.User_createUsersWithArrayInput(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def createUsersWithListInput(da: DataAccessor): Endpoint[Unit] = + post("user" :: "createWithList" :: jsonBody[Seq[User]]) { (body: Seq[User]) => + da.User_createUsersWithListInput(body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def deleteUser(da: DataAccessor): Endpoint[Unit] = + delete("user" :: string) { (username: String) => + da.User_deleteUser(username) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a User + */ + private def getUserByName(da: DataAccessor): Endpoint[User] = + get("user" :: string) { (username: String) => + Ok(da.User_getUserByName(username)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a String + */ + private def loginUser(da: DataAccessor): Endpoint[String] = + get("user" :: "login" :: string :: string) { (username: String, password: String) => + Ok(da.User_loginUser(username, password)) + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def logoutUser(da: DataAccessor): Endpoint[Unit] = + get("user" :: "logout") { + da.User_logoutUser() + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + /** + * + * @return And endpoint representing a Unit + */ + private def updateUser(da: DataAccessor): Endpoint[Unit] = + put("user" :: string :: jsonBody[User]) { (username: String, body: User) => + da.User_updateUser(username, body) + NoContent[Unit] + } handle { + case e: Exception => BadRequest(e) + } + + implicit private def fileUploadToFile(fileUpload: FileUpload): File = { + fileUpload match { + case upload: InMemoryFileUpload => + bytesToFile(Buf.ByteArray.Owned.extract(upload.content)) + case upload: OnDiskFileUpload => + upload.content + case _ => null + } + } + + private def bytesToFile(input: Array[Byte]): java.io.File = { + val file = File.createTempFile("tmpUserApi", null) + val output = new FileOutputStream(file) + output.write(input) + file + } + + // This assists in params(string) application (which must be Seq[A] in parameter list) when the param is used as a List[A] elsewhere. + implicit def seqList[A](input: Seq[A]): List[A] = input.toList +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala new file mode 100644 index 00000000000..248833a4e75 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/ApiResponse.scala @@ -0,0 +1,27 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * Describes the result of uploading an image resource + * @param code + * @param _type + * @param message + */ +case class ApiResponse( + code: Option[Int], + _type: Option[String], + message: Option[String] +) + +object ApiResponse { + /** + * Creates the codec for converting ApiResponse from and to JSON. + */ + implicit val decoder: Decoder[ApiResponse] = deriveDecoder + implicit val encoder: ObjectEncoder[ApiResponse] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala new file mode 100644 index 00000000000..ceb17f6b7e7 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Category.scala @@ -0,0 +1,25 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * A category for a pet + * @param id + * @param name + */ +case class Category( + id: Option[Long], + name: Option[String] +) + +object Category { + /** + * Creates the codec for converting Category from and to JSON. + */ + implicit val decoder: Decoder[Category] = deriveDecoder + implicit val encoder: ObjectEncoder[Category] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala new file mode 100644 index 00000000000..08743ebbf13 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Order.scala @@ -0,0 +1,34 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ +import java.time.LocalDateTime + +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +case class Order( + id: Option[Long], + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[LocalDateTime], + status: Option[String], + complete: Option[Boolean] +) + +object Order { + /** + * Creates the codec for converting Order from and to JSON. + */ + implicit val decoder: Decoder[Order] = deriveDecoder + implicit val encoder: ObjectEncoder[Order] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala new file mode 100644 index 00000000000..4a17021b726 --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Pet.scala @@ -0,0 +1,36 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ +import io.swagger.petstore.models.Category +import io.swagger.petstore.models.Tag +import scala.collection.immutable.Seq + +/** + * A pet for sale in the pet store + * @param id + * @param category + * @param name + * @param photoUrls + * @param tags + * @param status pet status in the store + */ +case class Pet( + id: Option[Long], + category: Option[Category], + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]], + status: Option[String] +) + +object Pet { + /** + * Creates the codec for converting Pet from and to JSON. + */ + implicit val decoder: Decoder[Pet] = deriveDecoder + implicit val encoder: ObjectEncoder[Pet] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala new file mode 100644 index 00000000000..5fb213c0c3f --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/Tag.scala @@ -0,0 +1,25 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * A tag for a pet + * @param id + * @param name + */ +case class Tag( + id: Option[Long], + name: Option[String] +) + +object Tag { + /** + * Creates the codec for converting Tag from and to JSON. + */ + implicit val decoder: Decoder[Tag] = deriveDecoder + implicit val encoder: ObjectEncoder[Tag] = deriveEncoder +} diff --git a/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala new file mode 100644 index 00000000000..6556cdb437a --- /dev/null +++ b/samples/server/petstore/finch/src/main/scala/io/swagger/petstore/models/User.scala @@ -0,0 +1,37 @@ +package io.swagger.petstore.models + +import io.circe._ +import io.finch.circe._ +import io.circe.generic.semiauto._ +import io.circe.java8.time._ +import io.swagger.petstore._ + +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +case class User( + id: Option[Long], + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + userStatus: Option[Int] +) + +object User { + /** + * Creates the codec for converting User from and to JSON. + */ + implicit val decoder: Decoder[User] = deriveDecoder + implicit val encoder: ObjectEncoder[User] = deriveEncoder +} diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala index 7c6d352ae5d..2353b35ff76 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/PetApi.scala @@ -63,7 +63,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description(""), headerParam[String]("apiKey").description("").optional) ) - delete("/pet/:petId",operation(deletePetOperation)) { + delete("/pet/{petId}",operation(deletePetOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -131,7 +131,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description("")) ) - get("/pet/:petId",operation(getPetByIdOperation)) { + get("/pet/{petId}",operation(getPetByIdOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -161,7 +161,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description(""), formParam[String]("name").description("").optional, formParam[String]("status").description("").optional) ) - post("/pet/:petId",operation(updatePetWithFormOperation)) { + post("/pet/{petId}",operation(updatePetWithFormOperation)) { val petId = params.getOrElse("petId", halt(400)) @@ -186,7 +186,7 @@ class PetApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("petId").description(""), formParam[String]("additionalMetadata").description("").optional, formParam[File]("file").description("").optional) ) - post("/pet/:petId/uploadImage",operation(uploadFileOperation)) { + post("/pet/{petId}/uploadImage",operation(uploadFileOperation)) { val petId = params.getOrElse("petId", halt(400)) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala index 58af1ba24f5..44e41f4d1e8 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/StoreApi.scala @@ -46,7 +46,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[String]("orderId").description("")) ) - delete("/store/order/:orderId",operation(deleteOrderOperation)) { + delete("/store/order/{orderId}",operation(deleteOrderOperation)) { val orderId = params.getOrElse("orderId", halt(400)) @@ -71,7 +71,7 @@ class StoreApi (implicit val swagger: Swagger) extends ScalatraServlet parameters(pathParam[Long]("orderId").description("")) ) - get("/store/order/:orderId",operation(getOrderByIdOperation)) { + get("/store/order/{orderId}",operation(getOrderByIdOperation)) { val orderId = params.getOrElse("orderId", halt(400)) diff --git a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala index 8dfcc672c26..8b8630675b1 100644 --- a/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala +++ b/samples/server/petstore/scalatra/src/main/scala/com/wordnik/client/api/UserApi.scala @@ -93,7 +93,6 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet delete("/user/:username",operation(deleteUserOperation)) { - val username = params.getOrElse("username", halt(400)) println("username: " + username) @@ -108,7 +107,6 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet get("/user/:username",operation(getUserByNameOperation)) { - val username = params.getOrElse("username", halt(400)) println("username: " + username) @@ -153,7 +151,6 @@ class UserApi (implicit val swagger: Swagger) extends ScalatraServlet put("/user/:username",operation(updateUserOperation)) { - val username = params.getOrElse("username", halt(400)) println("username: " + username)