[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
This commit is contained in:
wing328 2017-01-29 12:15:39 +08:00 committed by GitHub
parent 6890ef9755
commit ae8a123484
140 changed files with 5262 additions and 2421 deletions

31
bin/finch-petstore-server.sh Executable file
View File

@ -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

View File

@ -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<String>(
Arrays.asList("double",
"Int",
"Long",
"Float",
"Double",
"char",
"float",
"String",
"boolean",
"Boolean",
"Double",
"Integer",
"Long",
"Float",
"List",
"Set",
"Map")
);
typeMapping = new HashMap<String, String>();
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<String>(
Arrays.asList(
"String",
"Boolean",
"Double",
"Int",
"Integer",
"Long",
"Float",
"Any",
"AnyVal",
"AnyRef",
"Object")
);
instantiationTypes.put("array", "ArrayList");
instantiationTypes.put("map", "HashMap");
importMapping = new HashMap<String, String>();
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<String, Model> allDefinitions) {
CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
return codegenModel;
}
@Override
public Map<String, Object> postProcessOperations(Map<String, Object> objs) {
Map<String, Object> operations = (Map<String, Object>) objs.get("operations");
List<CodegenOperation> operationList = (List<CodegenOperation>) 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;
}
}

View File

@ -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"));

View File

@ -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");

View File

@ -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

View File

@ -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}}
}

View File

@ -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)
}

View File

@ -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)

View File

@ -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)
}

View File

@ -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
}

View File

@ -0,0 +1 @@
{{#isBodyParam}}bodyParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isBodyParam}}

View File

@ -0,0 +1,3 @@
{{#isBodyParam}}
val {{paramName}} = parsedBody.extract[{{dataType}}]
{{/isBodyParam}}

View File

@ -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)

View File

@ -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
}

View File

@ -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)

View File

@ -0,0 +1 @@
{{#isFormParam}}formParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isFormParam}}

View File

@ -0,0 +1,3 @@
{{#isFormParam}}
val {{paramName}} = params.getAs[{{dataType}}]("{{paramName}}")
{{/isFormParam}}

View File

@ -0,0 +1 @@
{{#isHeaderParam}}headerParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isHeaderParam}}

View File

@ -0,0 +1,3 @@
{{#isHeaderParam}}
val {{paramName}} = request.getHeader("{{paramName}}")
{{/isHeaderParam}}

View File

@ -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}}

View File

@ -0,0 +1 @@
{{#isPathParam}}pathParam[{{dataType}}]("{{paramName}}").description(""){{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isPathParam}}

View File

@ -0,0 +1 @@
sbt.version=0.13.13

View File

@ -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")

View File

@ -0,0 +1 @@
{{#isQueryParam}}queryParam[{{dataType}}]("{{paramName}}").description(""){{^required}}.optional{{/required}}{{#defaultValue}}.defaultValue({{{defaultValue}}}){{/defaultValue}}{{/isQueryParam}}

View File

@ -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}}

View File

@ -0,0 +1,525 @@
#!/usr/bin/env bash
#
# A more capable sbt runner, coincidentally also called sbt.
# Author: Paul Phillips <paulp@typesafe.com>
# 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
exec "$@"
}
jar_url () {
make_url "$1"
}
jar_file () {
echo "$sbt_launch_dir/$1/sbt-launch.jar"
}
download_url () {
local url="$1"
local jar="$2"
echoerr "Downloading sbt launcher for $sbt_version:"
echoerr " From $url"
echoerr " To $jar"
mkdir -p "${jar%/*}" && {
if which curl >/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 <<EOM
Usage: $script_name [options]
Note that options which are passed along to sbt begin with -- whereas
options to this runner use a single dash. Any sbt command can be scheduled
to run first by prefixing the command with --, so --warn, --error and so on
are not special.
Output filtering: if there is a file in the home directory called .sbtignore
and this is not an interactive sbt session, the file is treated as a list of
bash regular expressions. Output lines which match any regex are not echoed.
One can see exactly which lines would have been suppressed by starting this
runner with the -x option.
-h | -help print this message
-v verbose operation (this runner is chattier)
-d, -w, -q aliases for --debug, --warn, --error (q means quiet)
-x debug this script
-trace <level> display stack traces with a max of <level> 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> path to global settings/plugins directory (default: ~/.sbt/<version>)
-sbt-boot <path> path to shared boot directory (default: ~/.sbt/boot in 0.11+)
-ivy <path> path to local Ivy repository (default: ~/.ivy2)
-no-share use all local caches; no sharing
-offline put sbt in offline mode
-jvm-debug <port> Turn on JVM debugging, open at the given port.
-batch Disable interactive mode
-prompt <expr> 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 <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 <path> use the specified jar as the sbt launcher
-sbt-launch-dir <path> directory to hold sbt launchers (default: ~/.sbt/launchers)
-sbt-launch-repo <url> 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 <path> use the scala build at the specified directory
-scala-version <version> use the specified version of scala
-binary-version <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 <path> 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> $(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 <path> 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 <path> 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 <<EOM
$(pwd) doesn't appear to be an sbt project.
If you want to start sbt anyway, run:
$0 -sbt-create
EOM
exit 1
}
# pick up completion if present; todo
[[ -r .sbt_completion.sh ]] && source .sbt_completion.sh
# no jar? download it.
[[ -r "$sbt_jar" ]] || acquire_sbt_jar || {
# still no jar? uh-oh.
echo "Download failed. Obtain the jar manually and place it at $sbt_jar"
exit 1
}
if [[ -n "$noshare" ]]; then
for opt in ${noshare_opts}; do
addJava "$opt"
done
else
case "$sbt_version" in
"0.7."* | "0.10."* | "0.11."* | "0.12."* )
[[ -n "$sbt_dir" ]] || {
sbt_dir="$HOME/.sbt/$sbt_version"
vlog "Using $sbt_dir as sbt dir, -sbt-dir to override."
}
;;
esac
if [[ -n "$sbt_dir" ]]; then
addJava "-Dsbt.global.base=$sbt_dir"
fi
fi
if [[ -r "$jvm_opts_file" ]]; then
vlog "Using jvm options defined in file $jvm_opts_file"
while read opt; do extra_jvm_opts+=("$opt"); done < <(readConfigFile "$jvm_opts_file")
elif [[ -n "$JVM_OPTS" && ! ("$JVM_OPTS" =~ ^@.*) ]]; then
vlog "Using jvm options defined in \$JVM_OPTS variable"
extra_jvm_opts=( $JVM_OPTS )
else
vlog "Using default jvm options"
extra_jvm_opts=( $(default_jvm_opts) )
fi
# traceLevel is 0.12+
[[ -n "$trace_level" ]] && setTraceLevel
main () {
execRunner "$java_cmd" \
"${extra_jvm_opts[@]}" \
"${java_args[@]}" \
-jar "$sbt_jar" \
"${sbt_commands[@]}" \
"${residual_args[@]}"
}
# sbt inserts this string on certain lines when formatting is enabled:
# val OverwriteLine = "\r\u001BM\u001B[2K"
# ...in order not to spam the console with a million "Resolving" lines.
# Unfortunately that makes it that much harder to work with when
# we're not going to print those lines anyway. We strip that bit of
# line noise, but leave the other codes to preserve color.
mainFiltered () {
local ansiOverwrite='\r\x1BM\x1B[2K'
local excludeRegex=$(egrep -v '^#|^$' ~/.sbtignore | paste -sd'|' -)
echoLine () {
local line="$1"
local line1="$(echo "$line" | sed -r 's/\r\x1BM\x1B\[2K//g')" # This strips the OverwriteLine code.
local line2="$(echo "$line1" | sed -r 's/\x1B\[[0-9;]*[JKmsu]//g')" # This strips all codes - we test regexes against this.
if [[ $line2 =~ $excludeRegex ]]; then
[[ -n $debugUs ]] && echo "[X] $line1"
else
[[ -n $debugUs ]] && echo " $line1" || echo "$line1"
fi
}
echoLine "Starting sbt with output filtering enabled."
main | while read -r line; do echoLine "$line"; done
}
# Only filter if there's a filter file and we don't see a known interactive command.
# Obviously this is super ad hoc but I don't know how to improve on it. Testing whether
# stdin is a terminal is useless because most of my use cases for this filtering are
# exactly when I'm at a terminal, running sbt non-interactively.
shouldFilter () { [[ -f ~/.sbtignore ]] && ! egrep -q '\b(shell|console|consoleProject)\b' <<<"${residual_args[@]}"; }
# run sbt
if shouldFilter; then mainFiltered; else main; fi

View File

@ -1,14 +1,13 @@
#import "{{classPrefix}}Logger.h"
#import "{{classPrefix}}ApiClient.h"
#import "{{classPrefix}}JSONRequestSerializer.h"
#import "{{classPrefix}}QueryParamCollection.h"
#import "{{classPrefix}}DefaultConfiguration.h"
NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
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 k{{classPrefix}}ContentDispositionKey = @"Content-Disposition";
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
@ -19,179 +18,80 @@ static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *re
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
if(!headers[k{{classPrefix}}ContentDispositionKey]) {
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[k{{classPrefix}}ContentDispositionKey];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
@interface {{classPrefix}}ApiClient ()
@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders;
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
@property (nonatomic, strong) NSArray<NSString*>* 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<AFURLRequestSerialization> *)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 <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
__weak id<SWGSanitizer> 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<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> 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 <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
AFHTTPRequestSerializer <AFURLRequestSerialization> * 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

View File

@ -1,22 +1,10 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <AFNetworking/AFNetworking.h>
#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 <AFURLRequestSerialization> *>* 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<SWGConfiguration>)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

View File

@ -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

View File

@ -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 <Foundation/Foundation.h>
@interface {{classPrefix}}BasicAuthTokenProvider : NSObject
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
@end

View File

@ -0,0 +1,78 @@
#import <Foundation/Foundation.h>
@class {{classPrefix}}Logger;
{{>licenceInfo}}
static NSString * const k{{classPrefix}}APIVersion = @"{{podVersion}}";
@protocol {{classPrefix}}Configuration <NSObject>
/**
* 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

View File

@ -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];

View File

@ -1,23 +1,18 @@
#import <Foundation/Foundation.h>
#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
*/

View File

@ -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

View File

@ -1,8 +0,0 @@
#import <Foundation/Foundation.h>
#import <AFNetworking/AFURLResponseSerialization.h>
{{>licenceInfo}}
@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer
@end

View File

@ -1,3 +1,4 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "JSONValueTransformer+ISO8601.h"
@implementation JSONValueTransformer (ISO8601)

View File

@ -1,5 +1,4 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <JSONModel/JSONValueTransformer.h>
{{>licenceInfo}}

View File

@ -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;
}

View File

@ -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`.

View File

@ -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;
}

View File

@ -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"];

View File

@ -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];

View File

@ -3,6 +3,8 @@
#import "{{classPrefix}}QueryParamCollection.h"
#import <ISO8601/ISO8601.h>
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]];
}

View File

@ -4,6 +4,8 @@
extern NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string);
extern NSString * const k{{classPrefix}}ApplicationJSONType;
@protocol {{classPrefix}}Sanitizer <NSObject>
/**

View File

@ -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

View File

@ -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}}

View File

@ -1,20 +1,18 @@
#import <Foundation/Foundation.h>
#import "{{classPrefix}}Object.h"
#import "{{classPrefix}}ApiClient.h"
@class {{classPrefix}}ApiClient;
{{>licenceInfo}}
@protocol {{classPrefix}}Api <NSObject>
@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

View File

@ -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"];

View File

@ -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

View File

@ -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 := <dependencies>
<exclude module="slf4j-log4j12"/>
<exclude module="grizzled-slf4j_2.9.1"/>

View File

@ -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 <SwaggerClient/SWGApiClient.h>
#import <SwaggerClient/SWGConfiguration.h>
#import <SwaggerClient/SWGDefaultConfiguration.h>
// load models
#import <SwaggerClient/SWGCategory.h>
#import <SwaggerClient/SWGOrder.h>
@ -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

View File

@ -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

View File

@ -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 <SWGApi>
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<SWGPet>*
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* 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<SWGPet>*
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* 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

View File

@ -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<SWGPet>*
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
/// @returns NSArray<SWGPet>*
///
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"];
@ -263,19 +242,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)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<SWGPet>*
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
/// @returns NSArray<SWGPet>*
///
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"];
@ -326,20 +303,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)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

View File

@ -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 <SWGApi>
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<NSString*, NSNumber*>*
-(NSNumber*) getInventoryWithCompletionHandler:
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* 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

View File

@ -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<NSString*, NSNumber*>*
-(NSNumber*) getInventoryWithCompletionHandler:
/// @returns NSDictionary<NSString*, NSNumber*>*
///
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"];
@ -193,20 +172,17 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSDictionary<NSString*, NSNumber*>*)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

View File

@ -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 <SWGApi>
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<SWGUser>*) body
///
/// @return
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<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*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
///
/// @return
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) 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

View File

@ -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<SWGUser>*) body
/// @returns void
///
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) 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<SWGUser>*) body
/// @returns void
///
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) 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

View File

@ -1,5 +1,4 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <JSONModel/JSONValueTransformer.h>
/**

View File

@ -1,3 +1,4 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "JSONValueTransformer+ISO8601.h"
@implementation JSONValueTransformer (ISO8601)

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#import "SWGObject.h"
#import "SWGApiClient.h"
@class SWGApiClient;
/**
* Swagger Petstore
@ -17,15 +17,13 @@
@protocol SWGApi <NSObject>
@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

View File

@ -1,13 +1,7 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <AFNetworking/AFNetworking.h>
#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<SWGConfiguration> 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<SWGResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* 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<SWGConfiguration>)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<SWGConfiguration>)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

View File

@ -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<SWGConfiguration> configuration;
@property (nonatomic, strong) NSArray<NSString*>* 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<SWGConfiguration>)configuration {
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)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<AFURLRequestSerialization> *)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 <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
__weak id<SWGSanitizer> 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<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> 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 <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
AFHTTPRequestSerializer <AFURLRequestSerialization> * 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<SWGConfiguration> 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<SWGConfiguration> 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

View File

@ -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 <Foundation/Foundation.h>
@interface SWGBasicAuthTokenProvider : NSObject
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
@end

View File

@ -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

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#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 <NSObject>
/**
* 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

View File

@ -0,0 +1,177 @@
#import <Foundation/Foundation.h>
#import "SWGConfiguration.h"
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters
*
* 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 <SWGConfiguration>
/**
* 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

View File

@ -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];

View File

@ -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;
}

View File

@ -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`.

View File

@ -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;
}

View File

@ -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];

View File

@ -15,6 +15,8 @@
extern NSString * SWGPercentEscapedStringFromString(NSString *string);
extern NSString * const kSWGApplicationJSONType;
@protocol SWGSanitizer <NSObject>
/**

View File

@ -3,6 +3,8 @@
#import "SWGQueryParamCollection.h"
#import <ISO8601/ISO8601.h>
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]];
}

View File

@ -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;
};

View File

@ -1,11 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0730"
version = "1.3">
<BuildAction>
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForTesting = "YES">
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6003F5AD195388D20070C39A"
@ -17,9 +23,13 @@
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug">
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference>
<TestableReference
skipped = "NO">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6003F5AD195388D20070C39A"
@ -29,8 +39,43 @@
</BuildableReference>
</TestableReference>
</Testables>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
useCustomWorkingDirectory = "NO">
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "6003F5AD195388D20070C39A"
BuildableName = "SwaggerClient_Tests.xctest"
BlueprintName = "SwaggerClient_Tests"
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>

View File

@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "0600"
LastUpgradeVersion = "0730"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
@ -23,10 +23,10 @@
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES"
buildConfiguration = "Debug">
shouldUseLaunchSchemeArgsEnv = "YES">
<Testables>
<TestableReference
skipped = "NO">
@ -48,15 +48,18 @@
ReferencedContainer = "container:SwaggerClient.xcodeproj">
</BuildableReference>
</MacroExpansion>
<AdditionalOptions>
</AdditionalOptions>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
buildConfiguration = "Debug"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
@ -72,10 +75,10 @@
</AdditionalOptions>
</LaunchAction>
<ProfileAction
buildConfiguration = "Release"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
buildConfiguration = "Release"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">

View File

@ -10,7 +10,7 @@
#import <SwaggerClient/SWGApiClient.h>
#import <SwaggerClient/SWGPet.h>
#import <SwaggerClient/SWGPetApi.h>
#import <SwaggerClient/SWGConfiguration.h>
#import <SwaggerClient/SWGDefaultConfiguration.h>
@interface SWGViewController ()
@ -22,7 +22,7 @@
{
[super viewDidLoad];
SWGConfiguration *config = [SWGConfiguration sharedConfig];
SWGDefaultConfiguration *config = [SWGDefaultConfiguration sharedConfig];
config.debug = YES;
SWGPetApi *api = [[SWGPetApi alloc] init];

View File

@ -9,7 +9,7 @@
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>

View File

@ -7,7 +7,7 @@
<key>CFBundleExecutable</key>
<string>${EXECUTABLE_NAME}</string>
<key>CFBundleIdentifier</key>
<string>org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}</string>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundlePackageType</key>

View File

@ -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 <SwaggerClient/SWGApiClient.h>
#import <SwaggerClient/SWGConfiguration.h>
#import <SwaggerClient/SWGDefaultConfiguration.h>
// load models
#import <SwaggerClient/SWGCategory.h>
#import <SwaggerClient/SWGOrder.h>
@ -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

View File

@ -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

View File

@ -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 <SWGApi>
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<SWGPet>*
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* 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<SWGPet>*
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* 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

View File

@ -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<SWGPet>*
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
/// @returns NSArray<SWGPet>*
///
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"];
@ -263,19 +242,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)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<SWGPet>*
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
/// @returns NSArray<SWGPet>*
///
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"];
@ -326,20 +303,17 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)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

View File

@ -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 <SWGApi>
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<NSString*, NSNumber*>*
-(NSNumber*) getInventoryWithCompletionHandler:
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* 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

View File

@ -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<NSString*, NSNumber*>*
-(NSNumber*) getInventoryWithCompletionHandler:
/// @returns NSDictionary<NSString*, NSNumber*>*
///
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"];
@ -193,20 +172,17 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSDictionary<NSString*, NSNumber*>*)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

View File

@ -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 <SWGApi>
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<SWGUser>*) body
///
/// @return
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<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*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
///
/// @return
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) 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

View File

@ -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<SWGUser>*) body
/// @returns void
///
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) 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<SWGUser>*) body
/// @returns void
///
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) 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

View File

@ -1,5 +1,4 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <JSONModel/JSONValueTransformer.h>
/**

View File

@ -1,3 +1,4 @@
#import <ISO8601/NSDate+ISO8601.h>
#import "JSONValueTransformer+ISO8601.h"
@implementation JSONValueTransformer (ISO8601)

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#import "SWGObject.h"
#import "SWGApiClient.h"
@class SWGApiClient;
/**
* Swagger Petstore
@ -17,15 +17,13 @@
@protocol SWGApi <NSObject>
@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

View File

@ -1,13 +1,7 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <AFNetworking/AFNetworking.h>
#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<SWGConfiguration> 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<SWGResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* 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<SWGConfiguration>)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<SWGConfiguration>)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

View File

@ -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<SWGConfiguration> configuration;
@property (nonatomic, strong) NSArray<NSString*>* 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<SWGConfiguration>)configuration {
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)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<AFURLRequestSerialization> *)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 <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
__weak id<SWGSanitizer> 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<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> 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 <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
AFHTTPRequestSerializer <AFURLRequestSerialization> * 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<SWGConfiguration> 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<SWGConfiguration> 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

View File

@ -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 <Foundation/Foundation.h>
@interface SWGBasicAuthTokenProvider : NSObject
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
@end

View File

@ -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

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#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 <NSObject>
/**
* 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

View File

@ -0,0 +1,177 @@
#import <Foundation/Foundation.h>
#import "SWGConfiguration.h"
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters
*
* 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 <SWGConfiguration>
/**
* 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

View File

@ -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];

View File

@ -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

View File

@ -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;
}

Some files were not shown because too many files have changed in this diff Show More