From 14ef333ba561532b46b777b279424dd27cd9ece4 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Fri, 21 Aug 2015 14:40:05 -0700 Subject: [PATCH 01/10] reconfigured fotition-objc client for new codegen --- .../languages/FotitionClientCodegen.java | 325 ++++---- .../fotition-objc/ApiClient-body.mustache | 729 ++++++++++++++++++ .../fotition-objc/ApiClient-header.mustache | 203 +++++ .../fotition-objc/Configuration-body.mustache | 132 ++++ .../Configuration-header.mustache | 128 +++ .../FTConfiguration-header.mustache | 56 -- .../src/main/resources/fotition-objc/FTFile.h | 14 - .../src/main/resources/fotition-objc/FTFile.m | 26 - .../main/resources/fotition-objc/FTObject.h | 5 - .../main/resources/fotition-objc/FTObject.m | 4 - .../fotition-objc/FotitionAPIClient.h | 216 ------ .../fotition-objc/FotitionAPIClient.m | 686 ---------------- ...he => FotitionConfiguration-body.mustache} | 8 +- .../JSONRequestSerializer-body.mustache | 35 + .../JSONRequestSerializer-header.mustache | 5 + .../JSONResponseSerializer-body.mustache | 39 + .../JSONResponseSerializer-header.mustache | 6 + .../fotition-objc/Object-body.mustache | 4 + .../fotition-objc/Object-header.mustache | 5 + .../resources/fotition-objc/Podfile.mustache | 5 - ...n.m => QueryParamCollection-body.mustache} | 4 +- ...h => QueryParamCollection-header.mustache} | 2 +- .../resources/fotition-objc/README.mustache | 23 + .../resources/fotition-objc/api-body.mustache | 181 ++--- .../fotition-objc/api-header.mustache | 39 +- .../apiBodyResponseWithContainer.mustache | 38 - .../apiNonPrimitiveResponse.mustache | 24 - .../apiPrimitiveResponse.mustache | 36 - .../fotition-objc/model-body.mustache | 19 +- .../fotition-objc/model-header.mustache | 13 +- .../resources/fotition-objc/podspec.mustache | 31 + .../fotition-objc/voidResponse.mustache | 16 - 32 files changed, 1634 insertions(+), 1423 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-header.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-header.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.h delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.m delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.h delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.m delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.h delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.m rename modules/swagger-codegen/src/main/resources/fotition-objc/{FTConfiguration-body.mustache => FotitionConfiguration-body.mustache} (94%) create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-header.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/Object-body.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/Object-header.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/Podfile.mustache rename modules/swagger-codegen/src/main/resources/fotition-objc/{FTQueryParamCollection.m => QueryParamCollection-body.mustache} (70%) rename modules/swagger-codegen/src/main/resources/fotition-objc/{FTQueryParamCollection.h => QueryParamCollection-header.mustache} (80%) create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/README.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/apiBodyResponseWithContainer.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/apiNonPrimitiveResponse.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/apiPrimitiveResponse.mustache create mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/podspec.mustache delete mode 100644 modules/swagger-codegen/src/main/resources/fotition-objc/voidResponse.mustache diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FotitionClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FotitionClientCodegen.java index 50c58a050a6..e225d6c6537 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FotitionClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/FotitionClientCodegen.java @@ -18,65 +18,47 @@ public class FotitionClientCodegen extends DefaultCodegen implements CodegenConfig { - protected Set foundationClasses = new HashSet(); - protected String sourceFolder = "fotition-objc-client"; + protected String podName = "FotitionClient"; + protected String podVersion = "1.0.0"; protected String classPrefix = "FT"; - protected String projectName = "fotition-objc-client"; - - public FotitionClientCodegen() { - outputFolder = "generated-code" + File.separator + "fotition-objc"; + + public ObjcClientCodegen() { + super(); + + outputFolder = "generated-code" + File.separator + "objc"; modelTemplateFiles.put("model-header.mustache", ".h"); modelTemplateFiles.put("model-body.mustache", ".m"); apiTemplateFiles.put("api-header.mustache", ".h"); apiTemplateFiles.put("api-body.mustache", ".m"); templateDir = "fotition-objc"; - modelPackage = ""; - - defaultIncludes = new HashSet( - Arrays.asList( - "bool", - "BOOL", - "int", - "NSString", - "NSObject", - "NSArray", - "NSNumber", - "NSDate", - "NSDictionary", - "NSMutableArray", - "NSMutableDictionary") - ); - languageSpecificPrimitives = new HashSet( - Arrays.asList( - "NSNumber", - "NSString", - "NSObject", - "NSDate", - "bool", - "BOOL") - ); - - // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm - reservedWords = new HashSet( - Arrays.asList( - "auto", "else", "long", "switch", - "break", "enum", "register", "typedef", - "case", "extern", "return", "union", - "char", "float", "short", "unsigned", - "const", "for", "signed", "void", - "continue", "goto", "sizeof", "volatile", - "default", "if", "id", "static", "while", - "do", "int", "struct", "_Packed", - "double", "protocol", "interface", "implementation", - "NSObject", "NSInteger", "NSNumber", "CGFloat", - "property", "nonatomic", "retain", "strong", - "weak", "unsafe_unretained", "readwrite", "readonly" - )); - - typeMapping = new HashMap(); + + defaultIncludes.clear(); + defaultIncludes.add("bool"); + defaultIncludes.add("BOOL"); + defaultIncludes.add("int"); + defaultIncludes.add("NSURL"); + defaultIncludes.add("NSString"); + defaultIncludes.add("NSObject"); + defaultIncludes.add("NSArray"); + defaultIncludes.add("NSNumber"); + defaultIncludes.add("NSDate"); + defaultIncludes.add("NSDictionary"); + defaultIncludes.add("NSMutableArray"); + defaultIncludes.add("NSMutableDictionary"); + + languageSpecificPrimitives.clear(); + languageSpecificPrimitives.add("NSNumber"); + languageSpecificPrimitives.add("NSString"); + languageSpecificPrimitives.add("NSObject"); + languageSpecificPrimitives.add("NSDate"); + languageSpecificPrimitives.add("NSURL"); + languageSpecificPrimitives.add("bool"); + languageSpecificPrimitives.add("BOOL"); + + typeMapping.clear(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "NSDate"); + typeMapping.put("date", "NSDate"); typeMapping.put("DateTime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); @@ -90,71 +72,102 @@ public FotitionClientCodegen() { typeMapping.put("number", "NSNumber"); typeMapping.put("List", "NSArray"); typeMapping.put("object", "NSObject"); - + typeMapping.put("file", "NSURL"); + + // ref: http://www.tutorialspoint.com/objective_c/objective_c_basic_syntax.htm + reservedWords = new HashSet( + Arrays.asList( + "auto", "else", "long", "switch", + "break", "enum", "register", "typedef", + "case", "extern", "return", "union", + "char", "float", "short", "unsigned", + "const", "for", "signed", "void", + "continue", "goto", "sizeof", "volatile", + "default", "if", "id", "static", "while", + "do", "int", "struct", "_Packed", + "double", "protocol", "interface", "implementation", + "NSObject", "NSInteger", "NSNumber", "CGFloat", + "property", "nonatomic", "retain", "strong", + "weak", "unsafe_unretained", "readwrite", "readonly", + "description" + )); + importMapping = new HashMap(); - + foundationClasses = new HashSet( - Arrays.asList( - "NSNumber", - "NSObject", - "NSString", - "NSDate", - "NSDictionary") - ); - + Arrays.asList( + "NSNumber", + "NSObject", + "NSString", + "NSDate", + "NSURL", + "NSDictionary") + ); + instantiationTypes.put("array", "NSMutableArray"); instantiationTypes.put("map", "NSMutableDictionary"); - - cliOptions.add(new CliOption("classPrefix", "prefix for generated classes")); - cliOptions.add(new CliOption("sourceFolder", "source folder for generated code")); - cliOptions.add(new CliOption("projectName", "name of the Xcode project in generated Podfile")); + + cliOptions.clear(); + cliOptions.add(new CliOption("classPrefix", "prefix for generated classes (convention: Abbreviation of pod name e.g. `HN` for `HackerNews`), default: `SWG`")); + cliOptions.add(new CliOption("podName", "cocoapods package name (convention: CameCase), default: `SwaggerClient`")); + cliOptions.add(new CliOption("podVersion", "cocoapods package version, default: `1.0.0`")); } - + public CodegenType getTag() { return CodegenType.CLIENT; } - + public String getName() { - return "fotition-objc"; + return "objc"; } - + public String getHelp() { - return "Generates an Objective-C client library for Fotition."; + return "Generates an Objective-C client library."; } - + @Override public void processOpts() { super.processOpts(); - - if (additionalProperties.containsKey("sourceFolder")) { - this.setSourceFolder((String) additionalProperties.get("sourceFolder")); + + if (additionalProperties.containsKey("podName")) { + setPodName((String) additionalProperties.get("podName")); } - - if (additionalProperties.containsKey("classPrefix")) { - this.setClassPrefix((String) additionalProperties.get("classPrefix")); + + if (additionalProperties.containsKey("podVersion")) { + setPodVersion((String) additionalProperties.get("podVersion")); } - - if (additionalProperties.containsKey("projectName")) { - this.setProjectName((String) additionalProperties.get("projectName")); - } else { - additionalProperties.put("projectName", projectName); + + if (additionalProperties.containsKey("classPrefix")) { + setClassPrefix((String) additionalProperties.get("classPrefix")); } - - supportingFiles.add(new SupportingFile("FTObject.h", sourceFolder, "FTObject.h")); - supportingFiles.add(new SupportingFile("FTObject.m", sourceFolder, "FTObject.m")); - supportingFiles.add(new SupportingFile("FTQueryParamCollection.h", sourceFolder, "FTQueryParamCollection.h")); - supportingFiles.add(new SupportingFile("FTQueryParamCollection.m", sourceFolder, "FTQueryParamCollection.m")); - supportingFiles.add(new SupportingFile("FotitionAPIClient.h", sourceFolder, "FotitionAPIClient.h")); - supportingFiles.add(new SupportingFile("FotitionAPIClient.m", sourceFolder, "FotitionAPIClient.m")); - supportingFiles.add(new SupportingFile("FTFile.h", sourceFolder, "FTFile.h")); - supportingFiles.add(new SupportingFile("FTFile.m", sourceFolder, "FTFile.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); - supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); - supportingFiles.add(new SupportingFile("FTConfiguration-body.mustache", sourceFolder, "FTConfiguration.m")); - supportingFiles.add(new SupportingFile("FTConfiguration-header.mustache", sourceFolder, "FTConfiguration.h")); - supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); + + additionalProperties.put("podName", podName); + additionalProperties.put("podVersion", podVersion); + additionalProperties.put("classPrefix", classPrefix); + + String swaggerFolder = podName; + + modelPackage = swaggerFolder; + apiPackage = swaggerFolder; + + supportingFiles.add(new SupportingFile("Object-header.mustache", swaggerFolder, classPrefix + "Object.h")); + supportingFiles.add(new SupportingFile("Object-body.mustache", swaggerFolder, classPrefix + "Object.m")); + supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", swaggerFolder, classPrefix + "QueryParamCollection.h")); + supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", swaggerFolder, classPrefix + "QueryParamCollection.m")); + supportingFiles.add(new SupportingFile("ApiClient-header.mustache", swaggerFolder, classPrefix + "ApiClient.h")); + supportingFiles.add(new SupportingFile("ApiClient-body.mustache", swaggerFolder, classPrefix + "ApiClient.m")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.h")); + supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", swaggerFolder, classPrefix + "JSONResponseSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.m")); + supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", swaggerFolder, classPrefix + "JSONRequestSerializer.h")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", swaggerFolder, "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", swaggerFolder, "JSONValueTransformer+ISO8601.h")); + supportingFiles.add(new SupportingFile("Configuration-body.mustache", swaggerFolder, classPrefix + "Configuration.m")); + supportingFiles.add(new SupportingFile("Configuration-header.mustache", swaggerFolder, classPrefix + "Configuration.h")); + supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } - + @Override public String toInstantiationType(Property p) { if (p instanceof MapProperty) { @@ -169,7 +182,7 @@ public String toInstantiationType(Property p) { return null; } } - + @Override public String getTypeDeclaration(String name) { if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) { @@ -178,7 +191,7 @@ public String getTypeDeclaration(String name) { return name + "*"; } } - + @Override public String getSwaggerType(Property p) { String swaggerType = super.getSwaggerType(p); @@ -193,36 +206,47 @@ public String getSwaggerType(Property p) { } return toModelName(type); } - + @Override public String getTypeDeclaration(Property p) { if (p instanceof ArrayProperty) { ArrayProperty ap = (ArrayProperty) p; Property inner = ap.getItems(); String innerType = getSwaggerType(inner); - + + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) { + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + } + // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray*' + // return container type with pointer, e.g. `NSArray* /* NSString */' if (languageSpecificPrimitives.contains(innerType)) { - return getSwaggerType(p) + "*"; + return getSwaggerType(p) + "*" + " /* " + innerTypeDeclaration + " */"; } - // In this codition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' + // return container type combine inner type with pointer, e.g. `NSArray*' + else { + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + String innerTypeDeclaration = getTypeDeclaration(inner); - + if (innerTypeDeclaration.endsWith("*")) { innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); } - - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */"; } else { String swaggerType = getSwaggerType(p); - + // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', // return type of p with pointer, e.g. `NSNumber*' if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { + foundationClasses.contains(swaggerType)) { return swaggerType + "*"; } // In this codition, type of p is c primitive type, e.g. `bool', @@ -230,24 +254,24 @@ public String getTypeDeclaration(Property p) { else if (languageSpecificPrimitives.contains(swaggerType)) { return swaggerType; } - // In this codition, type of p is objective-c object type, e.g. `FTPet', - // return type of p with pointer, e.g. `FTPet*' + // In this codition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `SWGPet*' else { return swaggerType + "*"; } } } - + @Override public String toModelName(String type) { type = type.replaceAll("[^0-9a-zA-Z_]", "_"); - + // language build-in classes if (typeMapping.keySet().contains(type) || - foundationClasses.contains(type) || - importMapping.values().contains(type) || - defaultIncludes.contains(type) || - languageSpecificPrimitives.contains(type)) { + foundationClasses.contains(type) || + importMapping.values().contains(type) || + defaultIncludes.contains(type) || + languageSpecificPrimitives.contains(type)) { return camelize(type); } // custom classes @@ -255,13 +279,13 @@ public String toModelName(String type) { return classPrefix + camelize(type); } } - + @Override public String toModelFilename(String name) { // should be the same as the model name return toModelName(name); } - + @Override protected void setNonArrayMapProperty(CodegenProperty property, String type) { super.setNonArrayMapProperty(property, type); @@ -271,92 +295,93 @@ protected void setNonArrayMapProperty(CodegenProperty property, String type) { property.setter = "initWithValues"; } } - + @Override public String toModelImport(String name) { - if ("".equals(modelPackage())) { - return name; - } else { - return modelPackage() + "." + name; - } + return name; } - + @Override public String toDefaultValue(Property p) { return null; } - + @Override public String apiFileFolder() { - return outputFolder + File.separator + sourceFolder; + return outputFolder + File.separatorChar + apiPackage(); } - + @Override public String modelFileFolder() { - return outputFolder + File.separator + sourceFolder; + return outputFolder + File.separatorChar + modelPackage(); } - + @Override public String toApiName(String name) { return classPrefix + camelize(name) + "Api"; } - + public String toApiFilename(String name) { return classPrefix + camelize(name) + "Api"; } - + @Override public String toVarName(String name) { // replace non-word characters to `_` // e.g. `created-at` to `created_at` name = name.replaceAll("[^a-zA-Z0-9_]", "_"); - + // if it's all upper case, do noting if (name.matches("^[A-Z_]$")) { return name; } - + // camelize (lower first character) the variable name // e.g. `pet_id` to `petId` name = camelize(name, true); - + // for reserved word or word starting with number, prepend `_` if (reservedWords.contains(name) || name.matches("^\\d.*")) { name = escapeReservedWord(name); } - + return name; } - + @Override public String toParamName(String name) { // should be the same as variable name return toVarName(name); } - + public String escapeReservedWord(String name) { return "_" + name; } - + @Override public String toOperationId(String operationId) { + // throw exception if method name is empty + if (StringUtils.isEmpty(operationId)) { + throw new RuntimeException("Empty method name (operationId) not allowed"); + } + // method name cannot use reserved keyword, e.g. return if (reservedWords.contains(operationId)) { throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); } - + return camelize(operationId, true); } - - public void setSourceFolder(String sourceFolder) { - this.sourceFolder = sourceFolder; - } - + public void setClassPrefix(String classPrefix) { this.classPrefix = classPrefix; } - - public void setProjectName(String projectName) { - this.projectName = projectName; + + public void setPodName(String podName) { + this.podName = podName; + } + + public void setPodVersion(String podVersion) { + this.podVersion = podVersion; } } diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-body.mustache new file mode 100644 index 00000000000..b7643de6ddd --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-body.mustache @@ -0,0 +1,729 @@ +#import "{{classPrefix}}ApiClient.h" + +NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject"; + +static long requestId = 0; +static bool offlineState = false; +static NSMutableSet * queuedRequests = nil; +static bool cacheEnabled = false; +static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; +static void (^reachabilityChangeBlock)(int); + +@implementation {{classPrefix}}ApiClient + +- (instancetype)init { + NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host]; + return [self initWithBaseURL:[NSURL URLWithString:baseUrl]]; +} + +- (instancetype)initWithBaseURL:(NSURL *)url { + self = [super initWithBaseURL:url]; + if (self) { + self.requestSerializer = [AFJSONRequestSerializer serializer]; + self.responseSerializer = [AFJSONResponseSerializer serializer]; + // configure reachability + [self configureCacheReachibility]; + } + 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 - Setter Methods + ++ (void) setOfflineState:(BOOL) state { + offlineState = state; +} + ++ (void) setCacheEnabled:(BOOL)enabled { + cacheEnabled = enabled; +} + +- (void)setHeaderValue:(NSString*) value + forKey:(NSString*) forKey { + [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; +} + +#pragma mark - Log Methods + +- (void)logResponse:(AFHTTPRequestOperation *)operation + forRequest:(NSURLRequest *)request + error:(NSError*)error { + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + + NSString *message = [NSString stringWithFormat:@"\n[DEBUG] Request body \n~BEGIN~\n %@\n~END~\n"\ + "[DEBUG] HTTP Response body \n~BEGIN~\n %@\n~END~\n", + [[NSString alloc] initWithData:request.HTTPBody encoding:NSUTF8StringEncoding], + operation.responseString]; + + if (config.loggingFileHanlder) { + [config.loggingFileHanlder seekToEndOfFile]; + [config.loggingFileHanlder writeData:[message dataUsingEncoding:NSUTF8StringEncoding]]; + } + + NSLog(@"%@", message); +} + +#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 - Utility Methods + +/* + * Detect `Accept` from accepts + */ ++ (NSString *) selectHeaderAccept:(NSArray *)accepts +{ + if (accepts == nil || [accepts count] == 0) { + return @""; + } + + NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; + [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerAccepts addObject:[obj lowercaseString]]; + }]; + + + if ([lowerAccepts containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return [lowerAccepts componentsJoinedByString:@", "]; + } +} + +/* + * Detect `Content-Type` from contentTypes + */ ++ (NSString *) selectHeaderContentType:(NSArray *)contentTypes +{ + if (contentTypes == nil || [contentTypes count] == 0) { + return @"application/json"; + } + + NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; + [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [lowerContentTypes addObject:[obj lowercaseString]]; + }]; + + if ([lowerContentTypes containsObject:@"application/json"]) { + return @"application/json"; + } + else { + return lowerContentTypes[0]; + } +} + ++ (NSString*)escape:(id)unescaped { + if([unescaped isKindOfClass:[NSString class]]){ + return (NSString *)CFBridgingRelease + (CFURLCreateStringByAddingPercentEscapes( + NULL, + (__bridge CFStringRef) unescaped, + NULL, + (CFStringRef)@"!*'();:@&=+$,/?%#[]", + kCFStringEncodingUTF8)); + } + else { + return [NSString stringWithFormat:@"%@", unescaped]; + } +} + +#pragma mark - Request Methods + ++(unsigned long)requestQueueSize { + return [queuedRequests count]; +} + ++(NSNumber*) nextRequestId { + @synchronized(self) { + long nextId = ++requestId; + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"got id %ld", nextId); + return [NSNumber numberWithLong:nextId]; + } +} + ++(NSNumber*) queueRequest { + NSNumber* requestId = [{{classPrefix}}ApiClient nextRequestId]; + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"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) { + if([obj intValue] == [requestId intValue]) { + return YES; + } + else { + return NO; + } + }]; + + if(matchingItems.count == 1) { + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"removing request id %@", requestId); + [queuedRequests removeObject:requestId]; + return YES; + } + else { + return NO; + } +} + +#pragma mark - Reachability Methods + ++(AFNetworkReachabilityStatus) getReachabilityStatus { + return reachabilityStatus; +} + ++(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { + reachabilityChangeBlock = changeBlock; +} + +- (void) configureCacheReachibility { + [self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { + reachabilityStatus = status; + switch (status) { + case AFNetworkReachabilityStatusUnknown: + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); + [{{classPrefix}}ApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusNotReachable: + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); + [{{classPrefix}}ApiClient setOfflineState:true]; + break; + + case AFNetworkReachabilityStatusReachableViaWWAN: + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); + [{{classPrefix}}ApiClient setOfflineState:false]; + break; + + case AFNetworkReachabilityStatusReachableViaWiFi: + if([[{{classPrefix}}Configuration sharedConfig] debug]) + NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); + [{{classPrefix}}ApiClient setOfflineState:false]; + break; + default: + break; + } + + // call the reachability block, if configured + if(reachabilityChangeBlock != nil) { + reachabilityChangeBlock(status); + } + }]; + + [self.reachabilityManager startMonitoring]; +} + +#pragma mark - Deserialize methods + +- (id) deserialize:(id) data class:(NSString *) class { + NSRegularExpression *regexp = nil; + NSTextCheckingResult *match = nil; + NSMutableArray *resultArray = nil; + NSMutableDictionary *resultDict = nil; + NSString *innerType = nil; + + // return nil if data is nil or class is nil + if (!data || !class) { + return nil; + } + + // remove "*" from class, if ends with "*" + if ([class hasSuffix:@"*"]) { + class = [class substringToIndex:[class length] - 1]; + } + + // pure object + if ([class isEqualToString:@"NSObject"]) { + return [[NSObject alloc] init]; + } + + // list of models + NSString *arrayOfModelsPat = @"NSArray<(.+)>"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + } + ]; + + return resultArray; + } + + // list of primitives + NSString *arrayOfPrimitivesPat = @"NSArray\\* /\\* (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + innerType = [class substringWithRange:[match rangeAtIndex:1]]; + + resultArray = [NSMutableArray arrayWithCapacity:[data count]]; + [data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + [resultArray addObject:[self deserialize:obj class:innerType]]; + }]; + + return resultArray; + } + + // map + NSString *dictPat = @"NSDictionary\\* /\\* (.+?), (.+) \\*/"; + regexp = [NSRegularExpression regularExpressionWithPattern:dictPat + options:NSRegularExpressionCaseInsensitive + error:nil]; + match = [regexp firstMatchInString:class + options:0 + range:NSMakeRange(0, [class length])]; + + if (match) { + NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]]; + + resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]]; + [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resultDict setValue:[self deserialize:obj class:valueType] forKey:key]; + }]; + + return resultDict; + } + + // primitives + NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"]; + + if ([primitiveTypes containsObject:class]) { + if ([class isEqualToString:@"NSString"]) { + return [NSString stringWithString:data]; + } + else if ([class isEqualToString:@"NSDate"]) { + return [NSDate dateWithISO8601String:data]; + } + else if ([class isEqualToString:@"NSNumber"]) { + // NSNumber from NSNumber + if ([data isKindOfClass:[NSNumber class]]) { + return data; + } + else if ([data isKindOfClass:[NSString class]]) { + // NSNumber (NSCFBoolean) from NSString + if ([[data lowercaseString] isEqualToString:@"true"] || [[data lowercaseString] isEqualToString:@"false"]) { + return [NSNumber numberWithBool:[data boolValue]]; + // NSNumber from NSString + } else { + NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; + formatter.numberStyle = NSNumberFormatterDecimalStyle; + return [formatter numberFromString:data]; + } + } + } + } + + // model + Class ModelClass = NSClassFromString(class); + if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) { + return [[ModelClass alloc] initWithDictionary:data error:nil]; + } + + return nil; +} + +#pragma mark - Operation Methods + +- (void) operationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id response) { + if([self executeRequestWithId:requestId]) { + if([[{{classPrefix}}Configuration sharedConfig] debug]) { + [self logResponse:operation forRequest:request error:nil]; + } + completionBlock(response, nil); + } + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + if([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if(operation.responseObject) { + // Add in the (parsed) response body. + userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; + } + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if([[{{classPrefix}}Configuration sharedConfig] debug]) + [self logResponse:nil forRequest:request error:augmentedError]; + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; +} + +- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request + requestId: (NSNumber *) requestId + completionBlock: (void (^)(id, NSError *))completionBlock { + AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request + success:^(AFHTTPRequestOperation *operation, id responseObject) { + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + NSString *directory = nil; + if (config.tempFolderPath) { + directory = config.tempFolderPath; + } + else { + directory = NSTemporaryDirectory(); + } + + NSDictionary *headers = operation.response.allHeaderFields; + NSString *filename = nil; + if ([headers objectForKey:@"Content-Disposition"]) { + + NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?"; + NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern + options:NSRegularExpressionCaseInsensitive + error:nil]; + NSString *contentDispositionHeader = [headers objectForKey:@"Content-Disposition"]; + NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader + options:0 + range:NSMakeRange(0, [contentDispositionHeader length])]; + filename = [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]]; + } + else { + filename = [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]]; + } + + NSString *filepath = [directory stringByAppendingPathComponent:filename]; + NSURL *file = [NSURL fileURLWithPath:filepath]; + + [operation.responseData writeToURL:file atomically:YES]; + completionBlock(file, nil); + } failure:^(AFHTTPRequestOperation *operation, NSError *error) { + + if ([self executeRequestWithId:requestId]) { + NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; + if (operation.responseObject) { + userInfo[{{classPrefix}}ResponseObjectErrorKey] = operation.responseObject; + } + + NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; + + if ([[{{classPrefix}}Configuration sharedConfig] debug]) { + [self logResponse:nil forRequest:request error:augmentedError]; + } + + completionBlock(nil, augmentedError); + } + }]; + + [self.operationQueue addOperation:op]; +} + +#pragma mark - Perform Request Methods + +-(NSNumber*) requestWithCompletionBlock: (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 { + NSAssert(false, @"unsupport request type %@", requestContentType); + } + + // setting response serializer + if ([responseContentType isEqualToString:@"application/json"]) { + self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer]; + } + else { + self.responseSerializer = [AFHTTPResponseSerializer serializer]; + } + + // sanitize parameters + pathParams = [self sanitizeForSerialization:pathParams]; + queryParams = [self sanitizeForSerialization:queryParams]; + headerParams = [self sanitizeForSerialization:headerParams]; + formParams = [self sanitizeForSerialization:formParams]; + body = [self sanitizeForSerialization:body]; + + // auth setting + [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; + + NSMutableString *resourcePath = [NSMutableString stringWithString:path]; + [pathParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + [resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", key, @"}"]] + withString:[SWGApiClient escape:obj]]; + }]; + + 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]; + if (files.count > 0) { + request = [self.requestSerializer multipartFormRequestWithMethod:@"POST" + URLString:urlString + parameters:nil + constructingBodyWithBlock:^(id formData) { + [formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSData *data = [obj dataUsingEncoding:NSUTF8StringEncoding]; + [formData appendPartWithFormData:data name:key]; + }]; + [files enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + NSURL *filePath = (NSURL *)obj; + [formData appendPartWithFileURL:filePath name:key error:nil]; + }]; + } error:nil]; + } + else { + if (formParams) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:formParams + error:nil]; + } + if (body) { + request = [self.requestSerializer requestWithMethod:method + URLString:urlString + parameters:body + error:nil]; + } + } + + // request cache + BOOL hasHeaderParams = false; + if(headerParams != nil && [headerParams count] > 0) { + hasHeaderParams = true; + } + if(offlineState) { + NSLog(@"%@ cache forced", resourcePath); + [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; + } + else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { + NSLog(@"%@ cache enabled", resourcePath); + [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; + } + else { + NSLog(@"%@ cache disabled", resourcePath); + [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; + } + + if(hasHeaderParams){ + for(NSString * key in [headerParams keyEnumerator]){ + [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; + } + } + [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; + + + // Always disable cookies! + [request setHTTPShouldHandleCookies:NO]; + + NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest]; + if ([responseType isEqualToString:@"NSURL*"]) { + [self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock(data, error); + }]; + } + else { + [self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) { + completionBlock([self deserialize:data class:responseType], error); + }]; + } + return requestId; +} + +#pragma mark - + +- (NSString*) pathWithQueryParamsToString:(NSString*) path + queryParams:(NSDictionary*) queryParams { + NSString * separator = nil; + int counter = 0; + + NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; + if(queryParams != nil){ + for(NSString * key in [queryParams keyEnumerator]){ + if(counter == 0) separator = @"?"; + else separator = @"&"; + id queryParam = [queryParams valueForKey:key]; + if([queryParam isKindOfClass:[NSString class]]){ + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiClient escape:key], [{{classPrefix}}ApiClient escape:[queryParams valueForKey:key]]]]; + } + else if([queryParam isKindOfClass:[{{classPrefix}}QueryParamCollection class]]){ + {{classPrefix}}QueryParamCollection * coll = ({{classPrefix}}QueryParamCollection*) queryParam; + NSArray* values = [coll values]; + NSString* format = [coll format]; + + if([format isEqualToString:@"csv"]) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; + + } + else if([format isEqualToString:@"tsv"]) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; + + } + else if([format isEqualToString:@"pipes"]) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; + + } + else if([format isEqualToString:@"multi"]) { + for(id obj in values) { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; + counter += 1; + } + + } + } + else { + [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, + [{{classPrefix}}ApiClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; + } + + counter += 1; + } + } + return requestUrl; +} + +/** + * Update header and query params based on authentication settings + */ +- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers + queryParams:(NSDictionary *__autoreleasing *)querys + WithAuthSettings:(NSArray *)authSettings { + + if (!authSettings || [authSettings count] == 0) { + return; + } + + NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; + NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; + + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + for (NSString *auth in authSettings) { + NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; + + if (authSetting) { + if ([authSetting[@"in"] isEqualToString:@"header"]) { + [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + else if ([authSetting[@"in"] isEqualToString:@"query"]) { + [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; + } + } + } + + *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; + *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; +} + +- (id) sanitizeForSerialization:(id) object { + if (object == nil) { + return nil; + } + else if ([object isKindOfClass:[NSString class]] || [object isKindOfClass:[NSNumber class]] || [object isKindOfClass:[SWGQueryParamCollection class]]) { + return object; + } + else if ([object isKindOfClass:[NSDate class]]) { + return [object ISO8601String]; + } + else if ([object isKindOfClass:[NSArray class]]) { + NSMutableArray *sanitizedObjs = [NSMutableArray arrayWithCapacity:[object count]]; + [object enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { + if (obj) { + [sanitizedObjs addObject:[self sanitizeForSerialization:obj]]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[NSDictionary class]]) { + NSMutableDictionary *sanitizedObjs = [NSMutableDictionary dictionaryWithCapacity:[object count]]; + [object enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) { + if (obj) { + [sanitizedObjs setValue:[self sanitizeForSerialization:obj] forKey:key]; + } + }]; + return sanitizedObjs; + } + else if ([object isKindOfClass:[SWGObject class]]) { + return [object toDictionary]; + } + else { + NSException *e = [NSException + exceptionWithName:@"InvalidObjectArgumentException" + reason:[NSString stringWithFormat:@"*** The argument object: %@ is invalid", object] + userInfo:nil]; + @throw e; + } +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-header.mustache new file mode 100644 index 00000000000..eba62705879 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/ApiClient-header.mustache @@ -0,0 +1,203 @@ +#import +#import +#import +#import "{{classPrefix}}JSONResponseSerializer.h" +#import "{{classPrefix}}JSONRequestSerializer.h" +#import "{{classPrefix}}QueryParamCollection.h" +#import "{{classPrefix}}Configuration.h" + +/** + * 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. + */ + +{{#models}}{{#model}}#import "{{classname}}.h" +{{/model}}{{/models}} + +@class {{classPrefix}}Configuration; + +/** + * A key for `NSError` user info dictionaries. + * + * The corresponding value is the parsed response body for an HTTP error. + */ +extern NSString *const {{classPrefix}}ResponseObjectErrorKey; + + +@interface {{classPrefix}}ApiClient : AFHTTPRequestOperationManager + +@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; +@property(nonatomic, assign) NSTimeInterval timeoutInterval; +@property(nonatomic, readonly) NSOperationQueue* queue; + +/** + * Clears Cache + */ ++(void)clearCache; + +/** + * Turns on cache + * + * @param enabled If the cached is enable, must be `YES` or `NO` + */ ++(void)setCacheEnabled:(BOOL) enabled; + +/** + * Gets the request queue size + * + * @return The size of `queuedRequests` static variable. + */ ++(unsigned long)requestQueueSize; + +/** + * Sets the client unreachable + * + * @param state off line state, must be `YES` or `NO` + */ ++(void) setOfflineState:(BOOL) state; + +/** + * 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; + +/** + * Gets URL encoded NSString + * + * @param unescaped The string which will be escaped. + * + * @return The escaped string. + */ ++(NSString*) escape:(id)unescaped; + +/** + * 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; + +/** + * Detects Accept header from accepts NSArray + * + * @param accepts NSArray of header + * + * @return The Accept header + */ ++(NSString *) selectHeaderAccept:(NSArray *)accepts; + +/** + * Detects Content-Type header from contentTypes NSArray + * + * @param contentTypes NSArray of header + * + * @return The Content-Type header + */ ++(NSString *) selectHeaderContentType:(NSArray *)contentTypes; + +/** + * 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 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; + +/** + * Deserializes the given data to Objective-C object. + * + * @param data The data will be deserialized. + * @param class The type of objective-c object. + */ +- (id) deserialize:(id) data class:(NSString *) class; + +/** + * Logs request and response + * + * @param operation AFHTTPRequestOperation for the HTTP request. + * @param request The HTTP request. + * @param error The error of the HTTP request. + */ +- (void)logResponse:(AFHTTPRequestOperation *)operation + forRequest:(NSURLRequest *)request + error:(NSError *)error; + +/** + * Performs request + * + * @param path Request url. + * @param method Request method. + * @param pathParams Request path parameters. + * @param queryParams Request query parameters. + * @param body Request body. + * @param headerParams Request header parameters. + * @param authSettings Request authentication names. + * @param requestContentType Request content-type. + * @param responseContentType Response content-type. + * @param completionBlock The block will be executed when the request completed. + * + * @return The request id. + */ +-(NSNumber*) requestWithCompletionBlock:(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; + +/** + * Sanitize object for request + * + * @param object The query/path/header/form/body param to be sanitized. + */ +- (id) sanitizeForSerialization:(id) object; + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-body.mustache new file mode 100644 index 00000000000..9c941b107a0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-body.mustache @@ -0,0 +1,132 @@ +#import "{{classPrefix}}Configuration.h" + +@interface {{classPrefix}}Configuration () + +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey; +@property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; + +@end + +@implementation {{classPrefix}}Configuration + +#pragma mark - Singletion Methods + ++ (instancetype) sharedConfig { + static {{classPrefix}}Configuration *shardConfig = nil; + static dispatch_once_t onceToken; + dispatch_once(&onceToken, ^{ + shardConfig = [[self alloc] init]; + }); + return shardConfig; +} + +#pragma mark - Initialize Methods + +- (instancetype) init { + self = [super init]; + if (self) { + self.apiClient = nil; + self.host = @"{{basePath}}"; + self.username = @""; + self.password = @""; + self.tempFolderPath = nil; + self.debug = NO; + self.loggingFile = nil; + self.mutableApiKey = [NSMutableDictionary dictionary]; + self.mutableApiKeyPrefix = [NSMutableDictionary dictionary]; + } + return self; +} + +#pragma mark - Instance Methods + +- (NSString *) getApiKeyWithPrefix:(NSString *)key { + if ([self.apiKeyPrefix objectForKey:key] && [self.apiKey objectForKey:key]) { + return [NSString stringWithFormat:@"%@ %@", [self.apiKeyPrefix objectForKey:key], [self.apiKey objectForKey:key]]; + } + else if ([self.apiKey objectForKey:key]) { + return [NSString stringWithFormat:@"%@", [self.apiKey objectForKey:key]]; + } + else { + return @""; + } +} + +- (NSString *) getBasicAuthToken { + NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password]; + NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding]; + basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]]; + + return basicAuthCredentials; +} + +#pragma mark - Setter Methods + +- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString *)identifier { + [self.mutableApiKey setValue:apiKey forKey:identifier]; +} + +- (void) removeApiKey:(NSString *)identifier { + [self.mutableApiKey removeObjectForKey:identifier]; +} + +- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier { + [self.mutableApiKeyPrefix setValue:prefix forKey:identifier]; +} + +- (void) removeApiKeyPrefix:(NSString *)identifier { + [self.mutableApiKeyPrefix removeObjectForKey:identifier]; +} + +- (void) setLoggingFile:(NSString *)loggingFile { + // close old file handler + if ([self.loggingFileHanlder isKindOfClass:[NSFileHandle class]]) { + [self.loggingFileHanlder closeFile]; + } + + _loggingFile = loggingFile; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + if (_loggingFileHanlder == nil) { + [[NSFileManager defaultManager] createFileAtPath:_loggingFile contents:nil attributes:nil]; + _loggingFileHanlder = [NSFileHandle fileHandleForWritingAtPath:_loggingFile]; + } +} + +#pragma mark - Getter Methods + +- (NSDictionary *) apiKey { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKey]; +} + +- (NSDictionary *) apiKeyPrefix { + return [NSDictionary dictionaryWithDictionary:self.mutableApiKeyPrefix]; +} + +#pragma mark - + +- (NSDictionary *) authSettings { + return @{ +{{#authMethods}} +{{#isApiKey}} + @"{{name}}": + @{ + @"type": @"api_key", + @"in": {{#isKeyInHeader}}@"header"{{/isKeyInHeader}}{{#isKeyInQuery}}@"query"{{/isKeyInQuery}}, + @"key": @"{{keyParamName}}", + @"value": [self getApiKeyWithPrefix:@"{{keyParamName}}"] + }, +{{/isApiKey}} +{{#isBasic}} + @"{{name}}": + @{ + @"type": @"basic", + @"in": @"header", + @"key": @"Authorization", + @"value": [self getBasicAuthToken] + }, +{{/isBasic}} +{{/authMethods}} + }; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-header.mustache new file mode 100644 index 00000000000..c9bac508bbb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/Configuration-header.mustache @@ -0,0 +1,128 @@ +#import +#import "{{classPrefix}}ApiClient.h" + +/** The `{{classPrefix}}Configuration` class manages the configurations for the sdk. + * + * 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. + */ + +@class {{classPrefix}}ApiClient; + +@interface {{classPrefix}}Configuration : NSObject + +/** + * Default api client + */ +@property (nonatomic) {{classPrefix}}ApiClient *apiClient; + +/** + * 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; + +/** + * Usename for HTTP Basic Authentication + */ + @property (nonatomic) NSString *username; + +/** + * Password for HTTP Basic Authentication + */ +@property (nonatomic) NSString *password; + +/** + * Temp folder for file download + */ +@property (nonatomic) NSString *tempFolderPath; + +/** + * Logging Settings + */ + +/** + * Debug switch, default false + */ +@property (nonatomic) BOOL debug; + +/** + * Debug file location, default log in console + */ +@property (nonatomic) NSString *loggingFile; + +/** + * Log file handler, this property is used by sdk internally. + */ +@property (nonatomic, readonly) NSFileHandle *loggingFileHanlder; + +/** + * Gets configuration singleton instance + */ ++ (instancetype) sharedConfig; + +/** + * 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 + * + * To remove a apiKeyPrefix for an identifier, just set the apiKeyPrefix to nil. + * + * @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 Authentication Setings + */ +- (NSDictionary *) authSettings; + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-header.mustache deleted file mode 100644 index 5c8cc96953c..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-header.mustache +++ /dev/null @@ -1,56 +0,0 @@ -#import - -@interface FTConfiguration : NSObject - - -/** - * Api key values for Api Key type Authentication - * - * To add or remove api key, use `setValue:forApiKeyField:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKey; - -/** - * Api key prefix values to be prepend to the respective api key - * - * To add or remove prefix, use `setValue:forApiKeyPrefixField:`. - */ -@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix; - -/** - * Usename and Password for Basic type Authentication - */ -@property (nonatomic) NSString *username; -@property (nonatomic) NSString *password; - -/** - * Get configuration singleton instance - */ -+ (instancetype) sharedConfig; - -/** - * Sets field in `apiKey` - */ -- (void) setValue:(NSString *)value forApiKeyField:(NSString*)field; - -/** - * Sets field in `apiKeyPrefix` - */ -- (void) setValue:(NSString *)value forApiKeyPrefixField:(NSString *)field; - -/** - * Get API key (with prefix if set) - */ -- (NSString *) getApiKeyWithPrefix:(NSString *) key; - -/** - * Get Basic Auth token - */ -- (NSString *) getBasicAuthToken; - -/** - * Get Authentication Setings - */ -- (NSDictionary *) authSettings; - -@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.h b/modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.h deleted file mode 100644 index 18f126885e5..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.h +++ /dev/null @@ -1,14 +0,0 @@ -#import - -@interface FTFile : NSObject - -@property(nonatomic, readonly) NSString* name; -@property(nonatomic, readonly) NSString* mimeType; -@property(nonatomic, readonly) NSData* data; -@property(nonatomic) NSString* paramName; - -- (id) initWithNameData: (NSString*) filename - mimeType: (NSString*) mimeType - data: (NSData*) data; - -@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.m b/modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.m deleted file mode 100644 index 5f0b7934125..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTFile.m +++ /dev/null @@ -1,26 +0,0 @@ -#import "FTFile.h" - -@implementation FTFile - -@synthesize name = _name; -@synthesize mimeType = _mimeType; -@synthesize data = _data; - -- (id) init { - self = [super init]; - return self; -} - -- (id) initWithNameData: (NSString*) filename - mimeType: (NSString*) fileMimeType - data: (NSData*) data { - self = [super init]; - if(self) { - _name = filename; - _mimeType = fileMimeType; - _data = data; - } - return self; -} - -@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.h b/modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.h deleted file mode 100644 index 6b861585c6d..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.h +++ /dev/null @@ -1,5 +0,0 @@ -#import -#import "JSONModel.h" - -@interface FTObject : JSONModel -@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.m b/modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.m deleted file mode 100644 index 833c1b85019..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTObject.m +++ /dev/null @@ -1,4 +0,0 @@ -#import "FTObject.h" - -@implementation FTObject -@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.h b/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.h deleted file mode 100644 index 10f7afb1a2a..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.h +++ /dev/null @@ -1,216 +0,0 @@ -#import -#import "AFHTTPRequestOperationManager.h" - -/** - * A key for `NSError` user info dictionaries. - * - * The corresponding value is the parsed response body for an HTTP error. - */ -extern NSString *const FotitionResponseObjectErrorKey; - - -@interface FotitionAPIClient : AFHTTPRequestOperationManager - -@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy; -@property(nonatomic, assign) NSTimeInterval timeoutInterval; -@property(nonatomic, assign) BOOL logRequests; -@property(nonatomic, assign) BOOL logCacheHits; -@property(nonatomic, assign) BOOL logServerResponses; -@property(nonatomic, assign) BOOL logJSON; -@property(nonatomic, assign) BOOL logHTTP; -@property(nonatomic, readonly) NSOperationQueue* queue; - -/** - * Get the Api Client instance from pool - * - * @param baseUrl The base url of api client. - * - * @return The FotitionAPIClient instance. - */ -+(FotitionAPIClient *)sharedClientFromPool:(NSString *)baseUrl; - -/** - * Get the operations queue - * - * @return The `shardQueue` static variable. - */ -+(NSOperationQueue*) sharedQueue; - -/** - * Turn on logging - * - * @param state logging state, must be `YES` or `NO` - */ -+(void)setLoggingEnabled:(bool) state; - -/** - * Clear Cache - */ -+(void)clearCache; - -/** - * Turn on cache - * - * @param enabled If the cached is enable, must be `YES` or `NO` - */ -+(void)setCacheEnabled:(BOOL) enabled; - -/** - * Get the request queue size - * - * @return The size of `queuedRequests` static variable. - */ -+(unsigned long)requestQueueSize; - -/** - * Set the client unreachable - * - * @param state off line state, must be `YES` or `NO` - */ -+(void) setOfflineState:(BOOL) state; - -/** - * Get the client reachability - * - * @return The client reachability. - */ -+(AFNetworkReachabilityStatus) getReachabilityStatus; - -/** - * Get the next request id - * - * @return The next executed request id. - */ -+(NSNumber*) nextRequestId; - -/** - * Generate request id and add it to the queue - * - * @return The next executed request id. - */ -+(NSNumber*) queueRequest; - -/** - * Remove request id from the queue - * - * @param requestId The request which will be removed. - */ -+(void) cancelRequest:(NSNumber*)requestId; - -/** - * URL encode NSString - * - * @param unescaped The string which will be escaped. - * - * @return The escaped string. - */ -+(NSString*) escape:(id)unescaped; - -/** - * Customize the behavior when the reachability changed - * - * @param changeBlock The block will be executed when the reachability changed. - */ -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock; - -/** - * Set the client reachability strategy - * - * @param host The host of FotitionAPIClient. - */ -+(void) configureCacheReachibilityForHost:(NSString*)host; - -/** - * Detect Accept header from accepts NSArray - * - * @param accepts NSArray of header - * - * @return The Accept header - */ -+(NSString *) selectHeaderAccept:(NSArray *)accepts; - -/** - * Detect Content-Type header from contentTypes NSArray - * - * @param contentTypes NSArray of header - * - * @return The Content-Type header - */ -+(NSString *) selectHeaderContentType:(NSArray *)contentTypes; - -/** - * Set header for request - * - * @param value The header value - * @param forKey The header key - */ --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey; - -/** - * Update header parameters and query parameters for authentication - * - * @param headers The header parameter will be udpated, passed by pointer to pointer. - * @param querys The query parameters will be updated, passed by pointer to pointer. - * @param authSettings The authentication names NSArray. - */ -- (void) updateHeaderParams:(NSDictionary **)headers - queryParams:(NSDictionary **)querys - WithAuthSettings:(NSArray *)authSettings; - -/** - * Perform request - * - * Request with non-empty response - * - * @param path Request url. - * @param method Request method. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The request id. - */ --(NSNumber*) dictionary:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSDictionary *, NSDictionary*, NSError *))completionBlock; - -/** - * Perform request - * - * Request with empty response - * - * @param path Request url. - * @param method Request method. - * @param queryParams Request query parameters. - * @param body Request body. - * @param headerParams Request header parameters. - * @param authSettings Request authentication names. - * @param requestContentType Request content-type. - * @param responseContentType Response content-type. - * @param completionBlock The block will be executed when the request completed. - * - * @return The request id. - */ --(NSNumber*) stringWithCompletionBlock:(NSString*) path - method:(NSString*) method - queryParams:(NSDictionary*) queryParams - body:(id) body - headerParams:(NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType:(NSString*) requestContentType - responseContentType:(NSString*) responseContentType - completionBlock:(void (^)(NSDictionary *, NSString*, NSError *))completionBlock; -@end - - diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.m b/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.m deleted file mode 100644 index 704974a6444..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionAPIClient.m +++ /dev/null @@ -1,686 +0,0 @@ -#import "FotitionAPIClient.h" -#import "FTFile.h" -#import "FTQueryParamCollection.h" -#import "FTConfiguration.h" - -@implementation FotitionAPIClient - -NSString *const FotitionResponseObjectErrorKey = @"FotitionResponseObject"; - -static long requestId = 0; -static bool offlineState = false; -static NSMutableSet * queuedRequests = nil; -static bool cacheEnabled = false; -static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable; -static NSOperationQueue* sharedQueue; -static void (^reachabilityChangeBlock)(int); -static bool loggingEnabled = true; - -#pragma mark - Log Methods - -+(void)setLoggingEnabled:(bool) state { - loggingEnabled = state; -} - -- (void)logRequest:(NSURLRequest*)request { - NSLog(@"request: %@", [self descriptionForRequest:request]); -} - -- (void)logResponse:(id)data forRequest:(NSURLRequest*)request error:(NSError*)error { - NSLog(@"request: %@ response: %@ ", [self descriptionForRequest:request], data ); -} - -#pragma mark - - -+(void)clearCache { - [[NSURLCache sharedURLCache] removeAllCachedResponses]; -} - -+(void)setCacheEnabled:(BOOL)enabled { - cacheEnabled = enabled; -} - -+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize - diskSize: (unsigned long) diskSize { - NSAssert(memorySize > 0, @"invalid in-memory cache size"); - NSAssert(diskSize >= 0, @"invalid disk cache size"); - - NSURLCache *cache = - [[NSURLCache alloc] - initWithMemoryCapacity:memorySize - diskCapacity:diskSize - diskPath:@"swagger_url_cache"]; - - [NSURLCache setSharedURLCache:cache]; -} - -+(NSOperationQueue*) sharedQueue { - return sharedQueue; -} - -+(FotitionAPIClient *)sharedClientFromPool:(NSString *)baseUrl { - static NSMutableDictionary *_pool = nil; - if (queuedRequests == nil) { - queuedRequests = [[NSMutableSet alloc]init]; - } - if(_pool == nil) { - // setup static vars - // create queue - sharedQueue = [[NSOperationQueue alloc] init]; - - // create pool - _pool = [[NSMutableDictionary alloc] init]; - - // initialize URL cache - [FotitionAPIClient configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024]; - - // configure reachability - [FotitionAPIClient configureCacheReachibilityForHost:baseUrl]; - } - - @synchronized(self) { - FotitionAPIClient * client = [_pool objectForKey:baseUrl]; - if (client == nil) { - client = [[FotitionAPIClient alloc] initWithBaseURL:[NSURL URLWithString:baseUrl]]; - [_pool setValue:client forKey:baseUrl ]; - if(loggingEnabled) - NSLog(@"new client for path %@", baseUrl); - } - if(loggingEnabled) - NSLog(@"returning client for path %@", baseUrl); - return client; - } -} - -/* - * Detect `Accept` from accepts - */ -+ (NSString *) selectHeaderAccept:(NSArray *)accepts -{ - if (accepts == nil || [accepts count] == 0) { - return @""; - } - - NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]]; - [accepts enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerAccepts addObject:[obj lowercaseString]]; - }]; - - - if ([lowerAccepts containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return [lowerAccepts componentsJoinedByString:@", "]; - } -} - -/* - * Detect `Content-Type` from contentTypes - */ -+ (NSString *) selectHeaderContentType:(NSArray *)contentTypes -{ - if (contentTypes == nil || [contentTypes count] == 0) { - return @"application/json"; - } - - NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]]; - [contentTypes enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { - [lowerContentTypes addObject:[obj lowercaseString]]; - }]; - - if ([lowerContentTypes containsObject:@"application/json"]) { - return @"application/json"; - } - else { - return lowerContentTypes[0]; - } -} - --(void)setHeaderValue:(NSString*) value - forKey:(NSString*) forKey { - [self.requestSerializer setValue:value forHTTPHeaderField:forKey]; -} - -+(unsigned long)requestQueueSize { - return [queuedRequests count]; -} - -+(NSNumber*) nextRequestId { - @synchronized(self) { - long nextId = ++requestId; - if(loggingEnabled) - NSLog(@"got id %ld", nextId); - return [NSNumber numberWithLong:nextId]; - } -} - -+(NSNumber*) queueRequest { - NSNumber* requestId = [FotitionAPIClient nextRequestId]; - if(loggingEnabled) - NSLog(@"added %@ to request queue", requestId); - [queuedRequests addObject:requestId]; - return requestId; -} - -+(void) cancelRequest:(NSNumber*)requestId { - [queuedRequests removeObject:requestId]; -} - -+(NSString*) escape:(id)unescaped { - if([unescaped isKindOfClass:[NSString class]]){ - return (NSString *)CFBridgingRelease - (CFURLCreateStringByAddingPercentEscapes( - NULL, - (__bridge CFStringRef) unescaped, - NULL, - (CFStringRef)@"!*'();:@&=+$,/?%#[]", - kCFStringEncodingUTF8)); - } - else { - return [NSString stringWithFormat:@"%@", unescaped]; - } -} - --(Boolean) executeRequestWithId:(NSNumber*) requestId { - NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) { - if([obj intValue] == [requestId intValue]) - return TRUE; - else return FALSE; - }]; - - if(matchingItems.count == 1) { - if(loggingEnabled) - NSLog(@"removing request id %@", requestId); - [queuedRequests removeObject:requestId]; - return true; - } - else - return false; -} - --(id)initWithBaseURL:(NSURL *)url { - self = [super initWithBaseURL:url]; - self.requestSerializer = [AFJSONRequestSerializer serializer]; - self.responseSerializer = [AFJSONResponseSerializer serializer]; - if (!self) - return nil; - return self; -} - -+(AFNetworkReachabilityStatus) getReachabilityStatus { - return reachabilityStatus; -} - -+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock { - reachabilityChangeBlock = changeBlock; -} - -+(void) setOfflineState:(BOOL) state { - offlineState = state; -} - -+(void) configureCacheReachibilityForHost:(NSString*)host { - [[FotitionAPIClient sharedClientFromPool:host].reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { - reachabilityStatus = status; - switch (status) { - case AFNetworkReachabilityStatusUnknown: - if(loggingEnabled) - NSLog(@"reachability changed to AFNetworkReachabilityStatusUnknown"); - [FotitionAPIClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusNotReachable: - if(loggingEnabled) - NSLog(@"reachability changed to AFNetworkReachabilityStatusNotReachable"); - [FotitionAPIClient setOfflineState:true]; - break; - - case AFNetworkReachabilityStatusReachableViaWWAN: - if(loggingEnabled) - NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWWAN"); - [FotitionAPIClient setOfflineState:false]; - break; - - case AFNetworkReachabilityStatusReachableViaWiFi: - if(loggingEnabled) - NSLog(@"reachability changed to AFNetworkReachabilityStatusReachableViaWiFi"); - [FotitionAPIClient setOfflineState:false]; - break; - default: - break; - } - // call the reachability block, if configured - if(reachabilityChangeBlock != nil) { - reachabilityChangeBlock(status); - } - }]; - [[FotitionAPIClient sharedClientFromPool:host].reachabilityManager startMonitoring]; -} - --(NSString*) pathWithQueryParamsToString:(NSString*) path - queryParams:(NSDictionary*) queryParams { - NSString * separator = nil; - int counter = 0; - - NSMutableString * requestUrl = [NSMutableString stringWithFormat:@"%@", path]; - if(queryParams != nil){ - for(NSString * key in [queryParams keyEnumerator]){ - if(counter == 0) separator = @"?"; - else separator = @"&"; - id queryParam = [queryParams valueForKey:key]; - if([queryParam isKindOfClass:[NSString class]]){ - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [FotitionAPIClient escape:key], [FotitionAPIClient escape:[queryParams valueForKey:key]]]]; - } - else if([queryParam isKindOfClass:[FTQueryParamCollection class]]){ - FTQueryParamCollection * coll = (FTQueryParamCollection*) queryParam; - NSArray* values = [coll values]; - NSString* format = [coll format]; - - if([format isEqualToString:@"csv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [FotitionAPIClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@","]]]]; - - } - else if([format isEqualToString:@"tsv"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [FotitionAPIClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"\t"]]]]; - - } - else if([format isEqualToString:@"pipes"]) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [FotitionAPIClient escape:key], [NSString stringWithFormat:@"%@", [values componentsJoinedByString:@"|"]]]]; - - } - else if([format isEqualToString:@"multi"]) { - for(id obj in values) { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [FotitionAPIClient escape:key], [NSString stringWithFormat:@"%@", obj]]]; - counter += 1; - } - - } - } - else { - [requestUrl appendString:[NSString stringWithFormat:@"%@%@=%@", separator, - [FotitionAPIClient escape:key], [NSString stringWithFormat:@"%@", [queryParams valueForKey:key]]]]; - } - - counter += 1; - } - } - return requestUrl; -} - -- (NSString*)descriptionForRequest:(NSURLRequest*)request { - return [[request URL] absoluteString]; -} - - -/** - * Update header and query params based on authentication settings - */ -- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers - queryParams:(NSDictionary *__autoreleasing *)querys - WithAuthSettings:(NSArray *)authSettings { - - if (!authSettings || [authSettings count] == 0) { - return; - } - - NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers]; - NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys]; - - FTConfiguration *config = [FTConfiguration sharedConfig]; - for (NSString *auth in authSettings) { - NSDictionary *authSetting = [[config authSettings] objectForKey:auth]; - - if (authSetting) { - if ([authSetting[@"in"] isEqualToString:@"header"]) { - [headersWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - else if ([authSetting[@"in"] isEqualToString:@"query"]) { - [querysWithAuth setObject:authSetting[@"value"] forKey:authSetting[@"key"]]; - } - } - } - - *headers = [NSDictionary dictionaryWithDictionary:headersWithAuth]; - *querys = [NSDictionary dictionaryWithDictionary:querysWithAuth]; -} - -#pragma mark - Perform Request Methods - --(NSNumber*) dictionary: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - completionBlock: (void (^)(NSDictionary *, NSDictionary*, NSError *))completionBlock { - - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [AFJSONRequestSerializer 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 { - NSAssert(false, @"unsupport request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [AFJSONResponseSerializer serializer]; - } - else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableURLRequest * request = nil; - if (body != nil && [body isKindOfClass:[NSArray class]]){ - FTFile * file; - NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; - for(id obj in body) { - if([obj isKindOfClass:[FTFile class]]) { - file = (FTFile*) obj; - requestContentType = @"multipart/form-data"; - } - else if([obj isKindOfClass:[NSDictionary class]]) { - for(NSString * key in obj) { - params[key] = obj[key]; - } - } - } - NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; - - // request with multipart form - if([requestContentType isEqualToString:@"multipart/form-data"]) { - request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" - URLString: urlString - parameters: nil - constructingBodyWithBlock: ^(id formData) { - - for(NSString * key in params) { - NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData: data name: key]; - } - - if (file) { - [formData appendPartWithFileData: [file data] - name: [file paramName] - fileName: [file name] - mimeType: [file mimeType]]; - } - - } - error:nil]; - } - // request with form parameters or json - else { - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:params - error:nil]; - } - } - else { - NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:body - error:nil]; - } - BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) - hasHeaderParams = true; - if(offlineState) { - NSLog(@"%@ cache forced", path); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - NSLog(@"%@ cache disabled", path); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - if(body != nil) { - if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ - [self setHeaderValue:requestContentType forKey:@"Content-Type"]; - } - else if ([body isKindOfClass:[FTFile class]]) {} - else { - NSAssert(false, @"unsupported post type!"); - } - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self setHeaderValue:responseContentType forKey:@"Accept"]; - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; - - - if (self.logRequests) { - [self logRequest:request]; - } - - NSNumber* requestId = [FotitionAPIClient queueRequest]; - AFHTTPRequestOperation *op = - [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id JSON) { - if([self executeRequestWithId:requestId]) { - if(self.logServerResponses) - [self logResponse:JSON forRequest:request error:nil]; - completionBlock([[operation response] allHeaderFields], JSON, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { - // Add in the (parsed) response body. - userInfo[FotitionResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if(self.logServerResponses) - [self logResponse:nil forRequest:request error:augmentedError]; - completionBlock([[operation response] allHeaderFields], nil, augmentedError); - } - } - ]; - - [self.operationQueue addOperation:op]; - return requestId; -} - --(NSNumber*) stringWithCompletionBlock: (NSString*) path - method: (NSString*) method - queryParams: (NSDictionary*) queryParams - body: (id) body - headerParams: (NSDictionary*) headerParams - authSettings: (NSArray *) authSettings - requestContentType: (NSString*) requestContentType - responseContentType: (NSString*) responseContentType - completionBlock: (void (^)(NSDictionary *, NSString*, NSError *))completionBlock { - - // setting request serializer - if ([requestContentType isEqualToString:@"application/json"]) { - self.requestSerializer = [AFJSONRequestSerializer 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 { - NSAssert(false, @"unsupport request type %@", requestContentType); - } - - // setting response serializer - if ([responseContentType isEqualToString:@"application/json"]) { - self.responseSerializer = [AFJSONResponseSerializer serializer]; - } - else { - self.responseSerializer = [AFHTTPResponseSerializer serializer]; - } - - // auth setting - [self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings]; - - NSMutableURLRequest * request = nil; - if (body != nil && [body isKindOfClass:[NSArray class]]){ - FTFile * file; - NSMutableDictionary * params = [[NSMutableDictionary alloc] init]; - for(id obj in body) { - if([obj isKindOfClass:[FTFile class]]) { - file = (FTFile*) obj; - requestContentType = @"multipart/form-data"; - } - else if([obj isKindOfClass:[NSDictionary class]]) { - for(NSString * key in obj) { - params[key] = obj[key]; - } - } - } - NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString]; - - // request with multipart form - if([requestContentType isEqualToString:@"multipart/form-data"]) { - request = [self.requestSerializer multipartFormRequestWithMethod: @"POST" - URLString: urlString - parameters: nil - constructingBodyWithBlock: ^(id formData) { - - for(NSString * key in params) { - NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding]; - [formData appendPartWithFormData: data name: key]; - } - - if (file) { - [formData appendPartWithFileData: [file data] - name: [file paramName] - fileName: [file name] - mimeType: [file mimeType]]; - } - - } - error:nil]; - } - // request with form parameters or json - else { - NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod:method - URLString:urlString - parameters:params - error:nil]; - } - - } - else { - NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams]; - NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString]; - - request = [self.requestSerializer requestWithMethod: method - URLString: urlString - parameters: body - error: nil]; - } - BOOL hasHeaderParams = false; - if(headerParams != nil && [headerParams count] > 0) - hasHeaderParams = true; - if(offlineState) { - NSLog(@"%@ cache forced", path); - [request setCachePolicy:NSURLRequestReturnCacheDataDontLoad]; - } - else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) { - NSLog(@"%@ cache enabled", path); - [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; - } - else { - NSLog(@"%@ cache disabled", path); - [request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData]; - } - - - if(body != nil) { - if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){ - [self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"]; - } - else if ([body isKindOfClass:[FTFile class]]){} - else { - NSAssert(false, @"unsupported post type!"); - } - } - if(headerParams != nil){ - for(NSString * key in [headerParams keyEnumerator]){ - [request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key]; - } - } - [self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"]; - - - // Always disable cookies! - [request setHTTPShouldHandleCookies:NO]; - - NSNumber* requestId = [FotitionAPIClient queueRequest]; - AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request - success:^(AFHTTPRequestOperation *operation, id responseObject) { - NSString *response = [operation responseString]; - if([self executeRequestWithId:requestId]) { - if(self.logServerResponses) - [self logResponse:responseObject forRequest:request error:nil]; - completionBlock([[operation response] allHeaderFields], response, nil); - } - } failure:^(AFHTTPRequestOperation *operation, NSError *error) { - if([self executeRequestWithId:requestId]) { - NSMutableDictionary *userInfo = [error.userInfo mutableCopy]; - if(operation.responseObject) { - // Add in the (parsed) response body. - userInfo[FotitionResponseObjectErrorKey] = operation.responseObject; - } - NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo]; - - if(self.logServerResponses) - [self logResponse:nil forRequest:request error:augmentedError]; - completionBlock([[operation response] allHeaderFields], nil, augmentedError); - } - }]; - - [self.operationQueue addOperation:op]; - return requestId; -} - -@end - - - - - - - - diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionConfiguration-body.mustache similarity index 94% rename from modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-body.mustache rename to modules/swagger-codegen/src/main/resources/fotition-objc/FotitionConfiguration-body.mustache index aebd85dfe9a..cdb41b2f324 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTConfiguration-body.mustache +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/FotitionConfiguration-body.mustache @@ -1,18 +1,18 @@ -#import "FTConfiguration.h" +#import "FotitionConfiguration.h" -@interface FTConfiguration () +@interface FotitionConfiguration () @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKey; @property (readwrite, nonatomic, strong) NSMutableDictionary *mutableApiKeyPrefix; @end -@implementation FTConfiguration +@implementation FotitionConfiguration #pragma mark - Singletion Methods + (instancetype) sharedConfig { - static FTConfiguration *shardConfig = nil; + static FotitionConfiguration *shardConfig = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ shardConfig = [[self alloc] init]; diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-body.mustache new file mode 100644 index 00000000000..78b1409b6b9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-body.mustache @@ -0,0 +1,35 @@ +#import "{{classPrefix}}JSONRequestSerializer.h" + +@implementation {{classPrefix}}JSONRequestSerializer + +/// +/// When customize a request serializer, +/// the serializer must conform the protocol `AFURLRequestSerialization` +/// and implements the protocol method `requestBySerializingRequest:withParameters:error:` +/// +/// @param request The original request. +/// @param parameters The parameters to be encoded. +/// @param error The error that occurred while attempting to encode the request parameters. +/// +/// @return A serialized request. +/// +- (NSURLRequest *)requestBySerializingRequest:(NSURLRequest *)request + withParameters:(id)parameters + error:(NSError *__autoreleasing *)error +{ + // If the body data which will be serialized isn't NSArray or NSDictionary + // then put the data in the http request body directly. + if ([parameters isKindOfClass:[NSArray class]] || [parameters isKindOfClass:[NSDictionary class]]) { + return [super requestBySerializingRequest:request withParameters:parameters error:error]; + } else { + NSMutableURLRequest *mutableRequest = [request mutableCopy]; + + if (parameters) { + [mutableRequest setHTTPBody:[parameters dataUsingEncoding:self.stringEncoding]]; + } + + return mutableRequest; + } +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-header.mustache new file mode 100644 index 00000000000..a0732b93706 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONRequestSerializer-header.mustache @@ -0,0 +1,5 @@ +#import +#import + +@interface {{classPrefix}}JSONRequestSerializer : AFJSONRequestSerializer +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-body.mustache new file mode 100644 index 00000000000..3a19dd1ca4e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-body.mustache @@ -0,0 +1,39 @@ +#import "{{classPrefix}}JSONResponseSerializer.h" + +static BOOL JSONParseError(NSError *error) { + if ([error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840) { + return YES; + } + + return NO; +} + +@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 respnse 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 (JSONParseError(*error)) { + *error = nil; + NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; + return responseString; + } + + return responseJson; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-header.mustache new file mode 100644 index 00000000000..7a5f152e271 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/JSONResponseSerializer-header.mustache @@ -0,0 +1,6 @@ +#import +#import + +@interface {{classPrefix}}JSONResponseSerializer : AFJSONResponseSerializer + +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/Object-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/Object-body.mustache new file mode 100644 index 00000000000..122484f1ad4 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/Object-body.mustache @@ -0,0 +1,4 @@ +#import "{{classPrefix}}Object.h" + +@implementation {{classPrefix}}Object +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/Object-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/Object-header.mustache new file mode 100644 index 00000000000..d96e379908f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/Object-header.mustache @@ -0,0 +1,5 @@ +#import +#import + +@interface {{classPrefix}}Object : JSONModel +@end diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/Podfile.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/Podfile.mustache deleted file mode 100644 index c61ab59dd8f..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/Podfile.mustache +++ /dev/null @@ -1,5 +0,0 @@ -platform :ios, '6.0' -xcodeproj '{{projectName}}/{{projectName}}.xcodeproj' -pod 'AFNetworking', '~> 2.1' -pod 'JSONModel', '~> 1.0' -pod 'ISO8601' diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTQueryParamCollection.m b/modules/swagger-codegen/src/main/resources/fotition-objc/QueryParamCollection-body.mustache similarity index 70% rename from modules/swagger-codegen/src/main/resources/fotition-objc/FTQueryParamCollection.m rename to modules/swagger-codegen/src/main/resources/fotition-objc/QueryParamCollection-body.mustache index a1506e19e34..23d0c8eaa86 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTQueryParamCollection.m +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/QueryParamCollection-body.mustache @@ -1,6 +1,6 @@ -#import "FTQueryParamCollection.h" +#import "{{classPrefix}}QueryParamCollection.h" -@implementation FTQueryParamCollection +@implementation {{classPrefix}}QueryParamCollection @synthesize values = _values; @synthesize format = _format; diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/FTQueryParamCollection.h b/modules/swagger-codegen/src/main/resources/fotition-objc/QueryParamCollection-header.mustache similarity index 80% rename from modules/swagger-codegen/src/main/resources/fotition-objc/FTQueryParamCollection.h rename to modules/swagger-codegen/src/main/resources/fotition-objc/QueryParamCollection-header.mustache index b6ed93a256c..0389cce98be 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/FTQueryParamCollection.h +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/QueryParamCollection-header.mustache @@ -1,6 +1,6 @@ #import -@interface FTQueryParamCollection : NSObject +@interface {{classPrefix}}QueryParamCollection : NSObject @property(nonatomic, readonly) NSArray* values; @property(nonatomic, readonly) NSString* format; diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/README.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/README.mustache new file mode 100644 index 00000000000..30a8927c41a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/README.mustache @@ -0,0 +1,23 @@ +# {{podName}} + +## Requirements + +The API client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. + +## Installation + +To install it, put the API client library in your project and then simply add the following line to your Podfile: + +```ruby +pod "{{podName}}", :path => "/path/to/lib" +``` + +## Recommendation + +It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issue. + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} + diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/api-body.mustache index b5e14d8adf3..534c887fe7b 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/api-body.mustache @@ -1,7 +1,6 @@ {{#operations}} #import "{{classname}}.h" -#import "FTFile.h" -#import "FTQueryParamCollection.h" +#import "{{classPrefix}}QueryParamCollection.h" {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @@ -12,28 +11,25 @@ @implementation {{classname}} -static NSString * basePath = @"{{basePath}}"; - #pragma mark - Initialize methods - (id) init { self = [super init]; if (self) { - self.apiClient = [FotitionAPIClient sharedClientFromPool:basePath]; + {{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig]; + if (config.apiClient == nil) { + config.apiClient = [[{{classPrefix}}ApiClient alloc] init]; + } + self.apiClient = config.apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; } -- (id) initWithApiClient:(FotitionAPIClient *)apiClient { +- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient { self = [super init]; if (self) { - if (apiClient) { - self.apiClient = apiClient; - } - else { - self.apiClient = [FotitionAPIClient sharedClientFromPool:basePath]; - } + self.apiClient = apiClient; self.defaultHeaders = [NSMutableDictionary dictionary]; } return self; @@ -51,14 +47,6 @@ static NSString * basePath = @"{{basePath}}"; return singletonAPI; } -+(void) setBasePath:(NSString*)path { - basePath = path; -} - -+(NSString*) getBasePath { - return basePath; -} - -(void) addHeader:(NSString*)value forKey:(NSString*)key { [self.defaultHeaders setValue:value forKey:key]; } @@ -69,52 +57,60 @@ static NSString * basePath = @"{{basePath}}"; } -(unsigned long) requestQueueSize { - return [FotitionAPIClient requestQueueSize]; + return [{{classPrefix}}ApiClient requestQueueSize]; } +#pragma mark - Api Methods {{#operation}} -/*! - * {{{summary}}} - * {{{notes}}} -{{#allParams}} * \param {{paramName}} {{{description}}} -{{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - */ +/// +/// {{{summary}}} +/// {{{notes}}} +/// {{#allParams}} @param {{paramName}} {{{description}}} +/// +/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} +/// -(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}} {{/allParams}} - {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSDictionary *responseHeaders, {{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}} - {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSDictionary *responseHeaders, NSError* error))completionBlock{{/returnBaseType}} { + {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock { {{/returnBaseType}} + {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock { {{/returnBaseType}} {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set - NSAssert({{paramName}} != nil, @"Missing the required parameter `{{paramName}}` when calling {{nickname}}"); + if ({{paramName}} == nil) { + [NSException raise:@"Invalid parameter" format:@"Missing the required parameter `{{paramName}}` when calling `{{nickname}}`"]; + } {{/required}}{{/allParams}} - NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; + NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"{{path}}"]; // remove format in URL if needed - if ([requestUrl rangeOfString:@".{format}"].location != NSNotFound) - [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:@".{format}"] withString:@".json"]; + if ([resourcePath rangeOfString:@".{format}"].location != NSNotFound) { + [resourcePath replaceCharactersInRange: [resourcePath rangeOfString:@".{format}"] withString:@".json"]; + } - {{#pathParams}}[requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"{{baseName}}", @"}"]] withString: [FotitionAPIClient escape:{{paramName}}]]; + NSMutableDictionary *pathParams = [[NSMutableDictionary alloc] init]; + {{#pathParams}}if ({{paramName}} != nil) { + pathParams[@"{{baseName}}"] = {{paramName}}; + } {{/pathParams}} - NSMutableDictionary* queryParams __attribute__((unused)) = [[NSMutableDictionary alloc] init]; + NSMutableDictionary* queryParams = [[NSMutableDictionary alloc] init]; {{#queryParams}}if({{paramName}} != nil) { {{#collectionFormat}} - queryParams[@"{{baseName}}"] = [[FTQueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; + queryParams[@"{{baseName}}"] = [[{{classPrefix}}QueryParamCollection alloc] initWithValuesAndFormat: {{baseName}} format: @"{{collectionFormat}}"]; {{/collectionFormat}} {{^collectionFormat}}queryParams[@"{{baseName}}"] = {{paramName}};{{/collectionFormat}} } {{/queryParams}} - NSMutableDictionary* headerParams __attribute__((unused)) = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; + NSMutableDictionary* headerParams = [NSMutableDictionary dictionaryWithDictionary:self.defaultHeaders]; {{#headerParams}}if({{paramName}} != nil) headerParams[@"{{baseName}}"] = {{paramName}}; {{/headerParams}} - - // HTTP header `Accept` - headerParams[@"Accept"] = [FotitionAPIClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; + + // HTTP header `Accept` + headerParams[@"Accept"] = [{{classPrefix}}ApiClient selectHeaderAccept:@[{{#produces}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}}]]; if ([headerParams[@"Accept"] length] == 0) { [headerParams removeObjectForKey:@"Accept"]; } @@ -129,70 +125,26 @@ static NSString * basePath = @"{{basePath}}"; } // request content type - NSString *requestContentType = [FotitionAPIClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; + NSString *requestContentType = [{{classPrefix}}ApiClient selectHeaderContentType:@[{{#consumes}}@"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}}]]; // Authentication setting NSArray *authSettings = @[{{#authMethods}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/authMethods}}]; - - id bodyDictionary = nil; - {{#bodyParam}} - id __body = {{paramName}}; - - if(__body != nil && [__body isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] init]; - for (id dict in (NSArray*)__body) { - if([dict respondsToSelector:@selector(toDictionary)]) { - [objs addObject:[(FTObject*)dict toDictionary]]; - } - else{ - [objs addObject:dict]; - } - } - bodyDictionary = objs; - } - else if([__body respondsToSelector:@selector(toDictionary)]) { - bodyDictionary = [(FTObject*)__body toDictionary]; - } - else if([__body isKindOfClass:[NSString class]]) { - // convert it to a dictionary - NSError * error; - NSString * str = (NSString*)__body; - NSDictionary *JSON = - [NSJSONSerialization JSONObjectWithData: [str dataUsingEncoding: NSUTF8StringEncoding] - options: NSJSONReadingMutableContainers - error: &error]; - bodyDictionary = JSON; - } - {{/bodyParam}} - {{^bodyParam}} - NSMutableDictionary * formParams __attribute__((unused)) = [[NSMutableDictionary alloc]init]; - - if(bodyDictionary == nil) { - bodyDictionary = [[NSMutableArray alloc] init]; - } + id bodyParam = nil; + NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init]; + NSMutableDictionary *files = [[NSMutableDictionary alloc] init]; + {{#bodyParam}} + bodyParam = {{paramName}}; + {{/bodyParam}}{{^bodyParam}} {{#formParams}} {{#notFile}} - if ([{{paramName}} isKindOfClass:[NSNumber class]]){ - NSNumber *num = (NSNumber *){{paramName}}; - formParams[@"{{paramName}}"] = [num stringValue]; - }else{ - formParams[@"{{paramName}}"] = {{paramName}}; + if ({{paramName}}) { + formParams[@"{{baseName}}"] = {{paramName}}; } - - {{/notFile}}{{#isFile}} - requestContentType = @"multipart/form-data"; - - if({{paramName}} != nil) { - [bodyDictionary addObject:{{paramName}}]; - {{paramName}}.paramName = @"{{baseName}}"; - } + files[@"{{paramName}}"] = {{paramName}}; {{/isFile}} {{/formParams}} - - [bodyDictionary addObject:formParams]; - {{/bodyParam}} {{#requiredParamCount}} @@ -202,27 +154,23 @@ static NSString * basePath = @"{{basePath}}"; } {{/requiredParams}} {{/requiredParamCount}} - - {{#returnContainer}} - // response is in a container - {{>apiBodyResponseWithContainer}}{{/returnContainer}} - - {{#returnSimpleType}} - // non container response - - {{#returnTypeIsPrimitive}} - // primitive response - {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} - - {{#returnBaseType}} - // complex response - {{>apiNonPrimitiveResponse}}{{/returnBaseType}} - {{/returnSimpleType}} - - {{^returnSimpleType}}{{^returnContainer}} - // it's void - {{>voidResponse}} - {{/returnContainer}}{{/returnSimpleType}} + return [self.apiClient requestWithCompletionBlock: resourcePath + method: @"{{httpMethod}}" + pathParams: pathParams + queryParams: queryParams + formParams: formParams + files: files + body: bodyParam + headerParams: headerParams + authSettings: authSettings + requestContentType: requestContentType + responseContentType: responseContentType + responseType: {{^returnType}}nil{{/returnType}}{{#returnType}}@"{{{ returnType }}}"{{/returnType}} + completionBlock: ^(id data, NSError *error) { + {{^returnType}}completionBlock(error);{{/returnType}} + {{#returnType}}completionBlock(({{{ returnType }}})data, error);{{/returnType}} + } + ]; } {{/operation}} @@ -230,6 +178,3 @@ static NSString * basePath = @"{{basePath}}"; {{newline}} {{/operations}} @end - - - diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/api-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/api-header.mustache index 86ad2c60167..d9f691f7227 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/api-header.mustache +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/api-header.mustache @@ -1,38 +1,41 @@ #import {{#imports}}#import "{{import}}.h" {{/imports}} -#import "FTObject.h" -#import "FotitionAPIClient.h" +#import "{{classPrefix}}Object.h" +#import "{{classPrefix}}ApiClient.h" {{newline}} +/** + * 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. + */ + {{#operations}} @interface {{classname}}: NSObject -@property(nonatomic, assign)FotitionAPIClient *apiClient; +@property(nonatomic, assign){{classPrefix}}ApiClient *apiClient; --(instancetype) initWithApiClient:(FotitionAPIClient *)apiClient; +-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient; -(void) addHeader:(NSString*)value forKey:(NSString*)key; -(unsigned long) requestQueueSize; +({{classname}}*) apiWithHeader:(NSString*)headerValue key:(NSString*)key; -+(void) setBasePath:(NSString*)basePath; -+(NSString*) getBasePath; {{#operation}} -/** - - {{{summary}}} - {{#notes}}{{{notes}}}{{/notes}} - - {{#allParams}}@param {{paramName}} {{description}} - {{/allParams}} - - return type: {{{returnType}}} - */ +/// +/// +/// {{{summary}}} +/// {{#notes}}{{{notes}}}{{/notes}} +/// +/// {{#allParams}}@param {{paramName}} {{description}} +/// {{/allParams}} +/// +/// @return {{{returnType}}} -(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}} {{/hasMore}}{{/allParams}} {{#returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)(NSDictionary *responseHeaders, {{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}} + completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock;{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}} - completionHandler: {{/hasParams}}(void (^)(NSDictionary *responseHeaders, NSError* error))completionBlock;{{/returnBaseType}} + completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock;{{/returnBaseType}} {{newline}} {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/apiBodyResponseWithContainer.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/apiBodyResponseWithContainer.mustache deleted file mode 100644 index 9deba39e35a..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/apiBodyResponseWithContainer.mustache +++ /dev/null @@ -1,38 +0,0 @@ - // {{returnContainer}} container response type - return [self.apiClient dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *responseHeaders, NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(responseHeaders, nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(responseHeaders, error);{{/returnBaseType}} - return; - } - {{#isMapContainer}} - NSDictionary *result = nil; - if (data) { - result = [[NSDictionary alloc]initWithDictionary: data]; - } - completionBlock(data, nil); - {{/isMapContainer}}{{#isListContainer}} - {{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){ - NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; - for (NSDictionary* dict in (NSArray*)data) { - {{#returnTypeIsPrimitive}} - {{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict]; - {{/returnTypeIsPrimitive}} - {{^returnTypeIsPrimitive}} - {{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil]; - {{/returnTypeIsPrimitive}} - [objs addObject:d]; - } - completionBlock(responseHeaders, ({{{returnType}}})objs, nil); - } - {{/returnBaseType}} - {{/isListContainer}} - }]; - diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/apiNonPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/apiNonPrimitiveResponse.mustache deleted file mode 100644 index 47b6d614346..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/apiNonPrimitiveResponse.mustache +++ /dev/null @@ -1,24 +0,0 @@ - {{^returnTypeIsPrimitive}} - // comples response type - return [self.apiClient dictionary: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *responseHeaders, NSDictionary *data, NSError *error) { - if (error) { - {{#returnBaseType}}completionBlock(responseHeaders, nil, error);{{/returnBaseType}} - {{^returnBaseType}}completionBlock(responseHeaders, error);{{/returnBaseType}} - return; - } - {{#returnType}}{{returnType}} result = nil; - if (data) { - result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil]; - } - {{#returnType}}completionBlock(responseHeaders, result , nil);{{/returnType}} - {{/returnType}} - }]; - {{/returnTypeIsPrimitive}} diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/apiPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/apiPrimitiveResponse.mustache deleted file mode 100644 index a04f2a86656..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/apiPrimitiveResponse.mustache +++ /dev/null @@ -1,36 +0,0 @@ - // primitive response type - {{#returnBaseType}}return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *responseHeaders, NSString *data, NSError *error) { - if (error) { - completionBlock(responseHeaders, nil, error); - return; - } - {{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil; - completionBlock(responseHeaders, result, nil); - }]; - {{/returnBaseType}} - {{^returnBaseType}} - // no return base type - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *responseHeaders, NSString *data, NSError *error) { - if (error) { - completionBlock(responseHeaders, error); - return; - } - completionBlock(responseHeaders, nil); - }]; - {{/returnBaseType}} - diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/model-body.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/model-body.mustache index b728e6bb06c..33c0f8cf42b 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/model-body.mustache +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/model-body.mustache @@ -3,12 +3,21 @@ #import "{{classname}}.h" @implementation {{classname}} - + +/** + * Maps json key to property name. + * This method is used by `JSONModel`. + */ + (JSONKeyMapper *)keyMapper { return [[JSONKeyMapper alloc] initWithDictionary:@{ {{#vars}}@"{{baseName}}": @"{{name}}"{{#hasMore}}, {{/hasMore}}{{/vars}} }]; } +/** + * Indicates whether the property with the given name is optional. + * If `propertyName` is optional, then return `YES`, otherwise return `NO`. + * This method is used by `JSONModel`. + */ + (BOOL)propertyIsOptional:(NSString *)propertyName { NSArray *optionalProperties = @[{{#vars}}{{^required}}@"{{name}}"{{#hasMore}}, {{/hasMore}}{{/required}}{{/vars}}]; @@ -21,6 +30,14 @@ } } +/** + * Gets the string presentation of the object. + * This method will be called when logging model object using `NSLog`. + */ +- (NSString *)description { + return [[self toDictionary] description]; +} + {{/model}} @end {{/models}} diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/model-header.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/model-header.mustache index a899dcdd461..c3f3c865424 100644 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/model-header.mustache +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/model-header.mustache @@ -1,5 +1,12 @@ #import -#import "FTObject.h" +#import "{{classPrefix}}Object.h" + +/** + * 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. + */ + {{#imports}}#import "{{import}}.h" {{/imports}} {{newline}} @@ -8,8 +15,8 @@ @protocol {{classname}} @end - -@interface {{classname}} : FTObject + +@interface {{classname}} : {{classPrefix}}Object {{#vars}} {{#description}}/* {{{description}}} {{^required}}[optional]{{/required}} diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/podspec.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/podspec.mustache new file mode 100644 index 00000000000..9ce03695bcf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/fotition-objc/podspec.mustache @@ -0,0 +1,31 @@ +# +# Be sure to run `pod lib lint {{podName}}.podspec' to ensure this is a +# valid spec and remove all comments before submitting the spec. +# +# Any lines starting with a # are optional, but encouraged +# +# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html +# + +Pod::Spec.new do |s| + s.name = "{{podName}}" + s.version = "{{podVersion}}" +{{#apiInfo}}{{#apis}}{{^hasMore}} + s.summary = "{{appName}}" + s.description = <<-DESC + {{appDescription}} + DESC +{{/hasMore}}{{/apis}}{{/apiInfo}} + s.platform = :ios, '7.0' + s.requires_arc = true + + s.framework = 'SystemConfiguration' + + s.source_files = '{{podName}}/**/*' + s.public_header_files = '{{podName}}/**/*.h' + + s.dependency 'AFNetworking', '~> 2.3' + s.dependency 'JSONModel', '~> 1.1' + s.dependency 'ISO8601', '~> 0.3' +end + diff --git a/modules/swagger-codegen/src/main/resources/fotition-objc/voidResponse.mustache b/modules/swagger-codegen/src/main/resources/fotition-objc/voidResponse.mustache deleted file mode 100644 index 4fdc7c190e8..00000000000 --- a/modules/swagger-codegen/src/main/resources/fotition-objc/voidResponse.mustache +++ /dev/null @@ -1,16 +0,0 @@ - return [self.apiClient stringWithCompletionBlock: requestUrl - method: @"{{httpMethod}}" - queryParams: queryParams - body: bodyDictionary - headerParams: headerParams - authSettings: authSettings - requestContentType: requestContentType - responseContentType: responseContentType - completionBlock: ^(NSDictionary *responseHeaders, NSString *data, NSError *error) { - if (error) { - // no data to return - completionBlock(responseHeaders, error); - return; - } - completionBlock(responseHeaders, nil); - }]; From 3464a92ce83556ab815093d901ad21c1adc87510 Mon Sep 17 00:00:00 2001 From: Matthew Davis Date: Fri, 21 Aug 2015 15:14:33 -0700 Subject: [PATCH 02/10] fixed a typo in the custom client codegen file --- README.md | 380 +----------------- .../languages/FotitionClientCodegen.java | 8 +- 2 files changed, 15 insertions(+), 373 deletions(-) diff --git a/README.md b/README.md index 7dfad508092..8902e17ad24 100644 --- a/README.md +++ b/README.md @@ -1,383 +1,23 @@ -# Swagger Code Generator +# FotitionSDK -[![Build Status](https://travis-ci.org/swagger-api/swagger-codegen.png)](https://travis-ci.org/swagger-api/swagger-codegen) +## Requirements -## Overview -This is the swagger codegen project, which allows generation of client libraries automatically from a Swagger-compliant server. +The API client library requires ARC (Automatic Reference Counting) to be enabled in your Xcode project. -Check out [Swagger-Spec](https://github.com/swagger-api/swagger-spec) for additional information about the Swagger project, including additional libraries with support for other languages and more. +## Installation -## Build and run using docker +To install it, put the API client library in your project and then simply add the following line to your Podfile: +```ruby +pod "FotitionSDK", :path => "/path/to/lib" ``` -git clone https://github.com/swagger-api/swagger-codegen -cd swagger-codegen +## Recommendation -./run-in-docker.sh mvn package - ``` +It's recommended to create an instance of ApiClient per thread in a multithreaded environment to avoid any potential issue. -Build a nodejs server stub: +## Author - ``` -./run-in-docker.sh generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l nodejs \ - -o samples/server/petstore/nodejs - ``` -## Compatibility -The Swagger Specification has undergone 3 revisions since initial creation in 2010. The swagger-codegen project has the following compatibilies with the swagger specification: -Swagger Codegen Version | Release Date | Swagger Spec compatibility | Notes ------------------------ | ------------ | -------------------------- | ----- -2.1.2 | 2015-06-09 | 1.0, 1.1, 1.2, 2.0 | [master](https://github.com/swagger-api/swagger-codegen) -2.0.17 | 2014-08-22 | 1.1, 1.2 | [tag v2.0.17](https://github.com/swagger-api/swagger-codegen/tree/v2.0.17) -1.0.4 | 2012-04-12 | 1.0, 1.1 | [tag v1.0.4](https://github.com/swagger-api/swagger-codegen/tree/swagger-codegen_2.9.1-1.1) - -### Prerequisites -You need the following installed and available in your $PATH: - -* [Java 7](http://java.oracle.com) - -* [Apache maven 3.0.3 or greater](http://maven.apache.org/) - -#### OS X Users -Don't forget to install Java 7. You probably have 1.6 or 1.8. - -Export JAVA_HOME in order to user proper Java version: -``` -export JAVA_HOME=`/usr/libexec/java_home -v 1.7` -export PATH=${JAVA_HOME}/bin:$PATH -``` - -#### Building - -After cloning the project, you can build it from source with this command: - -``` -mvn package -``` - -### To generate a sample client library -You can build a client against the swagger sample [petstore](http://petstore.swagger.io) API as follows: - -``` -./bin/java-petstore.sh -``` - -This will run the generator with this command: - -``` -java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ - -i http://petstore.swagger.io/v2/swagger.json \ - -l java \ - -o samples/client/petstore/java -``` - -With a number of options. You can get the options with the `help generate` command: - -``` -NAME - swagger generate - Generate code with chosen lang - -SYNOPSIS - swagger generate [(-a | --auth )] - [(-c | --config )] - [-D ] - (-i | --input-spec ) - (-l | --lang ) - [(-o | --output )] - [(-t