This commit is contained in:
wing328 2016-09-16 23:45:44 +08:00
commit d5e4b24416
186 changed files with 15482 additions and 7040 deletions

View File

@ -3,7 +3,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.2.2-SNAPSHOT</version>
<version>2.3.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -6,7 +6,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.2.2-SNAPSHOT</version>
<version>2.3.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<artifactId>swagger-codegen-maven-plugin</artifactId>

View File

@ -3,7 +3,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.2.2-SNAPSHOT</version>
<version>2.3.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>

View File

@ -255,10 +255,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Object-body.mustache", coreFileFolder(), classPrefix + "Object.m"));
supportingFiles.add(new SupportingFile("QueryParamCollection-header.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.h"));
supportingFiles.add(new SupportingFile("QueryParamCollection-body.mustache", coreFileFolder(), classPrefix + "QueryParamCollection.m"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
supportingFiles.add(new SupportingFile("ApiClient-header.mustache", coreFileFolder(), classPrefix + "ApiClient.h"));
supportingFiles.add(new SupportingFile("ApiClient-body.mustache", coreFileFolder(), classPrefix + "ApiClient.m"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("JSONResponseSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-body.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.m"));
supportingFiles.add(new SupportingFile("JSONRequestSerializer-header.mustache", coreFileFolder(), classPrefix + "JSONRequestSerializer.h"));
supportingFiles.add(new SupportingFile("ResponseDeserializer-body.mustache", coreFileFolder(), classPrefix + "ResponseDeserializer.m"));
@ -269,8 +267,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("Logger-header.mustache", coreFileFolder(), classPrefix + "Logger.h"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-body.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601-header.mustache", coreFileFolder(), "JSONValueTransformer+ISO8601.h"));
supportingFiles.add(new SupportingFile("Configuration-body.mustache", coreFileFolder(), classPrefix + "Configuration.m"));
supportingFiles.add(new SupportingFile("Configuration-header.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("Configuration-protocol.mustache", coreFileFolder(), classPrefix + "Configuration.h"));
supportingFiles.add(new SupportingFile("DefaultConfiguration-body.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.m"));
supportingFiles.add(new SupportingFile("DefaultConfiguration-header.mustache", coreFileFolder(), classPrefix + "DefaultConfiguration.h"));
supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-header.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.h"));
supportingFiles.add(new SupportingFile("BasicAuthTokenProvider-body.mustache", coreFileFolder(), classPrefix + "BasicAuthTokenProvider.m"));
supportingFiles.add(new SupportingFile("api-protocol.mustache", coreFileFolder(), classPrefix + "Api.h"));
supportingFiles.add(new SupportingFile("podspec.mustache", "", podName + ".podspec"));
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));

View File

@ -25,17 +25,15 @@ import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig {
protected static String PREFIX = "Sami";
protected Set<String> foundationClasses = new HashSet<String>();
protected String sourceFolder = "client";
protected Map<String, String> namespaces = new HashMap<String, String>();
protected static String PREFIX = "ArtikCloud";
protected String sourceFolder = "src";
protected String documentationFolder = "doc";
public TizenClientCodegen() {
super();
outputFolder = "generated-code/tizen";
outputFolder = "";
modelTemplateFiles.put("model-header.mustache", ".h");
modelTemplateFiles.put("model-body.mustache", ".cpp");
apiTemplateFiles.put("api-header.mustache", ".h");
@ -47,70 +45,71 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
Arrays.asList(
"bool",
"int",
"long")
"long long",
"double",
"float")
);
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"bool",
"int",
"long long",
"double",
"float",
"std::string")
);
languageSpecificPrimitives = new HashSet<String>();
additionalProperties().put("prefix", PREFIX);
setReservedWordsLowerCase(
// VERIFY
Arrays.asList(
"void", "char", "short", "int", "void", "char", "short", "int",
"long", "float", "double", "signed", "unsigned", "id", "const",
"volatile", "in", "out", "inout", "bycopy", "byref", "oneway",
"self", "super"
"alignas", "alignof", "and", "and_eq", "asm", "atomic_cancel", "atomic_commit", "atomic_noexcept",
"auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t",
"class", "compl", "concept", "const", "constexpr", "const_cast", "continue", "decltype", "default",
"delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false",
"float", "for", "friend", "goto", "if", "inline", "int", "import", "long", "module", "mutable",
"namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private",
"protected", "public", "register", "reinterpret_cast", "requires", "return", "short", "signed",
"sizeof", "static", "static_assert", "static_cast", "struct", "switch", "synchronized", "template",
"this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union",
"unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq"
));
super.typeMapping = new HashMap<String, String>();
typeMapping.put("Date", "DateTime");
typeMapping.put("DateTime", "DateTime");
typeMapping.put("string", "String");
typeMapping.put("integer", "Integer");
typeMapping.put("float", "Float");
typeMapping.put("long", "Long");
typeMapping.put("boolean", "Boolean");
typeMapping.put("double", "Double");
typeMapping.put("array", "IList");
typeMapping.put("map", "HashMap");
typeMapping.put("number", "Long");
typeMapping.put("object", PREFIX + "Object");
//TODO binary should be mapped to byte array
// mapped to String as a workaround
typeMapping.put("binary", "String");
//typeMapping.put("Date", "DateTime");
//typeMapping.put("DateTime", "DateTime");
typeMapping.put("string", "std::string");
typeMapping.put("integer", "int");
typeMapping.put("float", "float");
typeMapping.put("long", "long long");
typeMapping.put("boolean", "bool");
typeMapping.put("double", "double");
typeMapping.put("array", "std::list");
typeMapping.put("map", "std::map");
typeMapping.put("number", "long long");
typeMapping.put("object", "std::string");
typeMapping.put("binary", "std::string");
typeMapping.put("password", "std::string");
//TODO:Maybe use better formats for dateTime?
typeMapping.put("file", "std::string");
typeMapping.put("DateTime", "std::string");
typeMapping.put("Date", "std::string");
importMapping = new HashMap<String, String>();
namespaces = new HashMap<String, String>();
namespaces.put("DateTime", "Tizen::Base::DateTime");
namespaces.put("Integer", "Tizen::Base::Integer");
namespaces.put("Long", "Tizen::Base::Long");
namespaces.put("Boolean", "Tizen::Base::Boolean");
namespaces.put("Float", "Tizen::Base::Float");
namespaces.put("String", "Tizen::Base::String");
namespaces.put("Double", "Tizen::Base::Double");
namespaces.put("IList", "Tizen::Base::Collection::IList");
namespaces.put("HashMap", "Tizen::Base::Collection::HashMap");
namespaces.put("ArrayList", "Tizen::Base::Collection::ArrayList");
namespaces.put("JsonNumber", "Tizen::Web::Json");
namespaces.put("JsonString", "Tizen::Web::Json");
foundationClasses = new HashSet<String>(
Arrays.asList(
"String",
"Integer",
"Float")
);
supportingFiles.clear();
supportingFiles.add(new SupportingFile("modelFactory.mustache", sourceFolder, PREFIX + "ModelFactory.h"));
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, PREFIX + "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, PREFIX + "Helpers.cpp"));
supportingFiles.add(new SupportingFile("apiclient-header.mustache", sourceFolder, PREFIX + "ApiClient.h"));
supportingFiles.add(new SupportingFile("apiclient-body.mustache", sourceFolder, PREFIX + "ApiClient.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, PREFIX + "Object.h"));
supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, PREFIX + "Error.h"));
supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, PREFIX + "Error.cpp"));
supportingFiles.add(new SupportingFile("helpers-header.mustache", sourceFolder, "Helpers.h"));
supportingFiles.add(new SupportingFile("helpers-body.mustache", sourceFolder, "Helpers.cpp"));
supportingFiles.add(new SupportingFile("netclient-header.mustache", sourceFolder, "NetClient.h"));
supportingFiles.add(new SupportingFile("netclient-body.mustache", sourceFolder, "NetClient.cpp"));
supportingFiles.add(new SupportingFile("object.mustache", sourceFolder, "Object.h"));
supportingFiles.add(new SupportingFile("requestinfo.mustache", sourceFolder, "RequestInfo.h"));
supportingFiles.add(new SupportingFile("error-header.mustache", sourceFolder, "Error.h"));
supportingFiles.add(new SupportingFile("error-body.mustache", sourceFolder, "Error.cpp"));
supportingFiles.add(new SupportingFile("Doxyfile.mustache", documentationFolder, "Doxyfile"));
supportingFiles.add(new SupportingFile("generateDocumentation.mustache", documentationFolder, "generateDocumentation.sh"));
supportingFiles.add(new SupportingFile("doc-readme.mustache", documentationFolder, "README.md"));
}
@Override
@ -141,10 +140,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getTypeDeclaration(String name) {
if (languageSpecificPrimitives.contains(name) && !foundationClasses.contains(name)) {
if (languageSpecificPrimitives.contains(name)) {
return name;
} else {
return name + "*";
return name + "";
}
}
@ -154,7 +153,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
String type = null;
if (typeMapping.containsKey(swaggerType)) {
type = typeMapping.get(swaggerType);
if (languageSpecificPrimitives.contains(type) && !foundationClasses.contains(type)) {
if (languageSpecificPrimitives.contains(type)) {
return toModelName(type);
}
} else {
@ -166,10 +165,10 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String getTypeDeclaration(Property p) {
String swaggerType = getSwaggerType(p);
if (languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) {
if (languageSpecificPrimitives.contains(swaggerType)) {
return toModelName(swaggerType);
} else {
return swaggerType + "*";
return swaggerType + "";
}
}
@ -177,48 +176,48 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
public String toModelName(String type) {
if (typeMapping.keySet().contains(type) ||
typeMapping.values().contains(type) ||
foundationClasses.contains(type) ||
importMapping.values().contains(type) ||
defaultIncludes.contains(type) ||
languageSpecificPrimitives.contains(type)) {
return type;
} else {
return PREFIX + Character.toUpperCase(type.charAt(0)) + type.substring(1);
return Character.toUpperCase(type.charAt(0)) + type.substring(1);
}
}
@Override
public String toModelImport(String name) {
if (namespaces.containsKey(name)) {
return "using " + namespaces.get(name) + ";";
if (name.equals("std::string")) {
return "#include <string>";
} else if (name.equals("std::map")) {
return "#include <map>";
} else if (name.equals("std::list")) {
return "#include <list>";
}
return "#include \"" + name + ".h\"";
}
//Might not be needed
@Override
public String toDefaultValue(Property p) {
if (p instanceof StringProperty) {
return "new String()";
return "std::string()";
} else if (p instanceof BooleanProperty) {
return "new Boolean(false)";
} else if (p instanceof DateProperty) {
return "new DateTime()";
} else if (p instanceof DateTimeProperty) {
return "new DateTime()";
return "bool(false)";
} else if (p instanceof DoubleProperty) {
return "new Double()";
return "double(0)";
} else if (p instanceof FloatProperty) {
return "new Float()";
return "float(0)";
} else if (p instanceof IntegerProperty) {
return "new Integer()";
return "int(0)";
} else if (p instanceof LongProperty) {
return "new Long()";
return "long(0)";
} else if (p instanceof DecimalProperty) {
return "new Long()";
return "long(0)";
} else if (p instanceof MapProperty) {
return "new HashMap()";
return "new std::map()";
} else if (p instanceof ArrayProperty) {
return "new ArrayList()";
return "new std::list()";
}
// else
if (p instanceof RefProperty) {
@ -228,6 +227,7 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
return "null";
}
@Override
public String apiFileFolder() {
return outputFolder + File.separator + sourceFolder;
@ -240,24 +240,27 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toModelFilename(String name) {
return PREFIX + initialCaps(name);
return initialCaps(name);
}
@Override
public String toApiName(String name) {
return PREFIX + initialCaps(name) + "Api";
return initialCaps(name) + "Manager";
}
@Override
public String toApiFilename(String name) {
return PREFIX + initialCaps(name) + "Api";
return initialCaps(name) + "Manager";
}
@Override
public String toVarName(String name) {
String paramName = name.replaceAll("[^a-zA-Z0-9_]", "");
paramName = Character.toUpperCase(paramName.charAt(0)) + paramName.substring(1);
return "p" + paramName;
paramName = Character.toLowerCase(paramName.charAt(0)) + paramName.substring(1);
if (isReservedWord(paramName)) {
return escapeReservedWord(paramName);
}
return "" + paramName;
}
@Override
@ -268,27 +271,17 @@ public class TizenClientCodegen extends DefaultCodegen implements CodegenConfig
@Override
public String toOperationId(String operationId) {
// throw exception if method name is empty
if (StringUtils.isEmpty(operationId)) {
if (operationId=="") {
throw new RuntimeException("Empty method name (operationId) not allowed");
}
// method name cannot use reserved keyword, e.g. return$
if (isReservedWord(operationId)) {
throw new RuntimeException(operationId + " (reserved word) cannot be used as method name");
operationId = escapeReservedWord(operationId);
}
// add_pet_by_id => addPetById
return camelize(operationId, true);
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("*/", "*_/").replace("/*", "/_*");
}
}

View File

@ -1,14 +1,13 @@
#import "{{classPrefix}}Logger.h"
#import "{{classPrefix}}ApiClient.h"
#import "{{classPrefix}}JSONRequestSerializer.h"
#import "{{classPrefix}}QueryParamCollection.h"
#import "{{classPrefix}}DefaultConfiguration.h"
NSString *const {{classPrefix}}ResponseObjectErrorKey = @"{{classPrefix}}ResponseObject";
static NSUInteger requestId = 0;
static bool offlineState = false;
static NSMutableSet * queuedRequests = nil;
static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static void (^reachabilityChangeBlock)(int);
static NSString * const k{{classPrefix}}ContentDispositionKey = @"Content-Disposition";
static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
@ -19,179 +18,80 @@ static NSDictionary * {{classPrefix}}__headerFieldsForResponse(NSURLResponse *re
static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = {{classPrefix}}__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
if(!headers[k{{classPrefix}}ContentDispositionKey]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSString *contentDispositionHeader = headers[k{{classPrefix}}ContentDispositionKey];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
@interface {{classPrefix}}ApiClient ()
@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders;
@property (nonatomic, strong, readwrite) id<{{classPrefix}}Configuration> configuration;
@property (nonatomic, strong) NSArray<NSString*>* downloadTaskResponseTypes;
@end
@implementation {{classPrefix}}ApiClient
#pragma mark - Singleton Methods
+ (instancetype) sharedClient {
static {{classPrefix}}ApiClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[self alloc] init];
});
return sharedClient;
}
#pragma mark - Initialize Methods
- (instancetype)init {
NSString *baseUrl = [[{{classPrefix}}Configuration sharedConfig] host];
return [self initWithBaseURL:[NSURL URLWithString:baseUrl]];
return [self initWithConfiguration:[{{classPrefix}}DefaultConfiguration sharedConfig]];
}
- (instancetype)initWithBaseURL:(NSURL *)url {
return [self initWithBaseURL:url configuration:[{{classPrefix}}DefaultConfiguration sharedConfig]];
}
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration {
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<{{classPrefix}}Configuration>)configuration {
self = [super initWithBaseURL:url];
if (self) {
self.timeoutInterval = 60;
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [self customSecurityPolicy];
self.responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
self.sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
// configure reachability
[self configureCacheReachibility];
_configuration = configuration;
_timeoutInterval = 60;
_responseDeserializer = [[{{classPrefix}}ResponseDeserializer alloc] init];
_sanitizer = [[{{classPrefix}}Sanitizer alloc] init];
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer];
_requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer,
@"application/x-www-form-urlencoded": afhttpRequestSerializer,
@"multipart/form-data": afhttpRequestSerializer
};
self.securityPolicy = [self createSecurityPolicy];
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
return self;
}
+ (void)initialize {
if (self == [{{classPrefix}}ApiClient class]) {
queuedRequests = [[NSMutableSet alloc] init];
// initialize URL cache
[self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024];
}
}
#pragma mark - Task Methods
#pragma mark - Setter Methods
+ (void) setOfflineState:(BOOL) state {
offlineState = state;
}
+ (void) setCacheEnabled:(BOOL)enabled {
cacheEnabled = enabled;
}
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
reachabilityStatus = status;
}
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
}
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
[super setRequestSerializer:requestSerializer];
requestSerializer.timeoutInterval = self.timeoutInterval;
}
#pragma mark - Cache Methods
+(void)clearCache {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
diskSize: (unsigned long) diskSize {
NSAssert(memorySize > 0, @"invalid in-memory cache size");
NSAssert(diskSize >= 0, @"invalid disk cache size");
NSURLCache *cache =
[[NSURLCache alloc]
initWithMemoryCapacity:memorySize
diskCapacity:diskSize
diskPath:@"swagger_url_cache"];
[NSURLCache setSharedURLCache:cache];
}
#pragma mark - Request Methods
+(NSUInteger)requestQueueSize {
return [queuedRequests count];
}
+(NSNumber*) nextRequestId {
@synchronized(self) {
return @(++requestId);
}
}
+(NSNumber*) queueRequest {
NSNumber* requestId = [[self class] nextRequestId];
{{classPrefix}}DebugLog(@"added %@ to request queue", requestId);
[queuedRequests addObject:requestId];
return requestId;
}
+(void) cancelRequest:(NSNumber*)requestId {
[queuedRequests removeObject:requestId];
}
-(Boolean) executeRequestWithId:(NSNumber*) requestId {
NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) {
return [obj intValue] == [requestId intValue];
}];
if (matchingItems.count == 1) {
{{classPrefix}}DebugLog(@"removed request id %@", requestId);
[queuedRequests removeObject:requestId];
return YES;
} else {
return NO;
}
}
#pragma mark - Reachability Methods
+(AFNetworkReachabilityStatus) getReachabilityStatus {
return reachabilityStatus;
}
+(BOOL) getOfflineState {
return offlineState;
}
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
reachabilityChangeBlock = changeBlock;
}
- (void) configureCacheReachibility {
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
reachabilityStatus = status;
{{classPrefix}}DebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
[{{classPrefix}}ApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
// call the reachability block, if configured
if (reachabilityChangeBlock != nil) {
reachabilityChangeBlock(status);
}
}];
[self.reachabilityManager startMonitoring];
}
#pragma mark - Operation Methods
- (void) operationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock {
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (![strongSelf executeRequestWithId:requestId]) {
return;
}
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response);
if(!error) {
completionBlock(responseObject, nil);
return;
@ -204,20 +104,17 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
}];
[op resume];
return task;
}
- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock {
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (![strongSelf executeRequestWithId:requestId]) {
return;
}
strongSelf.HTTPResponseHeaders = {{classPrefix}}__headerFieldsForResponse(response);
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
{{classPrefix}}DebugLogResponse(response, responseObject,request,error);
if(error) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
@ -225,9 +122,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
return;
}
NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory();
NSString * filename = {{classPrefix}}__fileNameForResponse(response);
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
NSString *filename = {{classPrefix}}__fileNameForResponse(response);
NSString *filepath = [directory stringByAppendingPathComponent:filename];
NSURL *file = [NSURL fileURLWithPath:filepath];
@ -236,53 +135,37 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
completionBlock(file, nil);
}];
[op resume];
return task;
}
#pragma mark - Perform Request Methods
#pragma mark - Perform Request Methods
-(NSNumber*) requestWithPath: (NSString*) path
method: (NSString*) method
pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams
formParams: (NSDictionary *) formParams
files: (NSDictionary *) files
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [{{classPrefix}}JSONRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
NSAssert(NO, @"Unsupported request type %@", requestContentType);
}
- (NSURLSessionTask*) requestWithPath: (NSString*) path
method: (NSString*) method
pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams
formParams: (NSDictionary *) formParams
files: (NSDictionary *) files
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [{{classPrefix}}JSONResponseSerializer serializer];
} else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
// sanitize parameters
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
formParams = [self.sanitizer sanitizeForSerialization:formParams];
pathParams = [sanitizer sanitizeForSerialization:pathParams];
queryParams = [sanitizer sanitizeForSerialization:queryParams];
headerParams = [sanitizer sanitizeForSerialization:headerParams];
formParams = [sanitizer sanitizeForSerialization:formParams];
if(![body isKindOfClass:[NSData class]]) {
body = [self.sanitizer sanitizeForSerialization:body];
body = [sanitizer sanitizeForSerialization:body];
}
// auth setting
@ -295,22 +178,19 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
}];
NSMutableURLRequest * request = nil;
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
if ([pathWithQueryParams hasPrefix:@"/"]) {
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
}
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
NSError *requestCreateError = nil;
NSMutableURLRequest * request = nil;
if (files.count > 0) {
__weak __typeof(self)weakSelf = self;
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
NSString *objString = [sanitizer parameterToString:obj];
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:key];
}];
@ -318,76 +198,73 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSURL *filePath = (NSURL *)obj;
[formData appendPartWithFileURL:filePath name:key error:nil];
}];
} error:nil];
} error:&requestCreateError];
}
else {
if (formParams) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:formParams
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
}
if (body) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
}
}
// request cache
BOOL hasHeaderParams = [headerParams count] > 0;
if (offlineState) {
{{classPrefix}}DebugLog(@"%@ cache forced", resourcePath);
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
{{classPrefix}}DebugLog(@"%@ cache enabled", resourcePath);
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
}
else {
{{classPrefix}}DebugLog(@"%@ cache disabled", resourcePath);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
if(!request) {
completionBlock(nil, requestCreateError);
return nil;
}
if (hasHeaderParams){
if ([headerParams count] > 0){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[self postProcessRequest:request];
NSNumber* requestId = [{{classPrefix}}ApiClient queueRequest];
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
[self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
NSURLSessionTask *task = nil;
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
completionBlock(data, error);
}];
}
else {
[self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
} else {
__weak typeof(self) weakSelf = self;
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
NSError * serializationError;
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError];
if(!response && !error){
error = serializationError;
}
completionBlock(response, error);
}];
}
return requestId;
[task resume];
return task;
}
-(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
AFHTTPRequestSerializer <AFURLRequestSerialization> * serializer = self.requestSerializerForContentType[requestContentType];
if(!serializer) {
NSAssert(NO, @"Unsupported request content type %@", requestContentType);
serializer = [AFHTTPRequestSerializer serializer];
}
serializer.timeoutInterval = self.timeoutInterval;
return serializer;
}
//Added for easier override to modify request
-(void)postProcessRequest:(NSMutableURLRequest *)request {
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
}
#pragma mark -
- (NSString*) pathWithQueryParamsToString:(NSString*) path
queryParams:(NSDictionary*) queryParams {
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
if(queryParams.count == 0) {
return path;
}
@ -445,9 +322,7 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
/**
* Update header and query params based on authentication settings
*/
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
queryParams:(NSDictionary *__autoreleasing *)querys
WithAuthSettings:(NSArray *)authSettings {
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
if ([authSettings count] == 0) {
return;
@ -455,10 +330,11 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
NSDictionary* configurationAuthSettings = [[self configuration] authSettings];
id<{{classPrefix}}Configuration> config = self.configuration;
for (NSString *auth in authSettings) {
NSDictionary *authSetting = configurationAuthSettings[auth];
NSDictionary *authSetting = config.authSettings[auth];
if(!authSetting) { // auth setting is set only if the key is non-empty
continue;
}
@ -476,14 +352,14 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
- (AFSecurityPolicy *) customSecurityPolicy {
- (AFSecurityPolicy *) createSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
{{classPrefix}}Configuration *config = [self configuration];
id<{{classPrefix}}Configuration> config = self.configuration;
if (config.sslCaCert) {
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
[securityPolicy setPinnedCertificates:@[certData]];
[securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]];
}
if (config.verifySSL) {
@ -497,8 +373,4 @@ static NSString * {{classPrefix}}__fileNameForResponse(NSURLResponse *response)
return securityPolicy;
}
- ({{classPrefix}}Configuration*) configuration {
return [{{classPrefix}}Configuration sharedConfig];
}
@end

View File

@ -1,22 +1,10 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <AFNetworking/AFNetworking.h>
#import "{{classPrefix}}JSONResponseSerializer.h"
#import "{{classPrefix}}JSONRequestSerializer.h"
#import "{{classPrefix}}QueryParamCollection.h"
#import "{{classPrefix}}Configuration.h"
#import "{{classPrefix}}ResponseDeserializer.h"
#import "{{classPrefix}}Sanitizer.h"
#import "{{classPrefix}}Logger.h"
{{>licenceInfo}}
{{#models}}{{#model}}#import "{{classname}}.h"
{{/model}}{{/models}}
{{^models}}#import "{{classPrefix}}Object.h"{{/models}}
@class {{classPrefix}}Configuration;
/**
* A key for `NSError` user info dictionaries.
*
@ -24,118 +12,42 @@
*/
extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
@interface {{classPrefix}}ApiClient : AFHTTPSessionManager
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readonly) NSOperationQueue* queue;
@property (nonatomic, strong, readonly) id<{{classPrefix}}Configuration> configuration;
/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one {{classPrefix}}ApiClient instance per thread.
@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, strong) id<{{classPrefix}}ResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<{{classPrefix}}Sanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
/**
* Turns on cache
*
* @param enabled If the cached is enable, must be `YES` or `NO`
* Gets client singleton instance
*/
+(void)setCacheEnabled:(BOOL) enabled;
+ (instancetype) sharedClient;
/**
* Gets the request queue size
*
* @return The size of `queuedRequests` static variable.
*/
+(NSUInteger)requestQueueSize;
/**
* Sets the client unreachable
*
* @param state off line state, must be `YES` or `NO`
*/
+(void) setOfflineState:(BOOL) state;
/**
* Gets if the client is unreachable
*
* @return The client offline state
*/
+(BOOL) getOfflineState;
/**
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
*
* @param The client reachability.
*/
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
/**
* Gets the client reachability
*
* @return The client reachability.
*/
+(AFNetworkReachabilityStatus) getReachabilityStatus;
/**
* Gets the next request id
*
* @return The next executed request id.
*/
+(NSNumber*) nextRequestId;
/**
* Generates request id and add it to the queue
*
* @return The next executed request id.
*/
+(NSNumber*) queueRequest;
/**
* Removes request id from the queue
*
* @param requestId The request which will be removed.
*/
+(void) cancelRequest:(NSNumber*)requestId;
/**
* Customizes the behavior when the reachability changed
*
* @param changeBlock The block will be executed when the reachability changed.
*/
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
/**
* Sets the api client reachability strategy
*/
- (void)configureCacheReachibility;
/**
* Sets header for request
*
* @param value The header value
* @param forKey The header key
*/
-(void)setHeaderValue:(NSString*) value
forKey:(NSString*) forKey;
/**
* Updates header parameters and query parameters for authentication
*
* @param headers The header parameter will be updated, passed by pointer to pointer.
* @param headers The header parameter will be udpated, passed by pointer to pointer.
* @param querys The query parameters will be updated, passed by pointer to pointer.
* @param authSettings The authentication names NSArray.
*/
- (void) updateHeaderParams:(NSDictionary **)headers
queryParams:(NSDictionary **)querys
WithAuthSettings:(NSArray *)authSettings;
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
/**
* Initializes the session manager with a configuration.
*
* @param configuration The configuration implementation
*/
- (instancetype)initWithConfiguration:(id<{{classPrefix}}Configuration>)configuration;
/**
* Performs request
*
@ -150,35 +62,20 @@ extern NSString *const {{classPrefix}}ResponseObjectErrorKey;
* @param responseContentType Response content-type.
* @param completionBlock The block will be executed when the request completed.
*
* @return The request id.
* @return The created session task.
*/
-(NSNumber*) requestWithPath:(NSString*) path
method:(NSString*) method
pathParams:(NSDictionary *) pathParams
queryParams:(NSDictionary*) queryParams
formParams:(NSDictionary *) formParams
files:(NSDictionary *) files
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings:(NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
responseType:(NSString *) responseType
completionBlock:(void (^)(id, NSError *))completionBlock;
/**
* Custom security policy
*
* @return AFSecurityPolicy
*/
- (AFSecurityPolicy *) customSecurityPolicy;
/**
* {{classPrefix}}Configuration return sharedConfig
*
* @return {{classPrefix}}Configuration
*/
- ({{classPrefix}}Configuration*) configuration;
- (NSURLSessionTask*) requestWithPath: (NSString*) path
method: (NSString*) method
pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams
formParams: (NSDictionary *) formParams
files: (NSDictionary *) files
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock;
@end

View File

@ -0,0 +1,19 @@
#import "{{classPrefix}}BasicAuthTokenProvider.h"
@implementation {{classPrefix}}BasicAuthTokenProvider
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password {
// return empty string if username and password are empty
if (username.length == 0 && password.length == 0){
return @"";
}
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials;
}
@end

View File

@ -0,0 +1,14 @@
/** The `{{classPrefix}}BasicAuthTokenProvider` class creates a basic auth token from username and password.
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
#import <Foundation/Foundation.h>
@interface {{classPrefix}}BasicAuthTokenProvider : NSObject
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
@end

View File

@ -0,0 +1,78 @@
#import <Foundation/Foundation.h>
@class {{classPrefix}}Logger;
{{>licenceInfo}}
static NSString * const k{{classPrefix}}APIVersion = @"{{podVersion}}";
@protocol {{classPrefix}}Configuration <NSObject>
/**
* Api logger
*/
@property (readonly, nonatomic) {{classPrefix}}Logger *logger;
/**
* Base url
*/
@property (readonly, nonatomic) NSString *host;
/**
* Api key values for Api Key type Authentication
*/
@property (readonly, nonatomic) NSDictionary *apiKey;
/**
* Api key prefix values to be prepend to the respective api key
*/
@property (readonly, nonatomic) NSDictionary *apiKeyPrefix;
/**
* Username for HTTP Basic Authentication
*/
@property (readonly, nonatomic) NSString *username;
/**
* Password for HTTP Basic Authentication
*/
@property (readonly, nonatomic) NSString *password;
/**
* Access token for OAuth
*/
@property (readonly, nonatomic) NSString *accessToken;
/**
* Temp folder for file download
*/
@property (readonly, nonatomic) NSString *tempFolderPath;
/**
* Debug switch, default false
*/
@property (readonly, nonatomic) BOOL debug;
/**
* SSL/TLS verification
* Set this to NO to skip verifying SSL certificate when calling API from https server
*/
@property (readonly, nonatomic) BOOL verifySSL;
/**
* SSL/TLS verification
* Set this to customize the certificate file to verify the peer
*/
@property (readonly, nonatomic) NSString *sslCaCert;
/**
* Authentication Settings
*/
@property (readonly, nonatomic) NSDictionary *authSettings;
/**
* Default headers for all services
*/
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
@end

View File

@ -1,6 +1,8 @@
#import "{{classPrefix}}Configuration.h"
#import "{{classPrefix}}DefaultConfiguration.h"
#import "{{classPrefix}}BasicAuthTokenProvider.h"
#import "{{classPrefix}}Logger.h"
@interface {{classPrefix}}Configuration ()
@interface {{classPrefix}}DefaultConfiguration ()
@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders;
@property (nonatomic, strong) NSMutableDictionary *mutableApiKey;
@ -8,12 +10,12 @@
@end
@implementation {{classPrefix}}Configuration
@implementation {{classPrefix}}DefaultConfiguration
#pragma mark - Singleton Methods
+ (instancetype) sharedConfig {
static {{classPrefix}}Configuration *shardConfig = nil;
static {{classPrefix}}DefaultConfiguration *shardConfig = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shardConfig = [[self alloc] init];
@ -26,17 +28,16 @@
- (instancetype) init {
self = [super init];
if (self) {
self.apiClient = nil;
self.host = @"{{basePath}}";
self.username = @"";
self.password = @"";
self.accessToken= @"";
self.verifySSL = YES;
self.mutableApiKey = [NSMutableDictionary dictionary];
self.mutableApiKeyPrefix = [NSMutableDictionary dictionary];
self.mutableDefaultHeaders = [NSMutableDictionary dictionary];
self.mutableDefaultHeaders[@"User-Agent"] = {{#httpUserAgent}}@"{{httpUserAgent}}"{{/httpUserAgent}}{{^httpUserAgent}}[NSString stringWithFormat:@"Swagger-Codegen/{{version}}/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]]{{/httpUserAgent}};
self.logger = [{{classPrefix}}Logger sharedLogger];
_host = @"{{basePath}}";
_username = @"";
_password = @"";
_accessToken= @"";
_verifySSL = YES;
_mutableApiKey = [NSMutableDictionary dictionary];
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
{{#httpUserAgent}}_mutableDefaultHeaders[@"User-Agent"] = @"{{httpUserAgent}}";{{/httpUserAgent}}
_logger = [{{classPrefix}}Logger sharedLogger];
}
return self;
}
@ -58,16 +59,9 @@
}
- (NSString *) getBasicAuthToken {
// return empty string if username and password are empty
if (self.username.length == 0 && self.password.length == 0){
return @"";
}
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials;
NSString *basicAuthToken = [{{classPrefix}}BasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password];
return basicAuthToken;
}
- (NSString *) getAccessToken {
@ -150,8 +144,6 @@
self.logger.enabled = debug;
}
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
if(!value) {
[self.mutableDefaultHeaders removeObjectForKey:key];

View File

@ -1,23 +1,18 @@
#import <Foundation/Foundation.h>
#import "{{classPrefix}}ApiClient.h"
#import "{{classPrefix}}Logger.h"
#import "{{classPrefix}}Configuration.h"
{{>licenceInfo}}
@class {{classPrefix}}ApiClient;
@interface {{classPrefix}}Configuration : NSObject
@interface {{classPrefix}}DefaultConfiguration : NSObject <{{classPrefix}}Configuration>
/**
* Default api logger
*/
@property (nonatomic, strong) {{classPrefix}}Logger * logger;
/**
* Default api client
*/
@property (nonatomic) {{classPrefix}}ApiClient *apiClient;
/**
* Default base url
*/

View File

@ -1,39 +0,0 @@
#import "{{classPrefix}}JSONResponseSerializer.h"
@implementation {{classPrefix}}JSONResponseSerializer
///
/// When customize a response serializer,
/// the serializer must conform the protocol `AFURLResponseSerialization`
/// and implements the protocol method `responseObjectForResponse:error:`
///
/// @param response The response to be processed.
/// @param data The response data to be decoded.
/// @param error The error that occurred while attempting to decode the response data.
///
/// @return The object decoded from the specified response data.
///
- (id) responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error {
NSDictionary *responseJson = [super responseObjectForResponse:response data:data error:error];
// if response data is not a valid json, return string of data.
if ([self isParseError:*error]) {
*error = nil;
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
return responseString;
}
return responseJson;
}
-(BOOL)isParseError:(NSError *)error {
return [error.domain isEqualToString:NSCocoaErrorDomain] && error.code == 3840;
}
+ (instancetype)serializer {
return [self serializerWithReadingOptions:NSJSONReadingAllowFragments];
}
@end

View File

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

View File

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

View File

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

View File

@ -17,8 +17,7 @@
#pragma mark - Log Methods
- (void)debugLog:(NSString *)method
message:(NSString *)format, ... {
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
if (!self.isEnabled) {
return;
}

View File

@ -2,8 +2,8 @@
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="9525" systemVersion="15D21" minimumToolsVersion="Xcode 7.0">
{{#models}}{{#model}}<entity name="{{{classname}}}ManagedObject" representedClassName="{{{classname}}}ManagedObject" syncable="YES">
{{#isArrayModel}} <relationship name="entries" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="{{{arrayModelType}}}ManagedObject" syncable="YES"/>
{{/isArrayModel}}{{^isArrayModel}}{{#vars}}{{#complexType}} <relationship name="{{name}}" {{^required}}optional="YES"{{/required}} {{#isListContainer}}toMany="YES"{{/isListContainer}}{{^isListContainer}}maxCount="1"{{/isListContainer}} deletionRule="Cascade" destinationEntity="{{{complexType}}}ManagedObject" syncable="YES"/>{{/complexType}}{{^complexType}} <attribute name="{{name}}" {{^required}}optional="YES"{{/required}} attributeType="{{#isString}}String{{/isString}}{{#isInteger}}Integer 16{{/isInteger}}{{#isLong}}Double{{/isLong}}{{#isDouble}}Double{{/isDouble}}{{#isFloat}}Float{{/isFloat}}{{#isByteArray}}Binary{{/isByteArray}}{{#isBinary}}Binary{{/isBinary}}{{#isListContainer}}Transformable{{/isListContainer}}{{#isMapContainer}}Transformable{{/isMapContainer}}{{#isBoolean}}Boolean{{/isBoolean}}{{#isDate}}Date{{/isDate}}{{#isDateTime}}Date{{/isDateTime}}" syncable="YES"/>{{/complexType}}{{#vendorExtensions.x-is-unique}}
{{#isArrayModel}} <relationship name="entries" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="{{{arrayModelType}}}ManagedObject" syncable="YES"/>
{{/isArrayModel}}{{^isArrayModel}}{{#vars}}{{#complexType}} <relationship name="{{name}}" {{^required}}optional="YES"{{/required}} {{#isListContainer}}toMany="YES" ordered="YES"{{/isListContainer}}{{^isListContainer}}maxCount="1"{{/isListContainer}} deletionRule="Cascade" destinationEntity="{{{complexType}}}ManagedObject" syncable="YES"/>{{/complexType}}{{^complexType}} <attribute name="{{name}}" {{^required}}optional="YES"{{/required}} attributeType="{{#isString}}String{{/isString}}{{#isInteger}}Integer 16{{/isInteger}}{{#isLong}}Double{{/isLong}}{{#isDouble}}Double{{/isDouble}}{{#isFloat}}Float{{/isFloat}}{{#isByteArray}}Binary{{/isByteArray}}{{#isBinary}}Binary{{/isBinary}}{{#isListContainer}}Transformable{{/isListContainer}}{{#isMapContainer}}Transformable{{/isMapContainer}}{{#isBoolean}}Boolean{{/isBoolean}}{{#isDate}}Date{{/isDate}}{{#isDateTime}}Date{{/isDateTime}}" syncable="YES"/>{{/complexType}}{{#vendorExtensions.x-is-unique}}
<uniquenessConstraints><uniquenessConstraint><constraint value="{{name}}"/></uniquenessConstraint></uniquenessConstraints>{{/vendorExtensions.x-is-unique}}
{{/vars}}
{{/isArrayModel}}

View File

@ -14,7 +14,7 @@ NS_ASSUME_NONNULL_BEGIN
@interface {{classname}}ManagedObject : NSManagedObject
@property (nullable, nonatomic, retain) NSSet<{{{arrayModelType}}}ManagedObject*>* entries;
@property (nullable, nonatomic, retain) NSOrderedSet<{{{arrayModelType}}}ManagedObject*>* entries;
{{/isArrayModel}}{{^isArrayModel}}
@interface {{classname}}ManagedObject : {{#parent}}{{{parent}}}ManagedObject{{/parent}}{{^parent}}NSManagedObject{{/parent}}
@ -22,7 +22,7 @@ NS_ASSUME_NONNULL_BEGIN
{{#vars}}
{{#description}}/* {{{description}}} {{^required}}[optional]{{/required}}
*/{{/description}}
@property (nullable, nonatomic, retain) {{^complexType}}{{{ datatype }}}{{/complexType}}{{#complexType}}{{#isListContainer}}NSSet<{{{complexType}}}ManagedObject*>*{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}{{{ datatype }}}{{/isMapContainer}}{{^isMapContainer}}{{{complexType}}}ManagedObject*{{/isMapContainer}}{{/isListContainer}}{{/complexType}} {{name}};
@property (nullable, nonatomic, retain) {{^complexType}}{{{ datatype }}}{{/complexType}}{{#complexType}}{{#isListContainer}}NSOrderedSet<{{{complexType}}}ManagedObject*>*{{/isListContainer}}{{^isListContainer}}{{#isMapContainer}}{{{ datatype }}}{{/isMapContainer}}{{^isMapContainer}}{{{complexType}}}ManagedObject*{{/isMapContainer}}{{/isListContainer}}{{/complexType}} {{name}};
{{/vars}}
{{/isArrayModel}}
@end
@ -31,14 +31,14 @@ NS_ASSUME_NONNULL_BEGIN
{{#isArrayModel}}
- (void)addEntriesObject:({{arrayModelType}}ManagedObject *)value;
- (void)removeEntriesObject:({{arrayModelType}}ManagedObject *)value;
- (void)addEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values;
- (void)removeEntries:(NSSet<{{{arrayModelType}}}ManagedObject*> *)values;
- (void)addEntries:(NSOrderedSet<{{{arrayModelType}}}ManagedObject*> *)values;
- (void)removeEntries:(NSOrderedSet<{{{arrayModelType}}}ManagedObject*> *)values;
{{/isArrayModel}}
{{^isArrayModel}}
{{#vars}}{{#isListContainer}}{{#complexType}}- (void)add{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value;
- (void)remove{{vendorExtensions.x-uppercaseName}}Object:({{complexType}}ManagedObject *)value;
- (void)add{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values;
- (void)remove{{vendorExtensions.x-uppercaseName}}:(NSSet<{{{complexType}}}ManagedObject*> *)values;
- (void)add{{vendorExtensions.x-uppercaseName}}:(NSOrderedSet<{{{complexType}}}ManagedObject*> *)values;
- (void)remove{{vendorExtensions.x-uppercaseName}}:(NSOrderedSet<{{{complexType}}}ManagedObject*> *)values;
{{/complexType}}{{/isListContainer}}{{/vars}}
{{/isArrayModel}}
@end

View File

@ -34,8 +34,14 @@
if(!managedObject || !object) {
return;
}
{{#vars}}{{^complexType}} managedObject.{{name}} = [object.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(object.{{name}}) {
NSMutableSet * convertedObjs = [NSMutableSet set];
NSManagedObjectContext* context = managedObject.managedObjectContext;
{{#vars}}{{^complexType}} managedObject.{{name}} = [object.{{name}} copy];{{/complexType}}{{#complexType}}{{#isListContainer}} if(managedObject.{{name}}) {
for (id object in managedObject.{{name}}) {
[context deleteObject:object];
}
}
if(object.{{name}}) {
NSMutableOrderedSet * convertedObjs = [NSMutableOrderedSet orderedSet];
for (id innerObject in object.{{name}}) {
id convertedObj = [self.{{name}}Builder {{complexType}}ManagedObjectFrom{{complexType}}:innerObject context:managedObject.managedObjectContext];
[convertedObjs addObject:convertedObj];
@ -47,7 +53,7 @@
} else {
[self.{{name}}Builder update{{complexType}}ManagedObject:managedObject.{{name}} with{{complexType}}:object.{{name}}];
}{{/isMapContainer}}{{#isMapContainer}}managedObject.{{name}} = [object.{{name}} copy];{{/isMapContainer}}{{/isListContainer}}{{/complexType}}
{{/vars}}{{#isArrayModel}} NSMutableSet * convertedObjs = [NSMutableSet set];
{{/vars}}{{#isArrayModel}} NSMutableOrderedSet * convertedObjs = [NSMutableOrderedSet orderedSet];
for (id innerObject in object) {
id convertedObj = [self.entriesBuilder {{arrayModelType}}ManagedObjectFrom{{arrayModelType}}:innerObject context:managedObject.managedObjectContext];
[convertedObjs addObject:convertedObj];

View File

@ -2,6 +2,35 @@
@implementation {{classPrefix}}Object
/**
* Workaround for JSONModel multithreading issues
* https://github.com/icanzilb/JSONModel/issues/441
*/
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
static NSMutableSet *classNames;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classNames = [NSMutableSet new];
});
BOOL initSync;
@synchronized([self class])
{
NSString *className = NSStringFromClass([self class]);
initSync = ![classNames containsObject:className];
if(initSync)
{
[classNames addObject:className];
self = [super initWithDictionary:dict error:err];
}
}
if(!initSync)
{
self = [super initWithDictionary:dict error:err];
}
return self;
}
/**
* Gets the string presentation of the object.
* This method will be called when logging model object using `NSLog`.

View File

@ -5,11 +5,15 @@
@synthesize values = _values;
@synthesize format = _format;
- (id) initWithValuesAndFormat: (NSArray*) values
format: (NSString*) format {
_values = values;
_format = format;
- (id)initWithValuesAndFormat:(NSArray *)values
format:(NSString *)format {
self = [super init];
if (self) {
_values = values;
_format = format;
}
return self;
}

View File

@ -47,7 +47,7 @@ Import the following:
```objc
#import <{{podName}}/{{{classPrefix}}}ApiClient.h>
#import <{{podName}}/{{{classPrefix}}}Configuration.h>
#import <{{podName}}/{{{classPrefix}}}DefaultConfiguration.h>
// load models
{{#models}}{{#model}}#import <{{podName}}/{{{classname}}}.h>
{{/model}}{{/models}}// load API classes for accessing endpoints
@ -66,7 +66,7 @@ Please follow the [installation procedure](#installation--usage) and then run th
```objc
{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}}
{{#hasAuthMethods}}
{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig];
{{classPrefix}}DefaultConfiguration *apiConfig = [{{classPrefix}}DefaultConfiguration sharedConfig];
{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}})
[apiConfig setUsername:@"YOUR_USERNAME"];
[apiConfig setPassword:@"YOUR_PASSWORD"];

View File

@ -16,6 +16,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
@property (nonatomic, strong) NSArray *primitiveTypes;
@property (nonatomic, strong) NSArray *basicReturnTypes;
@property (nonatomic, strong) NSArray *dataReturnTypes;
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
@ -33,7 +34,9 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
_numberFormatter = formatter;
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
_basicReturnTypes = @[@"NSObject", @"id"];
_dataReturnTypes = @[@"NSData"];
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
options:NSRegularExpressionCaseInsensitive
error:nil];
@ -53,23 +56,36 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
#pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
// return nil if data is nil or className is nil
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
if (!data || !className) {
return nil;
}
// remove "*" from className, if ends with "*"
if ([className hasSuffix:@"*"]) {
className = [className substringToIndex:[className length] - 1];
}
if([self.dataReturnTypes containsObject:className]) {
return data;
}
id jsonData = nil;
if([data isKindOfClass:[NSData class]]) {
jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
} else {
jsonData = data;
}
if(!jsonData) {
jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
} else if([jsonData isKindOfClass:[NSNull class]]) {
return nil;
}
// pure object
if ([self.basicReturnTypes containsObject:className]) {
return data;
return jsonData;
}
// primitives
if ([self.primitiveTypes containsObject:className]) {
return [self deserializePrimitiveValue:data class:className error:error];
return [self deserializePrimitiveValue:jsonData class:className error:error];
}
NSTextCheckingResult *match = nil;
@ -78,37 +94,37 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// list of primitives
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// map
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
// model
Class ModelClass = NSClassFromString(className);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
}
if(error) {
*error = [self unknownResponseErrorWithExpectedType:className data:data];
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
}
return nil;
}
@ -172,7 +188,7 @@ NSInteger const {{classPrefix}}UnknownResponseObjectErrorCode = 143528;
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
if ([className isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
return [NSString stringWithFormat:@"%@",data];
}
else if ([className isEqualToString:@"NSDate"]) {
return [self deserializeDateValue:data error:error];

View File

@ -3,6 +3,8 @@
#import "{{classPrefix}}QueryParamCollection.h"
#import <ISO8601/ISO8601.h>
NSString * const k{{classPrefix}}ApplicationJSONType = @"application/json";
NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
static NSString * const k{{classPrefix}}CharactersGeneralDelimitersToEncode = @":#[]@";
static NSString * const k{{classPrefix}}CharactersSubDelimitersToEncode = @"!$&'()*+,;=";
@ -43,8 +45,6 @@ NSString * {{classPrefix}}PercentEscapedStringFromString(NSString *string) {
@implementation {{classPrefix}}Sanitizer
static NSString * kApplicationJSONType = @"application/json";
-(instancetype)init {
self = [super init];
if ( !self ) {
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
for (NSString *string in accepts) {
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
return kApplicationJSONType;
return k{{classPrefix}}ApplicationJSONType;
}
[lowerAccepts addObject:[string lowercaseString]];
}
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
*/
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
if (contentTypes.count == 0) {
return kApplicationJSONType;
return k{{classPrefix}}ApplicationJSONType;
}
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
for (NSString *string in contentTypes) {
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
return kApplicationJSONType;
return k{{classPrefix}}ApplicationJSONType;
}
[lowerContentTypes addObject:[string lowercaseString]];
}

View File

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

View File

@ -1,13 +1,14 @@
{{#operations}}
#import "{{classname}}.h"
#import "{{classPrefix}}QueryParamCollection.h"
#import "{{classPrefix}}ApiClient.h"
{{#imports}}#import "{{import}}.h"
{{/imports}}
{{newline}}
@interface {{classname}} ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -21,52 +22,31 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
{{classPrefix}}Configuration *config = [{{classPrefix}}Configuration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[{{classPrefix}}ApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[{{classPrefix}}ApiClient sharedClient]];
}
- (id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient {
-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static {{classname}} *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [{{classPrefix}}ApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -79,7 +59,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
///
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
///
-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler {
{{#allParams}}
@ -175,8 +155,7 @@ NSInteger k{{classname}}MissingParamErrorCode = 234513;
if(handler) {
handler({{#returnType}}({{{ returnType }}})data, {{/returnType}}error);
}
}
];
}];
}
{{/operation}}

View File

@ -11,7 +11,7 @@
extern NSString* k{{classname}}ErrorDomain;
extern NSInteger k{{classname}}MissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
{{#operations}}
{{#operation}}
@ -23,7 +23,7 @@ extern NSInteger k{{classname}}MissingParamErrorCode;
/// code:{{{code}}} message:"{{{message}}}"{{#hasMore}},{{/hasMore}}{{/responses}}
///
/// @return {{{returnType}}}
-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;

View File

@ -1,20 +1,18 @@
#import <Foundation/Foundation.h>
#import "{{classPrefix}}Object.h"
#import "{{classPrefix}}ApiClient.h"
@class {{classPrefix}}ApiClient;
{{>licenceInfo}}
@protocol {{classPrefix}}Api <NSObject>
@property(nonatomic, assign) {{classPrefix}}ApiClient *apiClient;
@property(readonly, nonatomic, strong) {{classPrefix}}ApiClient *apiClient;
-(id) initWithApiClient:({{classPrefix}}ApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:");
-(instancetype) initWithApiClient:({{classPrefix}}ApiClient *)apiClient;
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
-(NSString*) defaultHeaderForKey:(NSString*)key;
-(NSUInteger) requestQueueSize;
-(NSDictionary *)defaultHeaders;
@end

View File

@ -12,7 +12,7 @@ Method | HTTP request | Description
{{#operation}}
# **{{{operationId}}}**
```objc
-(NSNumber*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
-(NSURLSessionTask*) {{#vendorExtensions.x-objc-operationId}}{{vendorExtensions.x-objc-operationId}}{{/vendorExtensions.x-objc-operationId}}{{^vendorExtensions.x-objc-operationId}}{{nickname}}{{#hasParams}}With{{vendorExtensions.firstParamAltName}}{{/hasParams}}{{^hasParams}}WithCompletionHandler: {{/hasParams}}{{/vendorExtensions.x-objc-operationId}}{{#allParams}}{{#secondaryParam}}
{{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}{{/allParams}}
{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{#returnBaseType}}{{{returnType}}} output, {{/returnBaseType}}NSError* error)) handler;
```
@ -24,7 +24,7 @@ Method | HTTP request | Description
### Example
```objc
{{#hasAuthMethods}}
{{classPrefix}}Configuration *apiConfig = [{{classPrefix}}Configuration sharedConfig];
{{classPrefix}}DefaultConfiguration *apiConfig = [{{classPrefix}}DefaultConfiguration sharedConfig];
{{#authMethods}}{{#isBasic}}// Configure HTTP basic authorization (authentication scheme: {{{name}}})
[apiConfig setUsername:@"YOUR_USERNAME"];
[apiConfig setPassword:@"YOUR_PASSWORD"];

View File

@ -12,9 +12,9 @@ Pod::Spec.new do |s|
s.version = "{{podVersion}}"
{{#apiInfo}}{{#apis}}{{^hasMore}}
s.summary = "{{appName}}"
s.description = <<-DESC
{{{#appDescription}}} s.description = <<-DESC
{{{appDescription}}}
DESC
DESC{{{/appDescription}}}
{{/hasMore}}{{/apis}}{{/apiInfo}}
s.platform = :ios, '7.0'
s.requires_arc = true
@ -32,6 +32,6 @@ Pod::Spec.new do |s|
s.dependency 'AFNetworking', '~> 3'
s.dependency 'JSONModel', '~> 1.2'
s.dependency 'ISO8601', '~> 0.5'
s.dependency 'ISO8601', '~> 0.6'
end

File diff suppressed because it is too large Load Diff

View File

@ -1,2 +0,0 @@
https://github.com/Backendless/Tizen-Backendless-Geo-Service-Demo/blob/master/src/Backendless.cpp

View File

@ -1,131 +1,349 @@
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include "{{classname}}.h"
#include "NetClient.h"
#include "Helpers.h"
#include "Error.h"
#include "RequestInfo.h"
#include "{{prefix}}Helpers.h"
#include "{{prefix}}Error.h"
using namespace Tizen::Base;
namespace Swagger {
using namespace std;
using namespace Tizen::{{prefix}};
{{#operations}}
{{classname}}::{{classname}}() {
{{classname}}::{{classname}}()
{
}
{{classname}}::~{{classname}}() {
{{classname}}::~{{classname}}()
{
}
static gboolean __{{classname}}responseHandler(gpointer data)
{
RequestInfo *request = static_cast<RequestInfo*>(data);
g_thread_join(request->thread);
// invoke the callback function
bool retval = request->processor(*(request->p_chunk), *(request->code), request->errormsg, request->userData, request->handler);
delete request;
return FALSE;
}
static gpointer __{{classname}}threadFunc(gpointer data)
{
RequestInfo *request = static_cast<RequestInfo*>(data);
// handle the request
NetClient::easycurl(request->host, request->path, request->method, request->queryParams,
request->mBody, request->headerList, request->p_chunk, request->code, request->errormsg);
request->thread = g_thread_self();
g_idle_add(__{{classname}}responseHandler, static_cast<gpointer>(request));
return NULL;
}
{{#operation}}
void
{{nickname}}Processor(HttpResponse* pHttpResponse, void (* handler)(void*, {{prefix}}Error*)) {
int code = pHttpResponse->GetHttpStatusCode();
bool {{nickname}}Processor(MemoryStruct_s p_chunk, long code, char* errormsg, void* userData,
void(* voidHandler)())
{
{{#returnType}}void(* handler)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<string,string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* )
= reinterpret_cast<void(*)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<string,string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* )> (voidHandler);{{/returnType}}
{{^returnType}}void(* handler)(Error, void* ) = reinterpret_cast<void(*)(Error, void* )> (voidHandler);{{/returnType}}
JsonNode* pJson;
char * data = p_chunk.memory;
{{#returnType}}
printf("%s\n", data);
{{/returnType}}
if(code >= 200 && code < 300) {
{{#returnType}}ByteBuffer* pBuffer = pHttpResponse->ReadBodyN();
IJsonValue* pJson = JsonParser::ParseN(*pBuffer);
{{#returnType}}{{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<string,string>{{/isMapContainer}} out;{{/returnContainer}}
{{^returnContainer}}{{returnType}} out;{{/returnContainer}}{{/returnType}}
{{{returnType}}} out = {{{defaultResponse}}};
jsonToValue(out, pJson, L"{{returnType}}", L"{{returnBaseType}}");
if (code >= 200 && code < 300) {
Error error(code, string("No Error"));
if (pJson) {
if (pJson->GetType() == JSON_TYPE_OBJECT) {
JsonObject* pObject = static_cast< JsonObject* >(pJson);
pObject->RemoveAll(true);
}
else if (pJson->GetType() == JSON_TYPE_ARRAY) {
JsonArray* pArray = static_cast< JsonArray* >(pJson);
pArray->RemoveAll(true);
}
handler(out, null);
}
else {
{{prefix}}Error* error = new {{prefix}}Error(0, new String(L"No parsable response received"));
handler(null, error);
}
{{/returnType}}{{^returnType}}handler(null, null);{{/returnType}}
}
else {
{{prefix}}Error* error = new {{prefix}}Error(code, new String(pHttpResponse->GetStatusText()));
{{#returnType}}handler(null, error);{{/returnType}}
{{^returnType}}handler(error, null);{{/returnType}}
}
{{^returnType}}
handler(error, userData);
return true;
{{/returnType}}
{{#returnContainer}}
{{#isListContainer}}
pJson = json_from_string(data, NULL);
JsonArray * jsonarray = json_node_get_array (pJson);
guint length = json_array_get_length (jsonarray);
for(guint i = 0; i < length; i++){
JsonNode* myJson = json_array_get_element (jsonarray, i);
char * singlenodestr = json_to_string(myJson, false);
{{returnBaseType}} singlemodel;
singlemodel.fromJson(singlenodestr);
out.push_front(singlemodel);
g_free(static_cast<gpointer>(singlenodestr));
json_node_free(myJson);
}
json_array_unref (jsonarray);
json_node_free(pJson);
{{/isListContainer}}
{{/returnContainer}}
{{^returnContainer}}
{{#returnType}}
if (isprimitive("{{returnType}}")) {
pJson = json_from_string(data, NULL);
jsonToValue(&out, pJson, "{{returnType}}", "{{returnBaseType}}");
json_node_free(pJson);
if ("{{returnType}}" == "std::string") {
string* val = (std::string*)(&out);
if (val->empty() && p_chunk.size>4) {
*val = string(p_chunk.memory, p_chunk.size);
}
}
} else {
{{#responses}}{{^primitiveType}}
out.fromJson(data);
char *jsonStr = out.toJson();
printf("\n%s\n", jsonStr);
g_free(static_cast<gpointer>(jsonStr));
{{/primitiveType}}{{/responses}}
}
handler(out, error, userData);
return true;
//TODO: handle case where json parsing has an error
{{/returnType}}
{{/returnContainer}}
} else {
Error error;
if (errormsg != NULL) {
error = Error(code, string(errormsg));
} else if (p_chunk.memory != NULL) {
error = Error(code, string(p_chunk.memory));
} else {
error = Error(code, string("Unkown Error"));
}
{{#returnType}} handler(out, error, userData);
return false;
{{/returnType}}{{^returnType}}handler(error, userData);
return false;
{{/returnType}}
}
}
{{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}
{{classname}}::{{nickname}}WithCompletion({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}},{{/hasParams}} {{#returnType}}void (* success)({{returnType}}, {{prefix}}Error*){{/returnType}}{{^returnType}}void(*success)({{prefix}}Error*){{/returnType}}) {
client = new {{prefix}}ApiClient();
bool {{nickname}}Helper(char * accessToken,
{{#allParams}}{{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
{{#returnType}}void(* handler)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<string,string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* ){{/returnType}}
{{^returnType}}void(* handler)(Error, void* ) {{/returnType}}, void* userData, bool isAsync)
{
client->success(&{{nickname}}Processor, (void(*)(void*, {{prefix}}Error*))success);
HashMap* headerParams = new HashMap(SingleObjectDeleter);
headerParams->Construct();
//TODO: maybe delete headerList after its used to free up space?
struct curl_slist *headerList = NULL;
{{#headerParams}}{{#collectionFormat}}
int sz = {{paramName}}->GetCount();
for(int i = 0; i < sz; i++) {
String itemAt = stringify({{paramName}}->GetAt(i), "{{baseType}}");
headerParams->Add(new String("{{paramName}}"), new String(itemAt));
}
{{/collectionFormat}}{{^collectionFormat}}
headerParams->Add(new String("{{baseName}}"), {{paramName}});
{{/collectionFormat}}
{{/headerParams}}
{{#headerParams}}{{#collectionFormat}}
for ({{{dataType}}}
<{{baseType}}>::iterator queryIter = {{paramName}}.begin(); queryIter != {{paramName}}.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "{{baseType}}");
{{^required}}
if( itemAt.empty()){
continue;
}
{{/required}}
itemAt.insert(0, "{{paramName}}: ");
headerList = curl_slist_append(headerList, itemAt);
}
{{/collectionFormat}}{{^collectionFormat}}
//TODO - should use value of paramname instead. Also check for empty not-required headers
headerList = curl_slist_append(headerList, "{{baseName}}: {{paramName}}");
{{/collectionFormat}}
{{/headerParams}}
HashMap* queryParams = new HashMap(SingleObjectDeleter);
queryParams->Construct();
string accessHeader = "Authorization: Bearer ";
accessHeader.append(accessToken);
headerList = curl_slist_append(headerList, accessHeader.c_str());
{{#hasConsumes}}
{{#consumes}}
headerList = curl_slist_append(headerList, "Content-Type: {{mediaType}}");
{{/consumes}}
{{/hasConsumes}}
{{^hasConsumes}}
headerList = curl_slist_append(headerList, "Content-Type: application/json");
{{/hasConsumes}}
{{#queryParams}}{{#collectionFormat}}
int sz = {{paramName}}->GetCount();
for(int i = 0; i < sz; i++) {
String itemAt = stringify({{paramName}}->GetAt(i), "{{baseType}}");
queryParams->Add(new String("{{paramName}}"), new String(itemAt));
}
{{/collectionFormat}}{{^collectionFormat}}
queryParams->Add(new String("{{baseName}}"), {{paramName}});
{{/collectionFormat}}
{{/queryParams}}
map <string, string> queryParams;
string itemAtq;
{{#queryParams}}{{#collectionFormat}}
for ({{{dataType}}}
<{{baseType}}>::iterator queryIter = {{paramName}}.begin(); queryIter != {{paramName}}.end(); ++queryIter) {
string itemAt = stringify(&(*queryIter), "{{baseType}}");
{{^required}}
if( itemAt.empty()){
continue;
}
{{/required}}
queryParams.insert(pair<string, string>("{{paramName}}", itemAt));
}
{{/collectionFormat}}{{^collectionFormat}}
String* mBody = null;
itemAtq = stringify(&{{paramName}}, "{{dataType}}");
queryParams.insert(pair<string, string>("{{baseName}}", itemAtq));
{{^required}}
if( itemAtq.empty()==true){
queryParams.erase("{{baseName}}");
}
{{/required}}
{{/collectionFormat}}
{{/queryParams}}
{{#bodyParams}}
{{#isContainer}}
if({{paramName}} != null) {
mBody = new String("");
int sz = {{paramName}}->GetCount();
for(int i = 0; i < sz; i++) {
{{prefix}}Object * obj = ({{prefix}}Object*){{paramName}}->GetAt(i);
String json = obj->asJson();
if(i > 0)
mBody->Append(",");
mBody->Append(json);
}
mBody->Append("]");
headerParams->Add(new String("Content-Type"), new String("application/json"));
}
{{/isContainer}}
{{^isContainer}}
if({{paramName}} != null) {
mBody = new String({{paramName}}->asJson());
headerParams->Add(new String("Content-Type"), new String("application/json"));
}
{{/isContainer}}
{{/bodyParams}}
string mBody = "";
JsonNode* node;
JsonArray* json_array;
{{#bodyParams}}
{{#isContainer}}
//TODO: Map Container
{{#isListContainer}}
if (isprimitive("{{baseType}}")) {
node = converttoJson(&{{paramName}}, "{{baseType}}", "array");
} {{^isFloat}}{{^isInteger}}{{^isDate}}{{^isLong}}{{^isString}}{{^isDateTime}}{{^isDouble}}{{^isBoolean}}else {
node = json_node_alloc();
json_array = json_array_new();
for ({{{dataType}}}
<{{baseType}}>::iterator bodyIter = {{paramName}}.begin(); bodyIter != {{paramName}}.end(); ++bodyIter) {
{{baseType}} itemAt = (*bodyIter);
char *jsonStr = itemAt.toJson();
JsonNode *node_temp = json_from_string(jsonStr, NULL);
g_free(static_cast<gpointer>(jsonStr));
json_array_add_element(json_array, node_temp);
}
json_node_init_array(node, json_array);
json_array_unref(json_array);
}
{{/isBoolean}}{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isLong}}{{/isDate}}{{/isInteger}}{{/isFloat}}
{{/isListContainer}}
String url(L"{{{path}}}");
{{#pathParams}}
String s_{{paramName}}(L"{");
s_{{paramName}}.Append(L"{{{baseName}}}");
s_{{paramName}}.Append(L"}");
url.Replace(s_{{paramName}}, stringify({{{paramName}}}, L"{{dataType}}"));
{{/pathParams}}
client->execute({{classname}}::getBasePath(), url, "{{httpMethod}}", (IMap*)queryParams, mBody, (IMap*)headerParams, null, L"application/json");
{{#returnType}}return null;{{/returnType}}
{{#isMapContainer}}
//IF CODE IS HERE, SOMETHING IS SLIGHTLY WRONG!
if (isprimitive("{{baseType}}")) {
node = converttoJson(&{{paramName}}, "{{baseType}}", "array");
} {{^isInteger}}{{^isDate}}{{^isLong}}{{^isBoolean}}{{^isFloat}}{{^isString}}{{^isDateTime}}{{^isDouble}}else {
node = json_node_alloc();
json_array = json_array_new();
for ({{{dataType}}}
<{{baseType}}>::iterator bodyIter = {{paramName}}.begin(); bodyIter != {{paramName}}.end(); ++bodyIter) {
{{baseType}} itemAt = (*bodyIter);
char *jsonStr = itemAt.toJson();
JsonNode *node_temp = json_from_string(jsonStr, NULL);
g_free(static_cast<gpointer>(jsonStr));
json_array_add_element(json_array, node_temp);
}
json_node_init_array(node, json_array);
json_array_unref(json_array);
}
{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isFloat}}{{/isBoolean}}{{/isLong}}{{/isDate}}{{/isInteger}}
{{/isMapContainer}}
{{/isContainer}}
{{^isContainer}}
if (isprimitive("{{baseType}}")) {
node = converttoJson(&{{paramName}}, "{{baseType}}", "");
}
{{^isInteger}}{{^isDate}}{{^isLong}}{{^isBoolean}}{{^isFloat}}{{^isString}}{{^isDateTime}}{{^isDouble}}
char *jsonStr = {{paramName}}.toJson();
node = json_from_string(jsonStr, NULL);
g_free(static_cast<gpointer>(jsonStr));
{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isFloat}}{{/isBoolean}}{{/isLong}}{{/isDate}}{{/isInteger}}
{{/isContainer}}
char *jsonStr1 = json_to_string(node, false);
mBody.append(jsonStr1);
g_free(static_cast<gpointer>(jsonStr1));
{{/bodyParams}}
string url("{{{path}}}");
int pos;
{{#pathParams}}
string s_{{paramName}}("{");
s_{{paramName}}.append("{{{baseName}}}");
s_{{paramName}}.append("}");
pos = url.find(s_{{paramName}});
url.erase(pos, s_{{paramName}}.length());
url.insert(pos, stringify(&{{paramName}}, "{{dataType}}"));
{{/pathParams}}
//TODO: free memory of errormsg, memorystruct
MemoryStruct_s* p_chunk = new MemoryStruct_s();
long code;
char* errormsg = NULL;
string myhttpmethod("{{httpMethod}}");
if(strcmp("PUT", "{{httpMethod}}") == 0){
if(strcmp("", mBody.c_str()) == 0){
mBody.append("{}");
}
}
if(!isAsync){
NetClient::easycurl({{classname}}::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg);
bool retval = {{nickname}}Processor(*p_chunk, code, errormsg, userData,reinterpret_cast<void(*)()>(handler));
curl_slist_free_all(headerList);
if (p_chunk) {
if(p_chunk->memory) {
free(p_chunk->memory);
}
delete (p_chunk);
}
if (errormsg) {
free(errormsg);
}
return retval;
} else{
GThread *thread = NULL;
RequestInfo *requestInfo = NULL;
requestInfo = new(nothrow) RequestInfo ({{classname}}::getBasePath(), url, myhttpmethod, queryParams,
mBody, headerList, p_chunk, &code, errormsg, userData, reinterpret_cast<void(*)()>(handler), {{nickname}}Processor);;
if(requestInfo == NULL)
return false;
thread = g_thread_new(NULL, __{{classname}}threadFunc, static_cast<gpointer>(requestInfo));
return true;
}
}
bool {{classname}}::{{nickname}}Async(char * accessToken,
{{#allParams}}{{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
{{#returnType}}void(* handler)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<string,string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* ){{/returnType}}
{{^returnType}}void(* handler)(Error, void* ) {{/returnType}}, void* userData)
{
return {{nickname}}Helper(accessToken,
{{#allParams}}{{#isContainer}}{{paramName}}{{/isContainer}}{{^isContainer}}{{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
handler, userData, true);
}
bool {{classname}}::{{nickname}}Sync(char * accessToken,
{{#allParams}}{{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
{{#returnType}}void(* handler)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<string,string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* ){{/returnType}}
{{^returnType}}void(* handler)(Error, void* ) {{/returnType}}, void* userData)
{
return {{nickname}}Helper(accessToken,
{{#allParams}}{{#isContainer}}{{paramName}}{{/isContainer}}{{^isContainer}}{{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
handler, userData, false);
}
{{/operation}}
{{/operations}}
} /* namespace Swagger */

View File

@ -1,37 +1,58 @@
#ifndef {{classname}}_H_
#define {{classname}}_H_
#ifndef _{{classname}}_H_
#define _{{classname}}_H_
#include <FNet.h>
#include "{{prefix}}ApiClient.h"
#include "{{prefix}}Error.h"
{{#imports}}{{{import}}}
#include <string>
#include <cstring>
#include <list>
#include <glib.h>
{{#imports}}
{{{import}}}
{{/imports}}
#include "Error.h"
using namespace Tizen::Net::Http;
namespace Swagger {
namespace Tizen{
namespace {{prefix}} {
{{#operations}}
class {{classname}} {
public:
{{classname}}();
virtual ~{{classname}}();
{{classname}}();
virtual ~{{classname}}();
{{#operation}}
{{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}}
{{nickname}}WithCompletion({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}},{{/hasParams}} {{#returnType}}void (* handler)({{returnType}}, {{prefix}}Error*){{/returnType}}{{^returnType}}void(* handler)({{prefix}}Error*){{/returnType}});
{{/operation}}
static String getBasePath() {
return L"{{basePath}}";
}
{{#operation}}
/*! \brief {{{summary}}}. *Synchronous*
*
* {{{notes}}}{{#allParams}}
* \param {{paramName}} {{{description}}}{{#required}} *Required*{{/required}}{{/allParams}}
* \param handler The callback function to be invoked on completion. *Required*
* \param accessToken The Authorization token. *Required*
* \param userData The user data to be passed to the callback function.
*/
bool {{nickname}}Sync(char * accessToken,
{{#allParams}}{{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
{{#returnType}}void(* handler)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<std::string,std::string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* ){{/returnType}}
{{^returnType}}void(* handler)(Error, void* ) {{/returnType}}, void* userData);
private:
{{prefix}}ApiClient* client;
/*! \brief {{{summary}}}. *Asynchronous*
*
* {{{notes}}}{{#allParams}}
* \param {{paramName}} {{{description}}}{{#required}} *Required*{{/required}}{{/allParams}}
* \param handler The callback function to be invoked on completion. *Required*
* \param accessToken The Authorization token. *Required*
* \param userData The user data to be passed to the callback function.
*/
bool {{nickname}}Async(char * accessToken,
{{#allParams}}{{#isContainer}}{{{dataType}}}<{{baseType}}> {{paramName}}{{/isContainer}}{{^isContainer}}{{{dataType}}} {{paramName}}{{/isContainer}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#hasParams}}, {{/hasParams}}
{{#returnType}}void(* handler)({{#returnContainer}}{{#isListContainer}}{{returnType}}<{{returnBaseType}}>{{/isListContainer}}{{#isMapContainer}}{{returnType}}<std::string,std::string>{{/isMapContainer}}{{/returnContainer}}{{^returnContainer}}{{returnType}}{{/returnContainer}}, Error, void* ){{/returnType}}
{{^returnType}}void(* handler)(Error, void* ) {{/returnType}}, void* userData);
{{/operation}}
static std::string getBasePath()
{
return "{{basePath}}";
}
};
{{/operations}}
} /* namespace Swagger */
}
}
#endif /* {{classname}}_H_ */

View File

@ -1,124 +0,0 @@
#include "{{prefix}}ApiClient.h"
using namespace Tizen::Base;
using namespace Tizen::Base::Utility;
namespace Swagger {
{{prefix}}ApiClient::{{prefix}}ApiClient() {
enc = new Utf8Encoding();
}
void
{{prefix}}ApiClient::success(void (*success) (HttpResponse*, void (*cb)(void*, {{prefix}}Error*)), void (*cb)(void*, {{prefix}}Error*)) {
this->successFunction = success;
this->cb = cb;
}
{{prefix}}ApiClient::~{{prefix}}ApiClient() {
if(enc)
delete enc;
}
result
{{prefix}}ApiClient::execute(String host, String path, String method, IMap* queryParams, String* body, IMap* headerParams, IMap* formParams, String contentType) {
NetHttpMethod httpMethod;
if(method.Equals(L"GET", false)) {
httpMethod = NET_HTTP_METHOD_GET;
}
else if(method.Equals(L"PUT", false)) {
httpMethod = NET_HTTP_METHOD_PUT;
}
else if(method.Equals(L"POST", false)) {
httpMethod = NET_HTTP_METHOD_POST;
}
else if(method.Equals(L"DELETE", false)) {
httpMethod = NET_HTTP_METHOD_DELETE;
}
else if(method.Equals(L"OPTIONS", false)) {
httpMethod = NET_HTTP_METHOD_OPTIONS;
}
else if(method.Equals(L"HEAD", false)) {
httpMethod = NET_HTTP_METHOD_HEAD;
}
else if(method.Equals(L"TRACE", false)) {
httpMethod = NET_HTTP_METHOD_TRACE;
}
String uri = String(host);
uri.Append(path);
HttpSession* __pHttpSession = null;
HttpTransaction* pHttpTransaction = null;
HttpRequest* pHttpRequest = null;
if (__pHttpSession == null) {
__pHttpSession = new (std::nothrow) HttpSession();
__pHttpSession->Construct(NET_HTTP_SESSION_MODE_NORMAL, null, uri, null);
__pHttpSession->SetAutoRedirectionEnabled(true);
}
pHttpTransaction = __pHttpSession->OpenTransactionN();
pHttpTransaction->AddHttpTransactionListener(*this);
pHttpRequest = const_cast< HttpRequest* >(pHttpTransaction->GetRequest());
HttpHeader *pHeader = pHttpRequest->GetHeader();
if(contentType != null && !contentType.Equals(L"", true)) {
pHeader->AddField(L"Accept", contentType);
}
if(queryParams != null) {
IMapEnumerator* pMapEnum = queryParams->GetMapEnumeratorN();
String queryParam = L"";
while (pMapEnum->MoveNext() == E_SUCCESS) {
if(queryParam.GetLength() == 0)
queryParam.Append(L"?");
else
queryParam.Append(L"&");
String* pKey = static_cast< String* > (pMapEnum->GetKey());
String* pValue = static_cast< String* > (pMapEnum->GetValue());
String encoded;
UrlEncoder::Encode(*pKey, L"UTF-8", encoded);
queryParam.Append(encoded);
queryParam.Append("=");
UrlEncoder::Encode(*pValue, L"UTF-8", encoded);
queryParam.Append(encoded);
}
uri.Append(queryParam);
delete queryParams;
}
if(headerParams != null) {
IMapEnumerator* pMapEnum = headerParams->GetMapEnumeratorN();
while (pMapEnum->MoveNext() == E_SUCCESS) {
String* pKey = static_cast< String* > (pMapEnum->GetKey());
String* pValue = static_cast< String* > (pMapEnum->GetValue());
pHeader->AddField(*pKey, *pValue);
}
delete headerParams;
}
if(body != null) {
HttpStringEntity * pEntity = new HttpStringEntity();
String* cp = new String(*body);
result res = pEntity->Construct(*body, L"application/json", "utf-8", *enc);
res = pHttpRequest->SetEntity(*pEntity);
}
pHttpRequest->SetUri(uri);
pHttpRequest->SetMethod(httpMethod);
AppLog("%ls", uri.GetPointer());
return pHttpTransaction->Submit();
}
void
{{prefix}}ApiClient::OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& pHttpTransaction) {
HttpResponse* pHttpResponse = pHttpTransaction.GetResponse();
if(successFunction != null) {
successFunction(pHttpResponse, cb);
}
delete &httpSession;
delete &pHttpTransaction;
}
} /* namespace Swagger */

View File

@ -1,73 +0,0 @@
#include <FNet.h>
#include "{{prefix}}Helpers.h"
#include "{{prefix}}Error.h"
using namespace Tizen::Net::Http;
using namespace Tizen::Base;
using namespace Tizen::Base::Collection;
using namespace Tizen::Text;
#ifndef APICLIENT_H_
#define APICLIENT_H_
namespace Swagger {
class {{prefix}}ApiClient: public IHttpTransactionEventListener {
public:
{{prefix}}ApiClient();
virtual ~{{prefix}}ApiClient();
result
execute(String host, String path, String method, IMap* queryParams, String* body, IMap* headerParams, IMap* formParams, String contentType);
void success(void (*res) (HttpResponse*, void (*cb)(void*, {{prefix}}Error*)), void (*cb)(void*, {{prefix}}Error*));
virtual void
OnTransactionCompleted(HttpSession& httpSession, HttpTransaction& pHttpTransaction);
virtual void
OnAudioInAudioFocusChanged(void) {
AppLog("OnAudioInAudioFocusChanged");
}
virtual void
OnTransactionCertVerificationRequiredN(HttpSession& httpSession, HttpTransaction& httpTransaction,
Tizen::Base::String* pCert) {
AppLog("OnTransactionCertVerificationRequiredN");
httpTransaction.Resume();
delete pCert;
}
virtual void
OnTransactionReadyToWrite(HttpSession& httpSession, HttpTransaction& httpTransaction, int recommendedChunkSize) {
AppLog("OnTransactionReadyToWrite");
}
virtual void
OnTransactionReadyToRead(HttpSession& httpSession, HttpTransaction& httpTransaction, int availableBodyLen) {
AppLog("OnTransactionReadyToRead");
}
virtual void
OnTransactionAborted(HttpSession& httpSession, HttpTransaction& httpTransaction, result r) {
AppLog("OnTransactionAborted: %ls", GetErrorMessage(r));
delete &httpTransaction;
}
virtual void
OnTransactionHeaderCompleted(HttpSession& httpSession, HttpTransaction& httpTransaction, int headerLen, bool
bAuthRequired) {
AppLog("OnTransactionHeaderCompleted");
}
private:
void (*successFunction) (HttpResponse*, void (*success)(void*, {{prefix}}Error*));
void (*cb)(void*, {{prefix}}Error*);
Utf8Encoding* enc;
};
} /* namespace Swagger */
#endif /* APICLIENT_H_ */

View File

@ -0,0 +1,48 @@
# Documentation for {{#swagger}}{{#info}}{{title}} {{version}} Tizen SDK{{/info}}{{/swagger}}
## How do I get the doc files?
First generate source code by running `swagger-codegen`
Then run `doc/generateDocumentation.sh` from the output folder. It will generate all the doc files and put them in the `doc/SDK` directory.
To successfully generate documentation it needs `Doxygen` installed in the path.
*Note* - Before generating the documentation, put the logo of the project as the file `doc/logo.png` before running `doxygen`.
## How do I use this?
This is the structure of the doc folder:
```
.
├── logo.png \\Logo of the project
├── Doxyfile \\Doxygen config files
├── generateDocumentation.sh \\Script to run to generate documentation
├── README.md \\This file
├── SDK \\Documentation for all classes in Tizen Client SDK for Artik Cloud. See ./html/index.html
│   └── html
```
## *tl;dr* run this:
```
doc/generateDocumentation.sh
```
The above SDK folder will be generated. See the index.html inside the SDK folder.
## What's Doxygen?
Doxygen is the de facto standard tool for generating/extracting documentation from annotated/unannotated C++ sources, but it also supports other popular programming languages such as C, Objective-C, C#, PHP, Java, Python, IDL (Corba, Microsoft, and UNO/OpenOffice flavors), Fortran, VHDL, Tcl, and to some extent D.
Check out [Doxygen](https://www.doxygen.org/) for additional information about the Doxygen project.
## I Don't want to run Doxygen. What are the API files for accessing the REST endpoints?
{{#apiInfo}}{{#apis}}{{#operations}}
* [{{classname}}](../src/{{classname}}.cpp)
{{#operation}}
* *{{nickname}}Sync* / *{{nickname}}Async* - {{{summary}}}.
{{/operation}}
{{/operations}}{{/apis}}{{/apiInfo}}
## What are the Model files for the data structures/objects?
{{#models}}{{#model}}
* [{{classname}}](../src/{{classname}}.cpp) - {{{description}}}{{/model}}{{/models}}

View File

@ -1,55 +1,58 @@
#include "{{prefix}}Error.h"
#include "Error.h"
using namespace Tizen::Base;
using namespace Tizen::System;
using namespace std;
using namespace Tizen::{{prefix}};
namespace Swagger {
{{prefix}}Error::{{prefix}}Error() {
init();
Error::Error()
{
init();
}
{{prefix}}Error::{{prefix}}Error(int code, String* message) {
init();
this->setCode(code);
this->setMessage(message);
Error::Error(int code, string message)
{
init();
this->setCode(code);
this->setMessage(message);
}
{{prefix}}Error::~{{prefix}}Error() {
this->cleanup();
Error::~Error()
{
this->cleanup();
}
void
{{prefix}}Error::init() {
pCode = 0;
pMessage = null;
Error::init()
{
pCode = 0;
pMessage = "";
}
void
{{prefix}}Error::cleanup() {
if(pMessage != null) {
delete pMessage;
pMessage = null;
}
Error::cleanup()
{
}
int
{{prefix}}Error::getCode() {
return pCode;
Error::getCode()
{
return pCode;
}
void
{{prefix}}Error::setCode(int pCode) {
this->pCode = pCode;
Error::setCode(int pCode)
{
this->pCode = pCode;
}
String*
{{prefix}}Error::getMessage() {
return pMessage;
string
Error::getMessage()
{
return pMessage;
}
void
{{prefix}}Error::setMessage(String* pMessage) {
this->pMessage = pMessage;
Error::setMessage(string pMessage)
{
this->pMessage = pMessage;
}
} /* namespace Swagger */

View File

@ -1,35 +1,33 @@
#ifndef {{prefix}}Error_H_
#define {{prefix}}Error_H_
#ifndef _Error_H_
#define _Error_H_
#include <string>
#include <FBase.h>
namespace Tizen{
namespace {{prefix}} {
using namespace Tizen::Base;
namespace Swagger {
class {{prefix}}Error {
class Error {
public:
{{prefix}}Error();
{{prefix}}Error(int code, String* message);
virtual ~{{prefix}}Error();
Error();
Error(int code, std::string message);
virtual ~Error();
void init();
void init();
void cleanup();
void cleanup();
int getCode();
void setCode(int pCode);
std::string getMessage();
void setMessage(std::string pMessage);
int getCode();
void setCode(int pCode);
String* getMessage();
void setMessage(String* pMessage);
private:
int pCode;
String* pMessage;
int pCode;
std::string pMessage;
};
} /* namespace Swagger */
#endif /* {{prefix}}Error_H_ */
}
}
#endif /* Error_H_ */

View File

@ -0,0 +1,4 @@
#!/bin/bash
#Full Client SDK documentation
doxygen doc/Doxyfile

View File

@ -1,273 +1,368 @@
#include "{{prefix}}Helpers.h"
#include "{{prefix}}ModelFactory.h"
#include <iostream>
#include <sstream>
#include <cstdlib>
#include <map>
#include <list>
#include <cstring>
#include "Helpers.h"
#include "Object.h"
using namespace Tizen::Base;
using namespace Tizen::Base::Utility;
using namespace Tizen::Base::Collection;
using namespace Tizen::Web::Json;
using namespace Tizen::Locales;
using namespace Tizen::System;
using namespace std;
namespace Swagger {
JsonObject*
toJson(void* ptr, String type, String containerType) {
if(ptr == null)
return null;
if(containerType != null && !type.Equals(L"", false)) {
if(containerType.Equals(L"array", false)) {
if(type != null) {
IList* list = static_cast< IList* >(ptr);
JsonArray* array = new JsonArray();
int sz = list->GetCount();
for(int i = 0; i < sz; i++) {
void* itemAt = list->GetAt(i);
JsonObject* item = toJson(itemAt, type, null);
if(item != null)
array->Add(item);
}
return (JsonObject*)array;
}
return null;
}
}
else if(type.Equals(L"Boolean", false)) {
Boolean* v = static_cast< Boolean* >(ptr);
return (JsonObject*) new JsonBool(*v);
}
else if(type.Equals(L"String", false)) {
String* v = static_cast< String* >(ptr);
return (JsonObject*) new JsonString(*v);
}
else if(type.Equals(L"Integer", false)) {
Integer* v = static_cast< Integer* >(ptr);
return (JsonObject*) new JsonNumber(v->ToInt());
}
else if(type.Equals(L"Long", false)) {
Long* v = static_cast< Long* >(ptr);
return (JsonObject*) new JsonNumber(v->ToInt());
}
else if(type.Equals(L"Float", false)) {
Float* v = static_cast< Float* >(ptr);
return (JsonObject*) new JsonNumber(v->ToFloat());
}
else if(type.Equals(L"Double", false)) {
Double* v = static_cast< Double* >(ptr);
return (JsonObject*) new JsonNumber(v->ToDouble());
}
else if(type.Equals(L"DateTime", false)) {
DateTime* v = static_cast< DateTime* >(ptr);
DateTimeFormatter* pFormatter = DateTimeFormatter::CreateDateTimeFormatterN();
String date;
pFormatter->ApplyPattern(L"yyyy-MM-dd");
pFormatter->Format(*v, date);
using namespace Tizen::{{prefix}};
String time;
pFormatter->ApplyPattern(L"hh:mm:ss");
pFormatter->Format(*v, time);
String formattedString = date + "T" + time;
delete pFormatter;
return (JsonObject*)new JsonString(formattedString);
}
else if(type.StartsWith(L"{{prefix}}", 0)) {
{{prefix}}Object* obj = static_cast< {{prefix}}Object* >(ptr);
return obj->asJsonObject();
}
return null;
}
void helper_func(JsonObject *object, const gchar* member_name, JsonNode *member_node,gpointer user_data)
{
const gchar* member_string;
if (!JSON_NODE_HOLDS_VALUE(member_node)) {
if (JSON_NODE_HOLDS_OBJECT(member_node)) {
JsonNode* tempnode = json_node_alloc();
json_node_init_object(tempnode,json_node_get_object(member_node));
member_string = json_to_string(tempnode,false);
json_node_free(tempnode);
} else {
JsonNode* tempnode = json_node_alloc();
json_node_init_array(tempnode,json_node_get_array(member_node));
member_string = json_to_string(tempnode,false);
json_node_free(tempnode);
}
} else {
member_string = json_node_get_string(member_node);
}
map<string,string>* new_map = static_cast<map<string,string>*>(user_data);
(*new_map)[string(member_name)] = string(member_string);
}
void
toISO8601(String str, DateTime* dt) {
int idx, start;
int year, month, day, hour, minute, second;
char * json_to_string(JsonNode *node, gboolean pretty)
{
JsonGenerator *generator;
char *retval;
start = 0;
str.IndexOf(L"-", start, idx);
String yearString;
str.SubString(0, idx, yearString);
Integer::Parse(yearString, year);
g_return_val_if_fail(node != NULL, NULL);
start = idx+1;
str.IndexOf(L"-", start, idx);
String monthString;
str.SubString(start, idx - start, monthString);
Integer::Parse(monthString, month);
generator = json_generator_new();
json_generator_set_pretty(generator, pretty);
json_generator_set_root(generator, node);
start = idx+1;
str.IndexOf(L"T", start, idx);
String dayString;
str.SubString(start, idx - start, dayString);
Integer::Parse(dayString, day);
retval = json_generator_to_data(generator, NULL);
start = idx+1;
str.IndexOf(L":", start, idx);
if(idx > 0) {
String hourString;
str.SubString(start, idx - start, hourString);
Integer::Parse(hourString, hour);
}
g_object_unref(generator);
start = idx+1;
str.IndexOf(L":", start, idx);
if(idx > 0) {
String minuteString;
str.SubString(start, idx - start, minuteString);
Integer::Parse(minuteString, minute);
}
return retval;
}
start = idx+1;
str.IndexOf(L"+", start, idx);
if(idx > 0) {
String secondString;
str.SubString(start, idx - start, secondString);
Integer::Parse(secondString, second);
}
JsonNode *
json_from_string(const char *str, GError **mygerror)
{
JsonParser *parser;
JsonNode *retval;
dt->SetValue(year, month, day, hour, minute, second);
}
g_return_val_if_fail(str != NULL, NULL);
void
jsonToValue(void* target, IJsonValue* ptr, String type, String innerType) {
if(target == null || ptr == null) {
return;
}
if(type.StartsWith(L"Boolean", 0)) {
JsonBool* json = static_cast< JsonBool* >(ptr);
Boolean* val = static_cast< Boolean* > (target);
val->value = json->ToBool();
}
else if(type.StartsWith(L"String", 0)) {
JsonString* json = static_cast< JsonString* >(ptr);
String* val = static_cast< String* > (target);
val->Clear();
val->Append(json->GetPointer());
}
else if(type.StartsWith(L"Integer", 0)) {
JsonNumber* json = static_cast< JsonNumber* >(ptr);
Integer* val = static_cast< Integer* > (target);
*val = json->ToInt();
}
else if(type.StartsWith(L"Long", 0)) {
JsonNumber* json = static_cast< JsonNumber* >(ptr);
Long* val = static_cast< Long* > (target);
*val = json->ToLong();
}
else if(type.StartsWith(L"DateTime", 0)) {
JsonString* json = static_cast< JsonString* >(ptr);
String str;
str.Append(json->GetPointer());
mygerror = NULL;
parser = json_parser_new();
if (!json_parser_load_from_data(parser, str, -1, mygerror))
{
g_object_unref(parser);
return NULL;
}
DateTime* val = static_cast< DateTime* > (target);
toISO8601(str, val);
}
else if(type.StartsWith(L"{{prefix}}", 0)) {
{{prefix}}Object* obj = static_cast< {{prefix}}Object* > (target);
obj->fromJsonObject(ptr);
}
else if(type.StartsWith(L"IList", 0)) {
IList* obj = static_cast< IList* >(target);
JsonArray* pJsonArray = static_cast< JsonArray* >(ptr);
retval = json_node_copy(json_parser_get_root(parser));
IEnumeratorT< IJsonValue* >* pEnum = pJsonArray->GetEnumeratorN();
while (pEnum->MoveNext() == E_SUCCESS) {
IJsonValue* pJsonValue = null;
pEnum->GetCurrent(pJsonValue);
void* updatedTarget = null;
updatedTarget = create(innerType);
g_object_unref(parser);
if(updatedTarget != null) {
jsonToValue(updatedTarget, pJsonValue, innerType, L"");
obj->Add((Object*)updatedTarget);
}
}
delete pEnum;
}
}
return retval;
}
Integer*
jsonToInteger(IJsonValue* value) {
if(value == null)
return null;
switch(value->GetType()) {
case JSON_TYPE_STRING:
break;
case JSON_TYPE_NUMBER: {
JsonNumber* number = static_cast< JsonNumber* >(value);
int num = number->ToInt();
return new Integer(num);
}
case JSON_TYPE_OBJECT:
break;
case JSON_TYPE_ARRAY:
break;
case JSON_TYPE_BOOL:
break;
case JSON_TYPE_NULL:
break;
}
return null;
}
JsonNode*
converttoJson(void* ptr, string type, string containerType)
{
if (ptr == NULL)
return NULL;
if (strcmp(containerType.c_str(), "array") == 0) {
if (!type.empty()) {
JsonArray* json_array = json_array_new();
JsonNode* node = json_node_alloc();
JsonNode* node_temp;
Long*
jsonToLong(IJsonValue* value) {
if(value == null)
return null;
switch(value->GetType()) {
case JSON_TYPE_STRING:
break;
case JSON_TYPE_NUMBER: {
JsonNumber* number = static_cast< JsonNumber* >(value);
long int num = number->ToLong();
return new Long(num);
}
case JSON_TYPE_OBJECT:
break;
case JSON_TYPE_ARRAY:
break;
case JSON_TYPE_BOOL:
break;
case JSON_TYPE_NULL:
break;
}
return null;
}
String*
jsonToString(IJsonValue* value) {
if(value == null)
return null;
switch(value->GetType()) {
case JSON_TYPE_STRING: {
JsonString* string = static_cast< JsonString* >(value);
return new String(string->GetPointer());
}
case JSON_TYPE_NUMBER:
break;
case JSON_TYPE_OBJECT:
break;
case JSON_TYPE_ARRAY:
break;
case JSON_TYPE_BOOL:
break;
case JSON_TYPE_NULL:
break;
}
return null;
}
if (strcmp("bool", type.c_str()) == 0) {
list<bool>* new_list = static_cast<std::list<bool>*> (ptr);
for (list<bool>::iterator it = (*new_list).begin(); it != (*new_list).end(); it++) {
bool b = *it;
node_temp = converttoJson(&b, type, "");
json_array_add_element(json_array, node_temp);
}
} else if (strcmp("std::string", type.c_str()) == 0) {
list<string>* new_list = static_cast<std::list<string>*> (ptr);
for (list<string>::iterator it = (*new_list).begin(); it != (*new_list).end(); it++) {
string b = *it;
node_temp = converttoJson(&b, type, "");
json_array_add_element(json_array, node_temp);
}
} else if (strcmp("int", type.c_str()) == 0) {
list<int>* new_list = static_cast<std::list<int>*> (ptr);
for (list<int>::iterator it = (*new_list).begin(); it != (*new_list).end(); it++) {
int b = *it;
node_temp = converttoJson(&b, type, "");
json_array_add_element(json_array, node_temp);
}
} else if (strcmp("long long", type.c_str()) == 0) {
list<long long>* new_list = static_cast<std::list<long long>*> (ptr);
for (list<long long>::iterator it = (*new_list).begin(); it != (*new_list).end(); it++) {
long long b = *it;
node_temp = converttoJson(&b, type, "");
json_array_add_element(json_array, node_temp);
}
} else if (strcmp("float", type.c_str()) == 0) {
list<float>* new_list = static_cast<std::list<float>*> (ptr);
for (list<float>::iterator it = (*new_list).begin(); it != (*new_list).end(); it++) {
float b = *it;
node_temp = converttoJson(&b, type, "");
json_array_add_element(json_array, node_temp);
}
} else if (strcmp("double", type.c_str()) == 0) {
list<double>* new_list = static_cast<std::list<double>*> (ptr);
for (list<double>::iterator it = (*new_list).begin(); it != (*new_list).end(); it++) {
double b = *it;
node_temp = converttoJson(&b, type, "");
json_array_add_element(json_array, node_temp);
}
} else {
cout << "This case not handled in Sami Helpers. Make a loop and iterate there." << endl;
//Object* obj = static_cast<Object*> (ptr);
//GError *mygerror = (GError*) malloc(sizeof (GError));
//JsonNode *node = json_from_string(obj->toJson(), &mygerror);
//return node;
}
String
stringify(void* ptr, String type) {
if(type.StartsWith(L"String", 0)) {
String * str = static_cast< String* > (ptr);
return String(str->GetPointer());
}
if(type.StartsWith(L"Integer", 0)) {
Integer* pInt = static_cast< Integer* > (ptr);
return pInt->ToString();
}
if(type.StartsWith(L"Long", 0)) {
Long* pLong = static_cast< Long* > (ptr);
return pLong->ToString();
}
return L"";
}
} /* namespace Swagger */
json_node_init_array(node, json_array);
json_array_unref(json_array);
return node;
}
return NULL;
} else if (strcmp("std::string", type.c_str()) == 0) {
JsonNode* node = json_node_alloc();
string* v = static_cast<string*> (ptr);
//const_gchar* b = v;
json_node_init(node, JSON_NODE_VALUE);
json_node_set_string(node, v->c_str());
return node;
} else if (strcmp("int", type.c_str()) == 0) {
JsonNode* node = json_node_alloc();
int* v = static_cast<int*> (ptr);
gint b = *v;
json_node_init(node, JSON_NODE_VALUE);
json_node_set_int(node, b);
return node;
} else if (strcmp("float", type.c_str()) == 0) {
JsonNode* node = json_node_alloc();
float* v = static_cast<float*> (ptr);
gdouble b = (double) *v;
json_node_init(node, JSON_NODE_VALUE);
json_node_set_double(node, b);
return node;
} else if (strcmp("long long", type.c_str()) == 0) {
JsonNode* node = json_node_alloc();
long long* v = static_cast<long long*> (ptr);
gint64 b = (long long) *v;
json_node_init(node, JSON_NODE_VALUE);
json_node_set_int(node, b);
return node;
} else if (strcmp("double", type.c_str()) == 0) {
JsonNode* node = json_node_alloc();
double* v = static_cast<double*> (ptr);
gdouble b = *v;
json_node_init(node, JSON_NODE_VALUE);
json_node_set_double(node, b);
return node;
} else if (strcmp("bool", type.c_str()) == 0) {
JsonNode* node = json_node_alloc();
bool* v = static_cast<bool*> (ptr);
gboolean b = *v;
json_node_init(node, JSON_NODE_VALUE);
json_node_set_boolean(node, b);
return node;
}
else if (!isprimitive(type)) {
//Object* obj = static_cast<Object*> (ptr);
//GError *mygerror = (GError*) malloc(sizeof (GError));
//JsonNode *node = json_from_string(obj->toJson(), &mygerror);
//return node;
}
return NULL;
}
// DateTime Class to be seen
// void
// toISO8601(String str, DateTime* dt) {
// int idx, start;
// int year, month, day, hour, minute, second;
// start = 0;
// str.IndexOf("-", start, idx);
// String yearString;
// str.SubString(0, idx, yearString);
// Integer::Parse(yearString, year);
// start = idx+1;
// str.IndexOf("-", start, idx);
// String monthString;
// str.SubString(start, idx - start, monthString);
// Integer::Parse(monthString, month);
// start = idx+1;
// str.IndexOf("T", start, idx);
// String dayString;
// str.SubString(start, idx - start, dayString);
// Integer::Parse(dayString, day);
// start = idx+1;
// str.IndexOf(":", start, idx);
// if(idx > 0) {
// String hourString;
// str.SubString(start, idx - start, hourString);
// Integer::Parse(hourString, hour);
// }
// start = idx+1;
// str.IndexOf(":", start, idx);
// if(idx > 0) {
// String minuteString;
// str.SubString(start, idx - start, minuteString);
// Integer::Parse(minuteString, minute);
// }
// start = idx+1;
// str.IndexOf("+", start, idx);
// if(idx > 0) {
// String secondString;
// str.SubString(start, idx - start, secondString);
// Integer::Parse(secondString, second);
// }
// dt->SetValue(year, month, day, hour, minute, second);
// }
void
jsonToValue(void* target, JsonNode* node, string type, string innerType)
{
if (target == NULL || node == NULL || !JSON_NODE_HOLDS_VALUE(node)) {
return;
} else if (strcmp("bool", type.c_str()) == 0) {
bool* val = static_cast<bool*> (target);
*val = json_node_get_boolean(node);
} else if (strcmp("int", type.c_str()) == 0) {
int* val = static_cast<int*> (target);
*val = json_node_get_int(node);
} else if (strcmp("float", type.c_str()) == 0) {
float* val = static_cast<float*> (target);
*val = (float)(json_node_get_double(node));
} else if (strcmp("long long", type.c_str()) == 0) {
long long* val = static_cast<long long*> (target);
*val = (long long)(json_node_get_int(node));
} else if (strcmp("double", type.c_str()) == 0) {
double* val = static_cast<double*> (target);
*val = json_node_get_double(node);
} else if (strcmp("std::string", type.c_str()) == 0) {
string* val = static_cast<string*> (target);
const gchar *temp = json_node_get_string(node);
if (node == NULL) {
}
*val = string(temp);
}
//Implement
// else if(type.StartsWith("DateTime", 0)) {
// JsonString* json = static_cast< JsonString* >(ptr);
// String str;
// str.Append(json->GetPointer());
// DateTime* val = static_cast< DateTime* > (target);
// toISO8601(str, val);
// }
else if (!isprimitive(type)) {
cout<<"SOMETHING IS WRONG"<<endl;
}
//Implement
// else if(type.StartsWith("IList", 0)) {
// IList* obj = static_cast< IList* >(target);
// JsonArray* pJsonArray = static_cast< JsonArray* >(ptr);
// IEnumeratorT< IJsonValue* >* pEnum = pJsonArray->GetEnumeratorN();
// while (pEnum->MoveNext() == E_SUCCESS) {
// IJsonValue* pJsonValue = NULL;
// pEnum->GetCurrent(pJsonValue);
// void* updatedTarget = NULL;
// updatedTarget = create(innerType);
// if(updatedTarget != NULL) {
// jsonToValue(updatedTarget, pJsonValue, innerType, "");
// obj->Add((Object*)updatedTarget);
// }
// }
// delete pEnum;
// }
}
string
stringify(void* ptr, string type)
{
if(ptr == NULL){
string retval = "";
return retval;
} else if (strcmp("std::string", type.c_str()) == 0) {
string * str = static_cast<string*> (ptr);
string retval = string(*str);
return retval;
} else if (strcmp("int", type.c_str()) == 0) {
int* pInt = static_cast<int*> (ptr);
stringstream ss;
ss << *pInt;
string retval = ss.str();
return retval;
} else if (strcmp("long long", type.c_str()) == 0) {
long long* pLong = static_cast<long long*> (ptr);
stringstream ss;
ss << *pLong;
string retval = ss.str();
return retval;
} else if (strcmp("bool", type.c_str()) == 0) {
bool* pBool = static_cast<bool*> (ptr);
string retval;
if (*pBool == true) {
retval = "true";
} else {
retval = "false";
}
return retval;
} else if (strcmp("double", type.c_str()) == 0) {
double* pDouble = static_cast<double*> (ptr);
stringstream ss;
ss << *pDouble;
string retval = ss.str();
return retval;
} else if (strcmp("float", type.c_str()) == 0) {
float* pFloat = static_cast<float*> (ptr);
stringstream ss;
ss << *pFloat;
string retval = ss.str();
return retval;
}
return "";
}
bool isprimitive(string type){
if(strcmp("std::string", type.c_str()) == 0||
strcmp("int", type.c_str()) == 0||
strcmp("long long", type.c_str()) == 0||
strcmp("double", type.c_str()) == 0||
strcmp("float", type.c_str()) == 0||
strcmp("bool", type.c_str()) == 0||
strcmp("std::map", type.c_str()) == 0||
strcmp("std::list", type.c_str()) == 0) {
return true;
}
return false;
}

View File

@ -1,45 +1,30 @@
#ifndef HELPERS_H_
#define HELPERS_H_
#ifndef _HELPERS_H_
#define _HELPERS_H_
#include <FApp.h>
#include <FBase.h>
#include <FSystem.h>
#include <FWebJson.h>
#include <FLocales.h>
#include "{{prefix}}Helpers.h"
#include "{{prefix}}Object.h"
#include <string>
#include <glib-object.h>
#include <json-glib/json-glib.h>
using Tizen::Base::String;
using Tizen::Base::DateTime;
using namespace Tizen::Web::Json;
using namespace Tizen::Base::Collection;
using namespace std;
using Tizen::Base::Long;
using Tizen::Base::DateTime;
using Tizen::Base::String;
using Tizen::Base::Integer;
JsonNode *
json_from_string (const char *str,
GError **mygerror);
namespace Swagger {
JsonObject*
toJson(void* v, String type, String containerType);
char *
json_to_string (JsonNode *node,
gboolean pretty);
JsonNode*
converttoJson(void* v, string type, string containerType);
void
jsonToValue(void* target, IJsonValue* ptr, String type, String innerType);
jsonToValue(void* target, JsonNode* ptr, string type, string innerType);
Integer*
jsonToInteger(IJsonValue* value);
void helper_func(JsonObject *object, const gchar* member_name, JsonNode *member_node,gpointer user_data);
Long*
jsonToLong(IJsonValue* value);
string
stringify(void* ptr, string type);
String*
jsonToString(IJsonValue* value);
DateTime*
jsonToDateTime(IJsonValue* value);
String
stringify(void* ptr, String type);
} /* namespace Swagger */
bool isprimitive(string type);
#endif /* HELPERS_H_ */

View File

@ -1,158 +1,188 @@
#include <map>
#include <cstdlib>
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include "Helpers.h"
{{#models}}{{#model}}
#include "{{classname}}.h"
#include <FLocales.h>
using namespace Tizen::Base;
using namespace Tizen::System;
using namespace Tizen::Base::Utility;
using namespace Tizen::Base::Collection;
using namespace Tizen::Web::Json;
using namespace Tizen::Locales;
using namespace std;
using namespace Tizen::{{prefix}};
namespace Swagger {
{{classname}}::{{classname}}() {
init();
}
{{classname}}::~{{classname}}() {
this->cleanup();
}
void
{{classname}}::init() {
{{#vars}}{{name}} = null;
{{/vars}}
}
void
{{classname}}::cleanup() {
{{#vars}}if({{name}} != null) {
{{#isContainer}}{{name}}->RemoveAll(true);{{/isContainer}}
delete {{name}};
{{name}} = null;
}
{{/vars}}
}
{{classname}}*
{{classname}}::fromJson(String* json) {
this->cleanup();
String str(json->GetPointer());
int length = str.GetLength();
ByteBuffer buffer;
buffer.Construct(length);
for (int i = 0; i < length; ++i) {
byte b = str[i];
buffer.SetByte(b);
}
IJsonValue* pJson = JsonParser::ParseN(buffer);
fromJsonObject(pJson);
if (pJson->GetType() == JSON_TYPE_OBJECT) {
JsonObject* pObject = static_cast< JsonObject* >(pJson);
pObject->RemoveAll(true);
}
else if (pJson->GetType() == JSON_TYPE_ARRAY) {
JsonArray* pArray = static_cast< JsonArray* >(pJson);
pArray->RemoveAll(true);
}
delete pJson;
return this;
}
void
{{classname}}::fromJsonObject(IJsonValue* pJson) {
JsonObject* pJsonObject = static_cast< JsonObject* >(pJson);
if(pJsonObject != null) {
{{#vars}}JsonString* {{name}}Key = new JsonString(L"{{baseName}}");
IJsonValue* {{name}}Val = null;
pJsonObject->GetValue({{name}}Key, {{name}}Val);
if({{name}}Val != null) {
{{#isContainer}}{{name}} = {{defaultValue}};{{/isContainer}}
{{#isNotContainer}}{{name}} = {{defaultValue}};{{/isNotContainer}}
jsonToValue({{name}}, {{name}}Val, L"{{baseType}}", L"{{complexType}}");
}
delete {{name}}Key;
{{/vars}}
}
}
{{classname}}::{{classname}}(String* json) {
init();
String str(json->GetPointer());
int length = str.GetLength();
ByteBuffer buffer;
buffer.Construct(length);
for (int i = 0; i < length; ++i) {
byte b = str[i];
buffer.SetByte(b);
}
IJsonValue* pJson = JsonParser::ParseN(buffer);
fromJsonObject(pJson);
if (pJson->GetType() == JSON_TYPE_OBJECT) {
JsonObject* pObject = static_cast< JsonObject* >(pJson);
pObject->RemoveAll(true);
}
else if (pJson->GetType() == JSON_TYPE_ARRAY) {
JsonArray* pArray = static_cast< JsonArray* >(pJson);
pArray->RemoveAll(true);
}
delete pJson;
}
String
{{classname}}::asJson ()
{{classname}}::{{classname}}()
{
JsonObject* pJsonObject = asJsonObject();
char *pComposeBuf = new char[256];
JsonWriter::Compose(pJsonObject, pComposeBuf, 256);
String s = String(pComposeBuf);
delete pComposeBuf;
pJsonObject->RemoveAll(true);
delete pJsonObject;
return s;
//__init();
}
JsonObject*
{{classname}}::asJsonObject() {
JsonObject *pJsonObject = new JsonObject();
pJsonObject->Construct();
{{classname}}::~{{classname}}()
{
//__cleanup();
}
{{#vars}}
JsonString *{{name}}Key = new JsonString(L"{{baseName}}");
pJsonObject->Add({{name}}Key, toJson({{getter}}(), "{{complexType}}", "{{containerType}}"));
void
{{classname}}::__init()
{
//{{#vars}}
//{{#isContainer}}{{defaultValue}}{{baseType}}> {{name}};{{/isContainer}}
//{{#isNotContainer}}{{name}} = {{defaultValue}};{{/isNotContainer}}
//{{/vars}}
}
{{/vars}}
return pJsonObject;
void
{{classname}}::__cleanup()
{
//{{#vars}}if({{name}} != NULL) {
//{{#isContainer}}{{name}}.RemoveAll(true);{{/isContainer}}
//delete {{name}};
//{{name}} = NULL;
//}
//{{/vars}}
}
void
{{classname}}::fromJson(char* jsonStr)
{
JsonObject *pJsonObject = json_node_get_object(json_from_string(jsonStr,NULL));
JsonNode *node;
{{#vars}}
const gchar *{{name}}Key = "{{baseName}}";
node = json_object_get_member(pJsonObject, {{name}}Key);
if (node !=NULL) {
{{#isContainer}}{{#isListContainer}}
{
JsonArray* arr = json_node_get_array(node);
JsonNode* temp_json;
list<{{#items}}{{datatype}}{{/items}}> new_list;
{{#items}}{{datatype}}{{/items}} inst;
for (guint i=0;i<json_array_get_length(arr);i++) {
temp_json = json_array_get_element(arr,i);
if (isprimitive("{{#items}}{{datatype}}{{/items}}")) {
jsonToValue(&inst, temp_json, "{{#items}}{{datatype}}{{/items}}", "");
} else {
{{#items}}{{^isInteger}}{{^isDate}}{{^isLong}}{{^isBoolean}}{{^isString}}{{^isDateTime}}{{^isDouble}}{{^isFloat}}
inst.fromJson(json_to_string(temp_json, false));
{{/isFloat}}{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isBoolean}}{{/isLong}}{{/isDate}}{{/isInteger}}{{/items}}
}
new_list.push_back(inst);
}
{{name}} = new_list;
}
{{/isListContainer}}{{#isMapContainer}}
{
JsonObject* json_obj = json_node_get_object(node);
map<string,string> new_map;
json_object_foreach_member(json_obj,helper_func,&new_map);
{{name}} = new_map;
}
{{/isMapContainer}}{{/isContainer}}
{{^isContainer}}
if (isprimitive("{{baseType}}")) {
jsonToValue(&{{name}}, node, "{{baseType}}", "{{complexType}}");
} else {
{{^isInteger}}{{^isDate}}{{^isLong}}{{^isBoolean}}{{^isString}}{{^isDateTime}}{{^isDouble}}{{^isFloat}}
{{baseType}}* obj = static_cast<{{baseType}}*> (&{{name}});
obj->fromJson(json_to_string(node, false));
{{/isFloat}}{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isBoolean}}{{/isLong}}{{/isDate}}{{/isInteger}}
}
{{/isContainer}}
}
{{/vars}}
}
{{classname}}::{{classname}}(char* json)
{
this->fromJson(json);
}
char*
{{classname}}::toJson()
{
JsonObject *pJsonObject = json_object_new();
JsonNode *node;
{{#vars}}
{{#isContainer}}
{{#isListContainer}}
if (isprimitive("{{#items}}{{datatype}}{{/items}}")) {
list<{{#items}}{{datatype}}{{/items}}> new_list = static_cast<list <{{#items}}{{datatype}}{{/items}}> > ({{getter}}());
node = converttoJson(&new_list, "{{#items}}{{datatype}}{{/items}}", "{{containerType}}");
} else {
node = json_node_alloc();
list<{{#items}}{{datatype}}{{/items}}> new_list = static_cast<list <{{#items}}{{datatype}}{{/items}}> > ({{getter}}());
JsonArray* json_array = json_array_new();
GError *mygerror;
{{#items}}{{^isInteger}}{{^isDate}}{{^isLong}}{{^isBoolean}}{{^isString}}{{^isDateTime}}{{^isDouble}}{{^isFloat}}
for (list<{{datatype}}>::iterator it = new_list.begin(); it != new_list.end(); it++) {
mygerror = NULL;
{{datatype}} obj = *it;
JsonNode *node_temp = json_from_string(obj.toJson(), &mygerror);
json_array_add_element(json_array, node_temp);
g_clear_error(&mygerror);
}
json_node_init_array(node, json_array);
json_array_unref(json_array);
{{/isFloat}}{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isBoolean}}{{/isLong}}{{/isDate}}{{/isInteger}}{{/items}}
}
{{/isListContainer}}
{{#isMapContainer}}{
JsonObject* json_obj;
map<string, string> new_list = static_cast<map <string, string> > ({{getter}}());
json_obj = json_object_new();
for (map<string, string>::iterator it = new_list.begin(); it != new_list.end(); it++) {
string obj = (*it).first;
string obj2 = (*it).second;
JsonNode* tempnode = json_from_string(obj2.c_str(),NULL);
json_object_set_member(json_obj, obj.c_str(), tempnode);
}
node = json_node_alloc();
json_node_init_object(node, json_obj);
json_object_unref(json_obj);
}
{{/isMapContainer}}
{{/isContainer}}
{{^isContainer}}
if (isprimitive("{{baseType}}")) {
{{baseType}} obj = {{getter}}();
node = converttoJson(&obj, "{{baseType}}", "");
}
else {
{{^isInteger}}{{^isDate}}{{^isLong}}{{^isBoolean}}{{^isString}}{{^isDateTime}}{{^isDouble}}{{^isFloat}}
{{baseType}} obj = static_cast<{{baseType}}> ({{getter}}());
GError *mygerror;
mygerror = NULL;
node = json_from_string(obj.toJson(), &mygerror);
{{/isFloat}}{{/isDouble}}{{/isDateTime}}{{/isString}}{{/isBoolean}}{{/isLong}}{{/isDate}}{{/isInteger}}
}
{{/isContainer}}
const gchar *{{name}}Key = "{{baseName}}";
json_object_set_member(pJsonObject, {{name}}Key, node);
{{/vars}}
node = json_node_alloc();
json_node_init(node, JSON_NODE_OBJECT);
json_node_take_object(node, pJsonObject);
char * ret = json_to_string(node, false);
json_node_free(node);
return ret;
}
{{#vars}}
{{datatype}}
{{classname}}::{{getter}}() {
return {{name}};
{{datatype}}{{#isContainer}}{{#isMapContainer}}<string, string>{{/isMapContainer}}{{^isMapContainer}}<{{#items}}{{datatype}}{{/items}}>{{/isMapContainer}}{{/isContainer}}
{{classname}}::{{getter}}()
{
return {{name}};
}
void
{{classname}}::{{setter}}({{datatype}} {{name}}) {
this->{{name}} = {{name}};
{{classname}}::{{setter}}({{datatype}} {{#isContainer}}{{#isMapContainer}}<string, string>{{/isMapContainer}}{{^isMapContainer}}<{{#items}}{{datatype}}{{/items}}>{{/isMapContainer}}{{/isContainer}} {{name}})
{
this->{{name}} = {{name}};
}
{{/vars}}
} /* namespace Swagger */
{{/model}}
{{/models}}

View File

@ -1,58 +1,67 @@
{{#models}}{{#model}}/*
* {{classname}}.h
*
*
* {{description}}
*/
#ifndef {{classname}}_H_
#define {{classname}}_H_
#include <FApp.h>
#include <FBase.h>
#include <FSystem.h>
#include <FWebJson.h>
#include "{{prefix}}Helpers.h"
#include "{{prefix}}Object.h"
using namespace Tizen::Web::Json;
#ifndef _{{classname}}_H_
#define _{{classname}}_H_
{{/model}}{{/models}}
{{#imports}}{{{import}}}
#include <string>
{{#imports}}
{{{import}}}
{{/imports}}
#include "Object.h"
namespace Tizen {
namespace {{prefix}} {
{{#models}}{{#model}}
namespace Swagger {
class {{classname}}: public {{prefix}}Object {
/*! \brief {{{description}}}
*
*/
class {{classname}} : public Object {
public:
{{classname}}();
{{classname}}(String* json);
virtual ~{{classname}}();
/*! \brief Constructor.
*/
{{classname}}();
{{classname}}(char* str);
void init();
/*! \brief Destructor.
*/
virtual ~{{classname}}();
void cleanup();
/*! \brief Retrieve a string JSON representation of this class.
*/
char* toJson();
String asJson ();
/*! \brief Fills in members of this class from JSON string representing it.
*/
void fromJson(char* jsonStr);
JsonObject* asJsonObject();
{{#vars}}
/*! \brief Get {{{description}}}
*/
{{datatype}}{{#isContainer}}{{#isMapContainer}}<std::string, std::string>{{/isMapContainer}}{{^isMapContainer}}<{{#items}}{{datatype}}{{/items}}>{{/isMapContainer}}{{/isContainer}} {{getter}}();
void fromJsonObject(IJsonValue* json);
{{classname}}* fromJson(String* obj);
{{#vars}}
{{datatype}} {{getter}}();
void {{setter}}({{datatype}} {{name}});
{{/vars}}
/*! \brief Set {{{description}}}
*/
void {{setter}}({{datatype}} {{#isContainer}}{{#isMapContainer}}<std::string, std::string>{{/isMapContainer}}{{^isMapContainer}}<{{#items}}{{datatype}}{{/items}}>{{/isMapContainer}}{{/isContainer}} {{name}});
{{/vars}}
private:
{{#vars}}{{datatype}} {{name}};
{{/vars}}
{{#vars}}
{{datatype}} {{#isContainer}}{{#isMapContainer}}<std::string, std::string>{{/isMapContainer}}{{^isMapContainer}}<{{#items}}{{datatype}}{{/items}}>{{/isMapContainer}}{{/isContainer}}{{name}};
{{/vars}}
void __init();
void __cleanup();
};
} /* namespace Swagger */
#endif /* {{classname}}_H_ */
{{/model}}
{{/models}}
}
}
#endif /* _{{classname}}_H_ */

View File

@ -1,31 +0,0 @@
#ifndef ModelFactory_H_
#define ModelFactory_H_
#include "{{prefix}}Object.h"
{{#models}}{{#model}}
#include "{{classname}}.h"{{/model}}{{/models}}
namespace Swagger {
void*
create(String type) {
{{#models}}{{#model}}if(type.Equals(L"{{classname}}", true)) {
return new {{classname}}();
}
{{/model}}{{/models}}
if(type.Equals(L"String", true)) {
return new String();
}
if(type.Equals(L"Integer", true)) {
return new Integer();
}
if(type.Equals(L"Long", true)) {
return new Long();
}
if(type.Equals(L"DateTime", true)) {
return new DateTime();
}
return null;
}
} /* namespace Swagger */
#endif /* ModelFactory_H_ */

View File

@ -0,0 +1,359 @@
#include "NetClient.h"
using namespace std;
NetClient::NetClient() {
}
/*
void
NetClient::success(void (*success) (HttpResponse*, void (*cb)(void*, Error*)), void (*cb)(void*, Error*)) {
this->successFunction = success;
this->cb = cb;
}
*/
NetClient::~NetClient() {
}
size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
size_t realsize = size * nmemb;
MemoryStruct_s *mem = (struct MemoryStruct_s *) userp;
mem->memory = (char *) realloc(mem->memory, mem->size + realsize + 1);
if (mem->memory == NULL) {
/* out of memory! */
//NET_LOGE("not enough memory (realloc returned NULL)\n");
printf("not enough memory (realloc returned NULL)\n");
return 0;
}
memcpy(&(mem->memory[mem->size]), contents, realsize);
mem->size += realsize;
mem->memory[mem->size] = 0;
return realsize;
}
static void curl_error_print(CURLcode res, const char *errbuf, int line) {
//NET_LOGD("start curl_error_print line:%d ", line);
if (res != CURLE_OK) {
//NET_LOGD("curl err=%d at line:%d ", res, line);
printf("curl err=%d at line:%d ", res, line);
size_t len = strlen(errbuf);
if (len)
//NET_LOGD("%s\n", errbuf);
printf("%s\n", errbuf);
}
}
class GlobalInit {
public:
GlobalInit()
{
CURLcode curl_res = curl_global_init(CURL_GLOBAL_ALL);
char errbuf[CURL_ERROR_SIZE] = {0,};
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
printf("cannot global initialize curl");
}
}
~GlobalInit()
{
curl_global_cleanup();
}
};
static GlobalInit globalinit;
int NetClient::easycurl(string host, string path, string method, std::map<string, string> queryParams,
string mBody, struct curl_slist* headerList, MemoryStruct_s *p_chunk, long *code, char * errormsg) {
char *url = NULL;
char *body = (char *) malloc(mBody.size() + 1);
memcpy(body, mBody.c_str(), mBody.size() + 1);
string uri = string(host);
uri.append(path);
NetHttpMethod httpMethod;
if (method.compare("GET") == 0)
httpMethod = NET_HTTP_GET;
else if (method.compare("PUT") == 0)
httpMethod = NET_HTTP_PUT;
else if (method.compare("POST") == 0)
httpMethod = NET_HTTP_POST;
else
httpMethod = NET_HTTP_DELETE;
CURL *curl_handle;
CURLcode curl_res;
errormsg = (char*) malloc(CURL_ERROR_SIZE);
char errbuf[CURL_ERROR_SIZE] = {0,};
MemoryStruct_s chunk;
int ret_val = {{prefix}}_ERROR_NONE;
// FILE *file;
printf("start NET_Utils::easycurl");
//NET_LOGD("start NET_Utils::easycurl");
/* if (put_method) {
file = fopen("tmp/sami_temp", "wb");
if (file == NULL) {
NET_LOGE("fopen() failed, file is NULL");
}
}
*/
//get_proxy_address();
chunk.memory = NULL;
/* init the curl session */
curl_handle = curl_easy_init();
if (curl_handle == NULL) {
printf("Unable to initialize cURL interface");
//NET_LOGE("Unable to initialize cURL interface");
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto RETURN;
}
curl_res = curl_easy_setopt(curl_handle, CURLOPT_SSL_VERIFYPEER, 0L);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
if (queryParams.size() > 0) {
string queryParam = "";
for (std::map<string, string>::iterator queryIter = queryParams.begin(); queryIter != queryParams.end(); ++queryIter) {
if (queryIter == queryParams.begin())
queryParam.append("?");
else
queryParam.append("&");
string pKey = static_cast<string> (queryIter->first);
string pValue = static_cast<string> (queryIter->second);
char *encoded = curl_easy_escape(curl_handle, pKey.c_str(), 0);
queryParam.append(encoded);
curl_free(encoded);
queryParam.append("=");
encoded = curl_easy_escape(curl_handle, pValue.c_str(), 0);
queryParam.append(encoded);
curl_free(encoded);
}
uri.append(queryParam);
}
//AppLog("%ls", uri.c_str());
printf("%s", uri.c_str());
curl_res = curl_easy_setopt(curl_handle, CURLOPT_ERRORBUFFER, errbuf);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
/* no progcurl_ress meter please */
//curl_easy_setopt(curl_handle, CURLOPT_FOLLOWLOCATION, 1L);
/* send all data to this function */
curl_res = curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
switch (httpMethod) {
case NET_HTTP_GET:
curl_res = curl_easy_setopt(curl_handle, CURLOPT_HTTPGET, true);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
break;
case NET_HTTP_POST:
curl_res = curl_easy_setopt(curl_handle, CURLOPT_POST, true);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
curl_res = curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, body);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
break;
case NET_HTTP_DELETE:
curl_res = curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
curl_res = curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, body);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
break;
case NET_HTTP_PUT:
//curl_res = curl_easy_setopt(curl_handle, CURLOPT_PUT, 1);
//curl_res = curl_easy_setopt(curl_handle, CURLOPT_UPLOAD, 1);
curl_res = curl_easy_setopt(curl_handle, CURLOPT_CUSTOMREQUEST, "PUT");
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
curl_res = curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, body);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
break;
default:
break;
}
/* set URL to get */
url = (char *) malloc(uri.size() + 1);
memcpy(url, uri.c_str(), uri.size() + 1);
printf("\n%s\n", url);
curl_res = curl_easy_setopt(curl_handle, CURLOPT_URL, url);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
//curl_easy_setopt(curl_handle, CURLOPT_HEADER, 1);
// curl_res = curl_easy_setopt(curl_handle, CURLOPT_HEADER, true);
// curl_error_print(curl_res, errbuf, __LINE__);
curl_res = curl_easy_setopt(curl_handle, CURLOPT_HTTPHEADER, headerList);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto CURL_EASY_CLEANUP;
}
/*
if(body != NULL) {
if (put_method == false) {
curl_res = curl_easy_setopt(curl_handle, CURLOPT_POSTFIELDS, body);
curl_error_print(curl_res, errbuf, 184);
}
else {
curl_res = curl_easy_setopt(curl_handle, CURLOPT_PUT, 1);
curl_error_print(curl_res, errbuf, 188);
//curl_easy_setopt(curl_handle, CURLOPT_BINARYTRANSFER, 1);
if (fwrite(body, sizeof(char), strlen(body), file) != strlen(body)) {
NET_LOGE("fwrite() failed");
}
curl_res = curl_easy_setopt(curl_handle, CURLOPT_INFILE, file);
curl_error_print(curl_res, errbuf, 195);
curl_res = curl_easy_setopt(curl_handle, CURLOPT_INFILESIZE, strlen(body));
curl_error_print(curl_res, errbuf, 197);
if (g_unlink("tmp/sami_temp") == -1) {
NET_LOGE("file was not deleted");
}
}
}
*/
chunk.memory = (char *) malloc(1); /* will be grown as needed by the realloc above */
chunk.size = 0; /* no data at this point */
/* we want the headers to this file handle */
curl_res = curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *) &chunk);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto FREE_CHUNK;
}
/* some servers don't like requests that are made without a user-agent
field, so we provide one */
curl_res = curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0");
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto FREE_CHUNK;
}
/* set timeout */
curl_res = curl_easy_setopt(curl_handle, CURLOPT_TIMEOUT, 30L);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto FREE_CHUNK;
}
//curl_res = curl_easy_setopt(curl_handle, CURLOPT_PROXY, "http://10.112.1.184:8080/");
curl_res = curl_easy_perform(curl_handle);
curl_error_print(curl_res, errbuf, __LINE__);
if (curl_res == CURLE_COULDNT_RESOLVE_HOST) {
ret_val = {{prefix}}_ERROR_UNREACHED_TO_SERVER;
goto FREE_CHUNK;
} else if (curl_res != CURLE_OK) {
ret_val = {{prefix}}_ERROR_UNKNOWN;
goto FREE_CHUNK;
}
curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, code);
p_chunk->memory = chunk.memory;
p_chunk->size = chunk.size;
/*
if (put_method) {
fclose(file);
if (g_unlink("tmp/sami_temp") == -1) {
NET_LOGE("file was not deleted");
}
}
*/
FREE_CHUNK:
if (curl_res != CURLE_OK) {
if (chunk.memory) {
free(chunk.memory);
chunk.memory = NULL;
}
size_t len = strlen(errbuf);
fprintf(stderr, "\nlibcurl: (%d) ", curl_res);
if (len) {
sprintf(errormsg, "%s%s", errbuf, ((errbuf[len - 1] != '\n') ? "\n" : ""));
} else {
sprintf(errormsg, "%s\n", curl_easy_strerror(curl_res));
}
}
CURL_EASY_CLEANUP:
/* cleanup curl stuff */
curl_easy_cleanup(curl_handle);
RETURN:
printf("end NET_Utils::easycurl");
free(url);
free(body);
//NET_LOGD("end NET_Utils::easycurl");
return ret_val;
}

View File

@ -0,0 +1,53 @@
#ifndef _NetClient_H_
#define _NetClient_H_
#include <map>
#include <string>
#include <cstring>
#include <stdbool.h>
#include <stdlib.h>
#include <glib.h>
#include <glib/gstdio.h>
#include <glib-object.h>
#include <json-glib/json-glib.h>
#include <curl/curl.h>
using namespace std;
typedef enum {
{{prefix}}_ERROR_NONE = 0, /**< Successful */
{{prefix}}_ERROR_UNKNOWN, /**< Unknown error */
{{prefix}}_ERROR_NO_RESPONSE_BODY, /**< No response body error */
{{prefix}}_ERROR_JSON_PARSING_FAIL, /**< Parsing fail of json data */
{{prefix}}_ERROR_UNREACHED_TO_SERVER, /**< Unreached to artik cloud server */
{{prefix}}_ERROR_INVALID_PARAMETER, /**< Invalid parameter */
{{prefix}}_ERROR_PERMISSION_DENIED /**< Permission denied */
} {{prefix}}_error_e;
typedef enum {
NET_HTTP_GET = 0,
NET_HTTP_POST,
NET_HTTP_PUT,
NET_HTTP_DELETE,
NET_HTTP_HEAD,
NET_HTTP_TRACE,
NET_HTTP_OPTIONS,
NET_HTTP_CONNECT,
NET_HTTP_PATCH
} NetHttpMethod;
struct MemoryStruct_s {
char *memory;
size_t size;
};
class NetClient {
public:
NetClient();
virtual ~NetClient();
static int easycurl(string host, string path, string method, map<string, string> queryParams,
string mBody, struct curl_slist* headerList, MemoryStruct_s* p_chunk, long* code, char* errormsg);
};
#endif /* NetClient_H_ */

View File

@ -1,27 +1,26 @@
#ifndef _{{prefix}}_OBJECT_H_
#define _{{prefix}}_OBJECT_H_
#ifndef _OBJECT_H_
#define _OBJECT_H_
#include <FNet.h>
#include <FWebJson.h>
#include <FBase.h>
namespace Tizen{
namespace {{prefix}} {
using Tizen::Base::String;
class Object {
public:
using namespace Tizen::Web::Json;
virtual char* toJson()
{
return NULL;
}
class {{prefix}}Object {
public:
virtual JsonObject* asJsonObject() {
return null;
}
virtual ~{{prefix}}Object() {}
virtual {{prefix}}Object* fromJson(String* obj) {
return null;
}
virtual void fromJsonObject(IJsonValue* obj) {}
virtual String asJson() {
return L"";
}
virtual ~Object()
{
}
virtual void fromJson(char* jsonStr)
{
}
};
#endif /* _{{prefix}}_OBJECT_H_ */
}
}
#endif /* _OBJECT_H_ */

View File

@ -0,0 +1,66 @@
#ifndef _REQUESTINFO_H_
#define _REQUESTINFO_H_
#include "NetClient.h"
using namespace std;
namespace Tizen{
namespace {{prefix}} {
class RequestInfo {
public:
string host;
string path;
string method;
map<string, string> queryParams;
string mBody;
struct curl_slist* headerList;
MemoryStruct_s *p_chunk;
long *code;
char *errormsg;
void *userData;
void(* handler)();
bool (*processor)(MemoryStruct_s, long, char*, void*, void(*)());
GThread *thread;
RequestInfo(string host, string path, string method, map<string, string> queryParams,
string mBody, struct curl_slist* headerList, MemoryStruct_s* p_chunk, long* code,
char* errormsg, void* userData, void(* voidHandler)(),
bool (*processor)(MemoryStruct_s, long, char*, void*, void(*)()))
{
this->host = host;
this->path = path;
this->method = method;
this->queryParams = queryParams;
this->mBody = mBody;
this->headerList = headerList;
this->p_chunk = p_chunk;
this->code = new long (*code);
this->errormsg = errormsg;
this->userData = userData;
this->handler = reinterpret_cast<void(*)()>(voidHandler);
this->processor = processor;
}
~RequestInfo()
{
curl_slist_free_all(headerList);
if (this->p_chunk) {
if((this->p_chunk)->memory) {
free((this->p_chunk)->memory);
}
delete (p_chunk);
}
delete (this->code);
if (this->errormsg) {
free(this->errormsg);
}
}
};
}
}
#endif /* REQUESTINFO_H_ */

View File

@ -4,7 +4,7 @@
<parent>
<groupId>io.swagger</groupId>
<artifactId>swagger-codegen-project</artifactId>
<version>2.2.2-SNAPSHOT</version>
<version>2.3.0-SNAPSHOT</version>
<relativePath>../..</relativePath>
</parent>
<artifactId>swagger-generator</artifactId>

View File

@ -10,7 +10,7 @@
<artifactId>swagger-codegen-project</artifactId>
<packaging>pom</packaging>
<name>swagger-codegen-project</name>
<version>2.2.2-SNAPSHOT</version>
<version>2.3.0-SNAPSHOT</version>
<url>https://github.com/swagger-api/swagger-codegen</url>
<scm>
<connection>scm:git:git@github.com:swagger-api/swagger-codegen.git</connection>

View File

@ -6,7 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi
- API version: 1.0.0
- Package version:
- Build date: 2016-08-28T17:01:51.939+03:00
- Build date: 2016-09-14T16:08:32.750+02:00
- Build package: class io.swagger.codegen.languages.ObjcClientCodegen
## Requirements
@ -40,7 +40,7 @@ Import the following:
```objc
#import <SwaggerClient/SWGApiClient.h>
#import <SwaggerClient/SWGConfiguration.h>
#import <SwaggerClient/SWGDefaultConfiguration.h>
// load models
#import <SwaggerClient/SWGCategory.h>
#import <SwaggerClient/SWGOrder.h>
@ -64,7 +64,7 @@ Please follow the [installation procedure](#installation--usage) and then run th
```objc
SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig];
SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig];
// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
@ -124,12 +124,6 @@ Class | Method | HTTP request | Description
## Documentation For Authorization
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## petstore_auth
- **Type**: OAuth
@ -139,6 +133,12 @@ Class | Method | HTTP request | Description
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## Author

View File

@ -32,6 +32,6 @@ Pod::Spec.new do |s|
s.dependency 'AFNetworking', '~> 3'
s.dependency 'JSONModel', '~> 1.2'
s.dependency 'ISO8601', '~> 0.5'
s.dependency 'ISO8601', '~> 0.6'
end

View File

@ -32,7 +32,7 @@
extern NSString* kSWGPetApiErrorDomain;
extern NSInteger kSWGPetApiMissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
/// Add a new pet to the store
///
@ -42,7 +42,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:405 message:"Invalid input"
///
/// @return
-(NSNumber*) addPetWithBody: (SWGPet*) body
-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -55,7 +55,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:400 message:"Invalid pet value"
///
/// @return
-(NSNumber*) deletePetWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId
apiKey: (NSString*) apiKey
completionHandler: (void (^)(NSError* error)) handler;
@ -69,7 +69,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:400 message:"Invalid status value"
///
/// @return NSArray<SWGPet>*
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler;
@ -82,7 +82,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:400 message:"Invalid tag value"
///
/// @return NSArray<SWGPet>*
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler;
@ -96,7 +96,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:404 message:"Pet not found"
///
/// @return SWGPet*
-(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error)) handler;
@ -110,7 +110,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:405 message:"Validation exception"
///
/// @return
-(NSNumber*) updatePetWithBody: (SWGPet*) body
-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -124,7 +124,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:405 message:"Invalid input"
///
/// @return
-(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId
-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId
name: (NSString*) name
status: (NSString*) status
completionHandler: (void (^)(NSError* error)) handler;
@ -140,7 +140,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) uploadFileWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata
file: (NSURL*) file
completionHandler: (void (^)(NSError* error)) handler;

View File

@ -1,11 +1,12 @@
#import "SWGPetApi.h"
#import "SWGQueryParamCollection.h"
#import "SWGApiClient.h"
#import "SWGPet.h"
@interface SWGPetApi ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -19,52 +20,31 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
SWGConfiguration *config = [SWGConfiguration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[SWGApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[SWGApiClient sharedClient]];
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static SWGPetApi *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [SWGApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -76,7 +56,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) addPetWithBody: (SWGPet*) body
-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"];
@ -124,8 +104,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -137,7 +116,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) deletePetWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId
apiKey: (NSString*) apiKey
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'petId' is set
@ -202,8 +181,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -213,7 +191,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns NSArray<SWGPet>*
///
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"];
@ -264,8 +242,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)data, error);
}
}
];
}];
}
///
@ -275,7 +252,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns NSArray<SWGPet>*
///
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"];
@ -326,8 +303,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)data, error);
}
}
];
}];
}
///
@ -337,7 +313,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns SWGPet*
///
-(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error)) handler {
// verify the required parameter 'petId' is set
if (petId == nil) {
@ -376,7 +352,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[@"api_key", @"petstore_auth"];
NSArray *authSettings = @[@"petstore_auth", @"api_key"];
id bodyParam = nil;
NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
@ -398,8 +374,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGPet*)data, error);
}
}
];
}];
}
///
@ -409,7 +384,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) updatePetWithBody: (SWGPet*) body
-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"];
@ -457,8 +432,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -472,7 +446,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId
-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId
name: (NSString*) name
status: (NSString*) status
completionHandler: (void (^)(NSError* error)) handler {
@ -541,8 +515,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -556,7 +529,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) uploadFileWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata
file: (NSURL*) file
completionHandler: (void (^)(NSError* error)) handler {
@ -623,8 +596,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}

View File

@ -32,7 +32,7 @@
extern NSString* kSWGStoreApiErrorDomain;
extern NSInteger kSWGStoreApiMissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
/// Delete purchase order by ID
/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
@ -43,7 +43,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:404 message:"Order not found"
///
/// @return
-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId
completionHandler: (void (^)(NSError* error)) handler;
@ -54,7 +54,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:200 message:"successful operation"
///
/// @return NSDictionary<NSString*, NSNumber*>*
-(NSNumber*) getInventoryWithCompletionHandler:
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* output, NSError* error)) handler;
@ -68,7 +68,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:404 message:"Order not found"
///
/// @return SWGOrder*
-(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler;
@ -81,7 +81,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:400 message:"Invalid Order"
///
/// @return SWGOrder*
-(NSNumber*) placeOrderWithBody: (SWGOrder*) body
-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler;

View File

@ -1,11 +1,12 @@
#import "SWGStoreApi.h"
#import "SWGQueryParamCollection.h"
#import "SWGApiClient.h"
#import "SWGOrder.h"
@interface SWGStoreApi ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -19,52 +20,31 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
SWGConfiguration *config = [SWGConfiguration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[SWGApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[SWGApiClient sharedClient]];
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static SWGStoreApi *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [SWGApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -76,7 +56,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'orderId' is set
if (orderId == nil) {
@ -137,8 +117,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -146,7 +125,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
/// Returns a map of status codes to quantities
/// @returns NSDictionary<NSString*, NSNumber*>*
///
-(NSNumber*) getInventoryWithCompletionHandler:
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"];
@ -193,8 +172,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSDictionary<NSString*, NSNumber*>*)data, error);
}
}
];
}];
}
///
@ -204,7 +182,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
///
/// @returns SWGOrder*
///
-(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler {
// verify the required parameter 'orderId' is set
if (orderId == nil) {
@ -265,8 +243,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGOrder*)data, error);
}
}
];
}];
}
///
@ -276,7 +253,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
///
/// @returns SWGOrder*
///
-(NSNumber*) placeOrderWithBody: (SWGOrder*) body
-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"];
@ -324,8 +301,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGOrder*)data, error);
}
}
];
}];
}

View File

@ -32,7 +32,7 @@
extern NSString* kSWGUserApiErrorDomain;
extern NSInteger kSWGUserApiMissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
/// Create user
/// This can only be done by the logged in user.
@ -42,7 +42,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) createUserWithBody: (SWGUser*) body
-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -54,7 +54,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -66,7 +66,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -79,7 +79,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:404 message:"User not found"
///
/// @return
-(NSNumber*) deleteUserWithUsername: (NSString*) username
-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username
completionHandler: (void (^)(NSError* error)) handler;
@ -93,7 +93,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:404 message:"User not found"
///
/// @return SWGUser*
-(NSNumber*) getUserByNameWithUsername: (NSString*) username
-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error)) handler;
@ -107,7 +107,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:400 message:"Invalid username/password supplied"
///
/// @return NSString*
-(NSNumber*) loginUserWithUsername: (NSString*) username
-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username
password: (NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error)) handler;
@ -119,7 +119,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) logoutUserWithCompletionHandler:
-(NSURLSessionTask*) logoutUserWithCompletionHandler:
(void (^)(NSError* error)) handler;
@ -133,7 +133,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:404 message:"User not found"
///
/// @return
-(NSNumber*) updateUserWithUsername: (NSString*) username
-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username
body: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler;

View File

@ -1,11 +1,12 @@
#import "SWGUserApi.h"
#import "SWGQueryParamCollection.h"
#import "SWGApiClient.h"
#import "SWGUser.h"
@interface SWGUserApi ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -19,52 +20,31 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
SWGConfiguration *config = [SWGConfiguration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[SWGApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[SWGApiClient sharedClient]];
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static SWGUserApi *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [SWGApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -76,7 +56,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) createUserWithBody: (SWGUser*) body
-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"];
@ -124,8 +104,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -135,7 +114,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"];
@ -183,8 +162,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -194,7 +172,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"];
@ -242,8 +220,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -253,7 +230,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) deleteUserWithUsername: (NSString*) username
-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'username' is set
if (username == nil) {
@ -314,8 +291,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -325,7 +301,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns SWGUser*
///
-(NSNumber*) getUserByNameWithUsername: (NSString*) username
-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error)) handler {
// verify the required parameter 'username' is set
if (username == nil) {
@ -386,8 +362,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGUser*)data, error);
}
}
];
}];
}
///
@ -399,7 +374,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns NSString*
///
-(NSNumber*) loginUserWithUsername: (NSString*) username
-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username
password: (NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"];
@ -453,8 +428,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSString*)data, error);
}
}
];
}];
}
///
@ -462,7 +436,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) logoutUserWithCompletionHandler:
-(NSURLSessionTask*) logoutUserWithCompletionHandler:
(void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"];
@ -509,8 +483,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -522,7 +495,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) updateUserWithUsername: (NSString*) username
-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username
body: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'username' is set
@ -585,8 +558,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}

View File

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

View File

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

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#import "SWGObject.h"
#import "SWGApiClient.h"
@class SWGApiClient;
/**
* Swagger Petstore
@ -28,15 +28,13 @@
@protocol SWGApi <NSObject>
@property(nonatomic, assign) SWGApiClient *apiClient;
@property(readonly, nonatomic, strong) SWGApiClient *apiClient;
-(id) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:");
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
-(NSString*) defaultHeaderForKey:(NSString*)key;
-(NSUInteger) requestQueueSize;
-(NSDictionary *)defaultHeaders;
@end

View File

@ -1,13 +1,7 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import <AFNetworking/AFNetworking.h>
#import "SWGJSONResponseSerializer.h"
#import "SWGJSONRequestSerializer.h"
#import "SWGQueryParamCollection.h"
#import "SWGConfiguration.h"
#import "SWGResponseDeserializer.h"
#import "SWGSanitizer.h"
#import "SWGLogger.h"
/**
* Swagger Petstore
@ -33,16 +27,6 @@
* limitations under the License.
*/
#import "SWGCategory.h"
#import "SWGOrder.h"
#import "SWGPet.h"
#import "SWGTag.h"
#import "SWGUser.h"
@class SWGConfiguration;
/**
* A key for `NSError` user info dictionaries.
*
@ -50,118 +34,42 @@
*/
extern NSString *const SWGResponseObjectErrorKey;
@interface SWGApiClient : AFHTTPSessionManager
@property(nonatomic, assign) NSURLRequestCachePolicy cachePolicy;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, readonly) NSOperationQueue* queue;
@property (nonatomic, strong, readonly) id<SWGConfiguration> configuration;
/// In order to ensure the HTTPResponseHeaders are correct, it is recommended to initialize one SWGApiClient instance per thread.
@property(nonatomic, readonly) NSDictionary* HTTPResponseHeaders;
@property(nonatomic, assign) NSTimeInterval timeoutInterval;
@property(nonatomic, strong) id<SWGResponseDeserializer> responseDeserializer;
@property(nonatomic, strong) id<SWGSanitizer> sanitizer;
/**
* Clears Cache
*/
+(void)clearCache;
@property (nonatomic, strong) NSDictionary< NSString *, AFHTTPRequestSerializer <AFURLRequestSerialization> *>* requestSerializerForContentType;
/**
* Turns on cache
*
* @param enabled If the cached is enable, must be `YES` or `NO`
* Gets client singleton instance
*/
+(void)setCacheEnabled:(BOOL) enabled;
+ (instancetype) sharedClient;
/**
* Gets the request queue size
*
* @return The size of `queuedRequests` static variable.
*/
+(NSUInteger)requestQueueSize;
/**
* Sets the client unreachable
*
* @param state off line state, must be `YES` or `NO`
*/
+(void) setOfflineState:(BOOL) state;
/**
* Gets if the client is unreachable
*
* @return The client offline state
*/
+(BOOL) getOfflineState;
/**
* Sets the client reachability, this may be overridden by the reachability manager if reachability changes
*
* @param The client reachability.
*/
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus) status;
/**
* Gets the client reachability
*
* @return The client reachability.
*/
+(AFNetworkReachabilityStatus) getReachabilityStatus;
/**
* Gets the next request id
*
* @return The next executed request id.
*/
+(NSNumber*) nextRequestId;
/**
* Generates request id and add it to the queue
*
* @return The next executed request id.
*/
+(NSNumber*) queueRequest;
/**
* Removes request id from the queue
*
* @param requestId The request which will be removed.
*/
+(void) cancelRequest:(NSNumber*)requestId;
/**
* Customizes the behavior when the reachability changed
*
* @param changeBlock The block will be executed when the reachability changed.
*/
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock;
/**
* Sets the api client reachability strategy
*/
- (void)configureCacheReachibility;
/**
* Sets header for request
*
* @param value The header value
* @param forKey The header key
*/
-(void)setHeaderValue:(NSString*) value
forKey:(NSString*) forKey;
/**
* Updates header parameters and query parameters for authentication
*
* @param headers The header parameter will be updated, passed by pointer to pointer.
* @param headers The header parameter will be udpated, passed by pointer to pointer.
* @param querys The query parameters will be updated, passed by pointer to pointer.
* @param authSettings The authentication names NSArray.
*/
- (void) updateHeaderParams:(NSDictionary **)headers
queryParams:(NSDictionary **)querys
WithAuthSettings:(NSArray *)authSettings;
- (void) updateHeaderParams:(NSDictionary **)headers queryParams:(NSDictionary **)querys WithAuthSettings:(NSArray *)authSettings;
/**
* Initializes the session manager with a configuration.
*
* @param configuration The configuration implementation
*/
- (instancetype)initWithConfiguration:(id<SWGConfiguration>)configuration;
/**
* Performs request
*
@ -176,35 +84,20 @@ extern NSString *const SWGResponseObjectErrorKey;
* @param responseContentType Response content-type.
* @param completionBlock The block will be executed when the request completed.
*
* @return The request id.
* @return The created session task.
*/
-(NSNumber*) requestWithPath:(NSString*) path
method:(NSString*) method
pathParams:(NSDictionary *) pathParams
queryParams:(NSDictionary*) queryParams
formParams:(NSDictionary *) formParams
files:(NSDictionary *) files
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings:(NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
responseType:(NSString *) responseType
completionBlock:(void (^)(id, NSError *))completionBlock;
/**
* Custom security policy
*
* @return AFSecurityPolicy
*/
- (AFSecurityPolicy *) customSecurityPolicy;
/**
* SWGConfiguration return sharedConfig
*
* @return SWGConfiguration
*/
- (SWGConfiguration*) configuration;
- (NSURLSessionTask*) requestWithPath: (NSString*) path
method: (NSString*) method
pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams
formParams: (NSDictionary *) formParams
files: (NSDictionary *) files
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock;
@end

View File

@ -1,14 +1,13 @@
#import "SWGLogger.h"
#import "SWGApiClient.h"
#import "SWGJSONRequestSerializer.h"
#import "SWGQueryParamCollection.h"
#import "SWGDefaultConfiguration.h"
NSString *const SWGResponseObjectErrorKey = @"SWGResponseObject";
static NSUInteger requestId = 0;
static bool offlineState = false;
static NSMutableSet * queuedRequests = nil;
static bool cacheEnabled = false;
static AFNetworkReachabilityStatus reachabilityStatus = AFNetworkReachabilityStatusNotReachable;
static void (^reachabilityChangeBlock)(int);
static NSString * const kSWGContentDispositionKey = @"Content-Disposition";
static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
if(![response isKindOfClass:[NSHTTPURLResponse class]]) {
@ -19,179 +18,80 @@ static NSDictionary * SWG__headerFieldsForResponse(NSURLResponse *response) {
static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSDictionary * headers = SWG__headerFieldsForResponse(response);
if(!headers[@"Content-Disposition"]) {
if(!headers[kSWGContentDispositionKey]) {
return [NSString stringWithFormat:@"%@", [[NSProcessInfo processInfo] globallyUniqueString]];
}
NSString *pattern = @"filename=['\"]?([^'\"\\s]+)['\"]?";
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive
error:nil];
NSString *contentDispositionHeader = headers[@"Content-Disposition"];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader
options:0
range:NSMakeRange(0, [contentDispositionHeader length])];
NSRegularExpression *regexp = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
NSString *contentDispositionHeader = headers[kSWGContentDispositionKey];
NSTextCheckingResult *match = [regexp firstMatchInString:contentDispositionHeader options:0 range:NSMakeRange(0, [contentDispositionHeader length])];
return [contentDispositionHeader substringWithRange:[match rangeAtIndex:1]];
}
@interface SWGApiClient ()
@property (nonatomic, strong) NSDictionary* HTTPResponseHeaders;
@property (nonatomic, strong, readwrite) id<SWGConfiguration> configuration;
@property (nonatomic, strong) NSArray<NSString*>* downloadTaskResponseTypes;
@end
@implementation SWGApiClient
#pragma mark - Singleton Methods
+ (instancetype) sharedClient {
static SWGApiClient *sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedClient = [[self alloc] init];
});
return sharedClient;
}
#pragma mark - Initialize Methods
- (instancetype)init {
NSString *baseUrl = [[SWGConfiguration sharedConfig] host];
return [self initWithBaseURL:[NSURL URLWithString:baseUrl]];
return [self initWithConfiguration:[SWGDefaultConfiguration sharedConfig]];
}
- (instancetype)initWithBaseURL:(NSURL *)url {
return [self initWithBaseURL:url configuration:[SWGDefaultConfiguration sharedConfig]];
}
- (instancetype)initWithConfiguration:(id<SWGConfiguration>)configuration {
return [self initWithBaseURL:[NSURL URLWithString:configuration.host] configuration:configuration];
}
- (instancetype)initWithBaseURL:(NSURL *)url configuration:(id<SWGConfiguration>)configuration {
self = [super initWithBaseURL:url];
if (self) {
self.timeoutInterval = 60;
self.requestSerializer = [AFJSONRequestSerializer serializer];
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.securityPolicy = [self customSecurityPolicy];
self.responseDeserializer = [[SWGResponseDeserializer alloc] init];
self.sanitizer = [[SWGSanitizer alloc] init];
// configure reachability
[self configureCacheReachibility];
_configuration = configuration;
_timeoutInterval = 60;
_responseDeserializer = [[SWGResponseDeserializer alloc] init];
_sanitizer = [[SWGSanitizer alloc] init];
_downloadTaskResponseTypes = @[@"NSURL*", @"NSURL"];
AFHTTPRequestSerializer* afhttpRequestSerializer = [AFHTTPRequestSerializer serializer];
SWGJSONRequestSerializer * swgjsonRequestSerializer = [SWGJSONRequestSerializer serializer];
_requestSerializerForContentType = @{kSWGApplicationJSONType : swgjsonRequestSerializer,
@"application/x-www-form-urlencoded": afhttpRequestSerializer,
@"multipart/form-data": afhttpRequestSerializer
};
self.securityPolicy = [self createSecurityPolicy];
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
return self;
}
+ (void)initialize {
if (self == [SWGApiClient class]) {
queuedRequests = [[NSMutableSet alloc] init];
// initialize URL cache
[self configureCacheWithMemoryAndDiskCapacity:4*1024*1024 diskSize:32*1024*1024];
}
}
#pragma mark - Task Methods
#pragma mark - Setter Methods
+ (void) setOfflineState:(BOOL) state {
offlineState = state;
}
+ (void) setCacheEnabled:(BOOL)enabled {
cacheEnabled = enabled;
}
+(void) setReachabilityStatus:(AFNetworkReachabilityStatus)status {
reachabilityStatus = status;
}
- (void)setHeaderValue:(NSString*) value forKey:(NSString*) forKey {
[self.requestSerializer setValue:value forHTTPHeaderField:forKey];
}
- (void)setRequestSerializer:(AFHTTPRequestSerializer<AFURLRequestSerialization> *)requestSerializer {
[super setRequestSerializer:requestSerializer];
requestSerializer.timeoutInterval = self.timeoutInterval;
}
#pragma mark - Cache Methods
+(void)clearCache {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
+(void)configureCacheWithMemoryAndDiskCapacity: (unsigned long) memorySize
diskSize: (unsigned long) diskSize {
NSAssert(memorySize > 0, @"invalid in-memory cache size");
NSAssert(diskSize >= 0, @"invalid disk cache size");
NSURLCache *cache =
[[NSURLCache alloc]
initWithMemoryCapacity:memorySize
diskCapacity:diskSize
diskPath:@"swagger_url_cache"];
[NSURLCache setSharedURLCache:cache];
}
#pragma mark - Request Methods
+(NSUInteger)requestQueueSize {
return [queuedRequests count];
}
+(NSNumber*) nextRequestId {
@synchronized(self) {
return @(++requestId);
}
}
+(NSNumber*) queueRequest {
NSNumber* requestId = [[self class] nextRequestId];
SWGDebugLog(@"added %@ to request queue", requestId);
[queuedRequests addObject:requestId];
return requestId;
}
+(void) cancelRequest:(NSNumber*)requestId {
[queuedRequests removeObject:requestId];
}
-(Boolean) executeRequestWithId:(NSNumber*) requestId {
NSSet* matchingItems = [queuedRequests objectsPassingTest:^BOOL(id obj, BOOL *stop) {
return [obj intValue] == [requestId intValue];
}];
if (matchingItems.count == 1) {
SWGDebugLog(@"removed request id %@", requestId);
[queuedRequests removeObject:requestId];
return YES;
} else {
return NO;
}
}
#pragma mark - Reachability Methods
+(AFNetworkReachabilityStatus) getReachabilityStatus {
return reachabilityStatus;
}
+(BOOL) getOfflineState {
return offlineState;
}
+(void) setReachabilityChangeBlock:(void(^)(int))changeBlock {
reachabilityChangeBlock = changeBlock;
}
- (void) configureCacheReachibility {
[self.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
reachabilityStatus = status;
SWGDebugLog(@"reachability changed to %@",AFStringFromNetworkReachabilityStatus(status));
[SWGApiClient setOfflineState:status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable];
// call the reachability block, if configured
if (reachabilityChangeBlock != nil) {
reachabilityChangeBlock(status);
}
}];
[self.reachabilityManager startMonitoring];
}
#pragma mark - Operation Methods
- (void) operationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock {
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (![strongSelf executeRequestWithId:requestId]) {
return;
}
- (NSURLSessionDataTask*) taskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
NSURLSessionDataTask *task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
SWGDebugLogResponse(response, responseObject,request,error);
strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response);
if(!error) {
completionBlock(responseObject, nil);
return;
@ -204,20 +104,17 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
}];
[op resume];
return task;
}
- (void) downloadOperationWithCompletionBlock: (NSURLRequest *)request
requestId: (NSNumber *) requestId
completionBlock: (void (^)(id, NSError *))completionBlock {
__weak __typeof(self)weakSelf = self;
NSURLSessionDataTask* op = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
__strong __typeof(weakSelf)strongSelf = weakSelf;
if (![strongSelf executeRequestWithId:requestId]) {
return;
}
strongSelf.HTTPResponseHeaders = SWG__headerFieldsForResponse(response);
- (NSURLSessionDataTask*) downloadTaskWithCompletionBlock: (NSURLRequest *)request completionBlock: (void (^)(id, NSError *))completionBlock {
__block NSString * tempFolderPath = [self.configuration.tempFolderPath copy];
NSURLSessionDataTask* task = [self dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
SWGDebugLogResponse(response, responseObject,request,error);
if(error) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if (responseObject) {
@ -225,9 +122,11 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
completionBlock(nil, augmentedError);
return;
}
NSString *directory = [self configuration].tempFolderPath ?: NSTemporaryDirectory();
NSString * filename = SWG__fileNameForResponse(response);
NSString *directory = tempFolderPath ?: NSTemporaryDirectory();
NSString *filename = SWG__fileNameForResponse(response);
NSString *filepath = [directory stringByAppendingPathComponent:filename];
NSURL *file = [NSURL fileURLWithPath:filepath];
@ -236,53 +135,37 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
completionBlock(file, nil);
}];
[op resume];
return task;
}
#pragma mark - Perform Request Methods
#pragma mark - Perform Request Methods
-(NSNumber*) requestWithPath: (NSString*) path
method: (NSString*) method
pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams
formParams: (NSDictionary *) formParams
files: (NSDictionary *) files
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [SWGJSONRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
NSAssert(NO, @"Unsupported request type %@", requestContentType);
}
- (NSURLSessionTask*) requestWithPath: (NSString*) path
method: (NSString*) method
pathParams: (NSDictionary *) pathParams
queryParams: (NSDictionary*) queryParams
formParams: (NSDictionary *) formParams
files: (NSDictionary *) files
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
responseType: (NSString *) responseType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [SWGJSONResponseSerializer serializer];
} else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
}
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = [self requestSerializerForRequestContentType:requestContentType];
__weak id<SWGSanitizer> sanitizer = self.sanitizer;
// sanitize parameters
pathParams = [self.sanitizer sanitizeForSerialization:pathParams];
queryParams = [self.sanitizer sanitizeForSerialization:queryParams];
headerParams = [self.sanitizer sanitizeForSerialization:headerParams];
formParams = [self.sanitizer sanitizeForSerialization:formParams];
pathParams = [sanitizer sanitizeForSerialization:pathParams];
queryParams = [sanitizer sanitizeForSerialization:queryParams];
headerParams = [sanitizer sanitizeForSerialization:headerParams];
formParams = [sanitizer sanitizeForSerialization:formParams];
if(![body isKindOfClass:[NSData class]]) {
body = [self.sanitizer sanitizeForSerialization:body];
body = [sanitizer sanitizeForSerialization:body];
}
// auth setting
@ -295,22 +178,19 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
[resourcePath replaceCharactersInRange:[resourcePath rangeOfString:[NSString stringWithFormat:@"{%@}", key]] withString:safeString];
}];
NSMutableURLRequest * request = nil;
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:resourcePath queryParams:queryParams];
if ([pathWithQueryParams hasPrefix:@"/"]) {
pathWithQueryParams = [pathWithQueryParams substringFromIndex:1];
}
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
NSError *requestCreateError = nil;
NSMutableURLRequest * request = nil;
if (files.count > 0) {
__weak __typeof(self)weakSelf = self;
request = [self.requestSerializer multipartFormRequestWithMethod:@"POST"
URLString:urlString
parameters:nil
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
request = [requestSerializer multipartFormRequestWithMethod:@"POST" URLString:urlString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formParams enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSString *objString = [weakSelf.sanitizer parameterToString:obj];
NSString *objString = [sanitizer parameterToString:obj];
NSData *data = [objString dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData:data name:key];
}];
@ -318,76 +198,73 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSURL *filePath = (NSURL *)obj;
[formData appendPartWithFileURL:filePath name:key error:nil];
}];
} error:nil];
} error:&requestCreateError];
}
else {
if (formParams) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:formParams
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:formParams error:&requestCreateError];
}
if (body) {
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
request = [requestSerializer requestWithMethod:method URLString:urlString parameters:body error:&requestCreateError];
}
}
// request cache
BOOL hasHeaderParams = [headerParams count] > 0;
if (offlineState) {
SWGDebugLog(@"%@ cache forced", resourcePath);
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
SWGDebugLog(@"%@ cache enabled", resourcePath);
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
}
else {
SWGDebugLog(@"%@ cache disabled", resourcePath);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
if(!request) {
completionBlock(nil, requestCreateError);
return nil;
}
if (hasHeaderParams){
if ([headerParams count] > 0){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
[self postProcessRequest:request];
NSNumber* requestId = [SWGApiClient queueRequest];
if ([responseType isEqualToString:@"NSURL*"] || [responseType isEqualToString:@"NSURL"]) {
[self downloadOperationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
NSURLSessionTask *task = nil;
if ([self.downloadTaskResponseTypes containsObject:responseType]) {
task = [self downloadTaskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
completionBlock(data, error);
}];
}
else {
[self operationWithCompletionBlock:request requestId:requestId completionBlock:^(id data, NSError *error) {
} else {
__weak typeof(self) weakSelf = self;
task = [self taskWithCompletionBlock:request completionBlock:^(id data, NSError *error) {
NSError * serializationError;
id response = [self.responseDeserializer deserialize:data class:responseType error:&serializationError];
id response = [weakSelf.responseDeserializer deserialize:data class:responseType error:&serializationError];
if(!response && !error){
error = serializationError;
}
completionBlock(response, error);
}];
}
return requestId;
[task resume];
return task;
}
-(AFHTTPRequestSerializer <AFURLRequestSerialization> *)requestSerializerForRequestContentType:(NSString *)requestContentType {
AFHTTPRequestSerializer <AFURLRequestSerialization> * serializer = self.requestSerializerForContentType[requestContentType];
if(!serializer) {
NSAssert(NO, @"Unsupported request content type %@", requestContentType);
serializer = [AFHTTPRequestSerializer serializer];
}
serializer.timeoutInterval = self.timeoutInterval;
return serializer;
}
//Added for easier override to modify request
-(void)postProcessRequest:(NSMutableURLRequest *)request {
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
}
#pragma mark -
- (NSString*) pathWithQueryParamsToString:(NSString*) path
queryParams:(NSDictionary*) queryParams {
- (NSString*) pathWithQueryParamsToString:(NSString*) path queryParams:(NSDictionary*) queryParams {
if(queryParams.count == 0) {
return path;
}
@ -445,9 +322,7 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
/**
* Update header and query params based on authentication settings
*/
- (void) updateHeaderParams:(NSDictionary *__autoreleasing *)headers
queryParams:(NSDictionary *__autoreleasing *)querys
WithAuthSettings:(NSArray *)authSettings {
- (void) updateHeaderParams:(NSDictionary * *)headers queryParams:(NSDictionary * *)querys WithAuthSettings:(NSArray *)authSettings {
if ([authSettings count] == 0) {
return;
@ -455,10 +330,11 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
NSMutableDictionary *headersWithAuth = [NSMutableDictionary dictionaryWithDictionary:*headers];
NSMutableDictionary *querysWithAuth = [NSMutableDictionary dictionaryWithDictionary:*querys];
NSDictionary* configurationAuthSettings = [[self configuration] authSettings];
id<SWGConfiguration> config = self.configuration;
for (NSString *auth in authSettings) {
NSDictionary *authSetting = configurationAuthSettings[auth];
NSDictionary *authSetting = config.authSettings[auth];
if(!authSetting) { // auth setting is set only if the key is non-empty
continue;
}
@ -476,14 +352,14 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
- (AFSecurityPolicy *) customSecurityPolicy {
- (AFSecurityPolicy *) createSecurityPolicy {
AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
SWGConfiguration *config = [self configuration];
id<SWGConfiguration> config = self.configuration;
if (config.sslCaCert) {
NSData *certData = [NSData dataWithContentsOfFile:config.sslCaCert];
[securityPolicy setPinnedCertificates:@[certData]];
[securityPolicy setPinnedCertificates:[NSSet setWithObject:certData]];
}
if (config.verifySSL) {
@ -497,8 +373,4 @@ static NSString * SWG__fileNameForResponse(NSURLResponse *response) {
return securityPolicy;
}
- (SWGConfiguration*) configuration {
return [SWGConfiguration sharedConfig];
}
@end

View File

@ -0,0 +1,14 @@
/** The `SWGBasicAuthTokenProvider` class creates a basic auth token from username and password.
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen
* Do not edit the class manually.
*/
#import <Foundation/Foundation.h>
@interface SWGBasicAuthTokenProvider : NSObject
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password;
@end

View File

@ -0,0 +1,19 @@
#import "SWGBasicAuthTokenProvider.h"
@implementation SWGBasicAuthTokenProvider
+ (NSString *)createBasicAuthTokenWithUsername:(NSString *)username password:(NSString *)password {
// return empty string if username and password are empty
if (username.length == 0 && password.length == 0){
return @"";
}
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", username, password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials;
}
@end

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#import "SWGApiClient.h"
#import "SWGLogger.h"
@class SWGLogger;
/**
* Swagger Petstore
@ -26,157 +26,75 @@
* limitations under the License.
*/
@class SWGApiClient;
static NSString * const kSWGAPIVersion = @"1.0.0";
@interface SWGConfiguration : NSObject
@protocol SWGConfiguration <NSObject>
/**
* Default api logger
* Api logger
*/
@property (nonatomic, strong) SWGLogger * logger;
@property (readonly, nonatomic) SWGLogger *logger;
/**
* Default api client
* Base url
*/
@property (nonatomic) SWGApiClient *apiClient;
/**
* Default base url
*/
@property (nonatomic) NSString *host;
@property (readonly, nonatomic) NSString *host;
/**
* Api key values for Api Key type Authentication
*
* To add or remove api key, use `setApiKey:forApiKeyIdentifier:`.
*/
@property (readonly, nonatomic, strong) NSDictionary *apiKey;
@property (readonly, nonatomic) NSDictionary *apiKey;
/**
* Api key prefix values to be prepend to the respective api key
*
* To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`.
*/
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
@property (readonly, nonatomic) NSDictionary *apiKeyPrefix;
/**
* Username for HTTP Basic Authentication
*/
@property (nonatomic) NSString *username;
@property (readonly, nonatomic) NSString *username;
/**
* Password for HTTP Basic Authentication
*/
@property (nonatomic) NSString *password;
@property (readonly, nonatomic) NSString *password;
/**
* Access token for OAuth
*/
@property (nonatomic) NSString *accessToken;
@property (readonly, nonatomic) NSString *accessToken;
/**
* Temp folder for file download
*/
@property (nonatomic) NSString *tempFolderPath;
@property (readonly, nonatomic) NSString *tempFolderPath;
/**
* Debug switch, default false
*/
@property (nonatomic) BOOL debug;
/**
* Gets configuration singleton instance
*/
+ (instancetype) sharedConfig;
@property (readonly, nonatomic) BOOL debug;
/**
* SSL/TLS verification
* Set this to NO to skip verifying SSL certificate when calling API from https server
*/
@property (nonatomic) BOOL verifySSL;
@property (readonly, nonatomic) BOOL verifySSL;
/**
* SSL/TLS verification
* Set this to customize the certificate file to verify the peer
*/
@property (nonatomic) NSString *sslCaCert;
@property (readonly, nonatomic) NSString *sslCaCert;
/**
* Sets API key
*
* To remove a apiKey for an identifier, just set the apiKey to nil.
*
* @param apiKey API key or token.
* @param identifier API key identifier (authentication schema).
*
* Authentication Settings
*/
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier;
/**
* Removes api key
*
* @param identifier API key identifier.
*/
- (void) removeApiKey:(NSString *)identifier;
/**
* Sets the prefix for API key
*
* @param apiKeyPrefix API key prefix.
* @param identifier API key identifier.
*/
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier;
/**
* Removes api key prefix
*
* @param identifier API key identifier.
*/
- (void) removeApiKeyPrefix:(NSString *)identifier;
/**
* Gets API key (with prefix if set)
*/
- (NSString *) getApiKeyWithPrefix:(NSString *) key;
/**
* Gets Basic Auth token
*/
- (NSString *) getBasicAuthToken;
/**
* Gets OAuth access token
*/
- (NSString *) getAccessToken;
/**
* Gets Authentication Settings
*/
- (NSDictionary *) authSettings;
@property (readonly, nonatomic) NSDictionary *authSettings;
/**
* Default headers for all services
*/
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
/**
* Removes header from defaultHeaders
*
* @param Header name.
*/
-(void) removeDefaultHeaderForKey:(NSString*)key;
/**
* Sets the header for key
*
* @param value Value for header name
* @param key Header name
*/
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
/**
* @param Header key name.
*/
-(NSString*) defaultHeaderForKey:(NSString*)key;
@end
@end

View File

@ -0,0 +1,177 @@
#import <Foundation/Foundation.h>
#import "SWGConfiguration.h"
/**
* Swagger Petstore
* This is a sample server Petstore server. You can find out more about Swagger at <a href=\"http://swagger.io\">http://swagger.io</a> or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters
*
* OpenAPI spec version: 1.0.0
* Contact: apiteam@wordnik.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@class SWGApiClient;
@interface SWGDefaultConfiguration : NSObject <SWGConfiguration>
/**
* Default api logger
*/
@property (nonatomic, strong) SWGLogger * logger;
/**
* Default base url
*/
@property (nonatomic) NSString *host;
/**
* Api key values for Api Key type Authentication
*
* To add or remove api key, use `setApiKey:forApiKeyIdentifier:`.
*/
@property (readonly, nonatomic, strong) NSDictionary *apiKey;
/**
* Api key prefix values to be prepend to the respective api key
*
* To add or remove prefix, use `setApiKeyPrefix:forApiKeyPrefixIdentifier:`.
*/
@property (readonly, nonatomic, strong) NSDictionary *apiKeyPrefix;
/**
* Username for HTTP Basic Authentication
*/
@property (nonatomic) NSString *username;
/**
* Password for HTTP Basic Authentication
*/
@property (nonatomic) NSString *password;
/**
* Access token for OAuth
*/
@property (nonatomic) NSString *accessToken;
/**
* Temp folder for file download
*/
@property (nonatomic) NSString *tempFolderPath;
/**
* Debug switch, default false
*/
@property (nonatomic) BOOL debug;
/**
* Gets configuration singleton instance
*/
+ (instancetype) sharedConfig;
/**
* SSL/TLS verification
* Set this to NO to skip verifying SSL certificate when calling API from https server
*/
@property (nonatomic) BOOL verifySSL;
/**
* SSL/TLS verification
* Set this to customize the certificate file to verify the peer
*/
@property (nonatomic) NSString *sslCaCert;
/**
* Sets API key
*
* To remove a apiKey for an identifier, just set the apiKey to nil.
*
* @param apiKey API key or token.
* @param identifier API key identifier (authentication schema).
*
*/
- (void) setApiKey:(NSString *)apiKey forApiKeyIdentifier:(NSString*)identifier;
/**
* Removes api key
*
* @param identifier API key identifier.
*/
- (void) removeApiKey:(NSString *)identifier;
/**
* Sets the prefix for API key
*
* @param apiKeyPrefix API key prefix.
* @param identifier API key identifier.
*/
- (void) setApiKeyPrefix:(NSString *)prefix forApiKeyPrefixIdentifier:(NSString *)identifier;
/**
* Removes api key prefix
*
* @param identifier API key identifier.
*/
- (void) removeApiKeyPrefix:(NSString *)identifier;
/**
* Gets API key (with prefix if set)
*/
- (NSString *) getApiKeyWithPrefix:(NSString *) key;
/**
* Gets Basic Auth token
*/
- (NSString *) getBasicAuthToken;
/**
* Gets OAuth access token
*/
- (NSString *) getAccessToken;
/**
* Gets Authentication Settings
*/
- (NSDictionary *) authSettings;
/**
* Default headers for all services
*/
@property (readonly, nonatomic, strong) NSDictionary *defaultHeaders;
/**
* Removes header from defaultHeaders
*
* @param Header name.
*/
-(void) removeDefaultHeaderForKey:(NSString*)key;
/**
* Sets the header for key
*
* @param value Value for header name
* @param key Header name
*/
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
/**
* @param Header key name.
*/
-(NSString*) defaultHeaderForKey:(NSString*)key;
@end

View File

@ -1,6 +1,8 @@
#import "SWGConfiguration.h"
#import "SWGDefaultConfiguration.h"
#import "SWGBasicAuthTokenProvider.h"
#import "SWGLogger.h"
@interface SWGConfiguration ()
@interface SWGDefaultConfiguration ()
@property (nonatomic, strong) NSMutableDictionary *mutableDefaultHeaders;
@property (nonatomic, strong) NSMutableDictionary *mutableApiKey;
@ -8,12 +10,12 @@
@end
@implementation SWGConfiguration
@implementation SWGDefaultConfiguration
#pragma mark - Singleton Methods
+ (instancetype) sharedConfig {
static SWGConfiguration *shardConfig = nil;
static SWGDefaultConfiguration *shardConfig = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
shardConfig = [[self alloc] init];
@ -26,17 +28,16 @@
- (instancetype) init {
self = [super init];
if (self) {
self.apiClient = nil;
self.host = @"http://petstore.swagger.io/v2";
self.username = @"";
self.password = @"";
self.accessToken= @"";
self.verifySSL = YES;
self.mutableApiKey = [NSMutableDictionary dictionary];
self.mutableApiKeyPrefix = [NSMutableDictionary dictionary];
self.mutableDefaultHeaders = [NSMutableDictionary dictionary];
self.mutableDefaultHeaders[@"User-Agent"] = [NSString stringWithFormat:@"Swagger-Codegen/1.0.0/objc (%@; iOS %@; Scale/%0.2f)",[[UIDevice currentDevice] model], [[UIDevice currentDevice] systemVersion], [[UIScreen mainScreen] scale]];
self.logger = [SWGLogger sharedLogger];
_host = @"http://petstore.swagger.io/v2";
_username = @"";
_password = @"";
_accessToken= @"";
_verifySSL = YES;
_mutableApiKey = [NSMutableDictionary dictionary];
_mutableApiKeyPrefix = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
_logger = [SWGLogger sharedLogger];
}
return self;
}
@ -58,16 +59,9 @@
}
- (NSString *) getBasicAuthToken {
// return empty string if username and password are empty
if (self.username.length == 0 && self.password.length == 0){
return @"";
}
NSString *basicAuthCredentials = [NSString stringWithFormat:@"%@:%@", self.username, self.password];
NSData *data = [basicAuthCredentials dataUsingEncoding:NSUTF8StringEncoding];
basicAuthCredentials = [NSString stringWithFormat:@"Basic %@", [data base64EncodedStringWithOptions:0]];
return basicAuthCredentials;
NSString *basicAuthToken = [SWGBasicAuthTokenProvider createBasicAuthTokenWithUsername:self.username password:self.password];
return basicAuthToken;
}
- (NSString *) getAccessToken {
@ -110,13 +104,6 @@
- (NSDictionary *) authSettings {
return @{
@"api_key":
@{
@"type": @"api_key",
@"in": @"header",
@"key": @"api_key",
@"value": [self getApiKeyWithPrefix:@"api_key"]
},
@"petstore_auth":
@{
@"type": @"oauth",
@ -124,6 +111,13 @@
@"key": @"Authorization",
@"value": [self getAccessToken]
},
@"api_key":
@{
@"type": @"api_key",
@"in": @"header",
@"key": @"api_key",
@"value": [self getApiKeyWithPrefix:@"api_key"]
},
};
}
@ -135,8 +129,6 @@
self.logger.enabled = debug;
}
- (void)setDefaultHeaderValue:(NSString *)value forKey:(NSString *)key {
if(!value) {
[self.mutableDefaultHeaders removeObjectForKey:key];

View File

@ -17,8 +17,7 @@
#pragma mark - Log Methods
- (void)debugLog:(NSString *)method
message:(NSString *)format, ... {
- (void)debugLog:(NSString *)method message:(NSString *)format, ... {
if (!self.isEnabled) {
return;
}

View File

@ -2,6 +2,35 @@
@implementation SWGObject
/**
* Workaround for JSONModel multithreading issues
* https://github.com/icanzilb/JSONModel/issues/441
*/
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)err {
static NSMutableSet *classNames;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
classNames = [NSMutableSet new];
});
BOOL initSync;
@synchronized([self class])
{
NSString *className = NSStringFromClass([self class]);
initSync = ![classNames containsObject:className];
if(initSync)
{
[classNames addObject:className];
self = [super initWithDictionary:dict error:err];
}
}
if(!initSync)
{
self = [super initWithDictionary:dict error:err];
}
return self;
}
/**
* Gets the string presentation of the object.
* This method will be called when logging model object using `NSLog`.

View File

@ -5,11 +5,15 @@
@synthesize values = _values;
@synthesize format = _format;
- (id) initWithValuesAndFormat: (NSArray*) values
format: (NSString*) format {
_values = values;
_format = format;
- (id)initWithValuesAndFormat:(NSArray *)values
format:(NSString *)format {
self = [super init];
if (self) {
_values = values;
_format = format;
}
return self;
}

View File

@ -16,6 +16,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
@property (nonatomic, strong) NSNumberFormatter* numberFormatter;
@property (nonatomic, strong) NSArray *primitiveTypes;
@property (nonatomic, strong) NSArray *basicReturnTypes;
@property (nonatomic, strong) NSArray *dataReturnTypes;
@property (nonatomic, strong) NSRegularExpression* arrayOfModelsPatExpression;
@property (nonatomic, strong) NSRegularExpression* arrayOfPrimitivesPatExpression;
@ -33,7 +34,9 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
formatter.numberStyle = NSNumberFormatterDecimalStyle;
_numberFormatter = formatter;
_primitiveTypes = @[@"NSString", @"NSDate", @"NSNumber"];
_basicReturnTypes = @[@"NSObject", @"id", @"NSData"];
_basicReturnTypes = @[@"NSObject", @"id"];
_dataReturnTypes = @[@"NSData"];
_arrayOfModelsPatExpression = [NSRegularExpression regularExpressionWithPattern:@"NSArray<(.+)>"
options:NSRegularExpressionCaseInsensitive
error:nil];
@ -53,23 +56,36 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
#pragma mark - Deserialize methods
- (id) deserialize:(id) data class:(NSString *) className error:(NSError **) error {
// return nil if data is nil or className is nil
if (!data || !className || [data isKindOfClass:[NSNull class]]) {
if (!data || !className) {
return nil;
}
// remove "*" from className, if ends with "*"
if ([className hasSuffix:@"*"]) {
className = [className substringToIndex:[className length] - 1];
}
if([self.dataReturnTypes containsObject:className]) {
return data;
}
id jsonData = nil;
if([data isKindOfClass:[NSData class]]) {
jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:error];
} else {
jsonData = data;
}
if(!jsonData) {
jsonData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
} else if([jsonData isKindOfClass:[NSNull class]]) {
return nil;
}
// pure object
if ([self.basicReturnTypes containsObject:className]) {
return data;
return jsonData;
}
// primitives
if ([self.primitiveTypes containsObject:className]) {
return [self deserializePrimitiveValue:data class:className error:error];
return [self deserializePrimitiveValue:jsonData class:className error:error];
}
NSTextCheckingResult *match = nil;
@ -78,37 +94,37 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
match = [self.arrayOfModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// list of primitives
match = [self.arrayOfPrimitivesPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *innerType = [className substringWithRange:[match rangeAtIndex:1]];
return [self deserializeArrayValue:data innerType:innerType error:error];
return [self deserializeArrayValue:jsonData innerType:innerType error:error];
}
// map
match = [self.dictPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
match = [self.dictModelsPatExpression firstMatchInString:className options:0 range:range];
if (match) {
NSString *valueType = [className substringWithRange:[match rangeAtIndex:2]];
return [self deserializeDictionaryValue:data valueType:valueType error:error];
return [self deserializeDictionaryValue:jsonData valueType:valueType error:error];
}
// model
Class ModelClass = NSClassFromString(className);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [(JSONModel *) [ModelClass alloc] initWithDictionary:data error:error];
return [(JSONModel *) [ModelClass alloc] initWithDictionary:jsonData error:error];
}
if(error) {
*error = [self unknownResponseErrorWithExpectedType:className data:data];
*error = [self unknownResponseErrorWithExpectedType:className data:jsonData];
}
return nil;
}
@ -172,7 +188,7 @@ NSInteger const SWGUnknownResponseObjectErrorCode = 143528;
- (id) deserializePrimitiveValue:(id) data class:(NSString *) className error:(NSError**)error {
if ([className isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
return [NSString stringWithFormat:@"%@",data];
}
else if ([className isEqualToString:@"NSDate"]) {
return [self deserializeDateValue:data error:error];

View File

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

View File

@ -3,6 +3,8 @@
#import "SWGQueryParamCollection.h"
#import <ISO8601/ISO8601.h>
NSString * const kSWGApplicationJSONType = @"application/json";
NSString * SWGPercentEscapedStringFromString(NSString *string) {
static NSString * const kSWGCharactersGeneralDelimitersToEncode = @":#[]@";
static NSString * const kSWGCharactersSubDelimitersToEncode = @"!$&'()*+,;=";
@ -43,8 +45,6 @@ NSString * SWGPercentEscapedStringFromString(NSString *string) {
@implementation SWGSanitizer
static NSString * kApplicationJSONType = @"application/json";
-(instancetype)init {
self = [super init];
if ( !self ) {
@ -141,7 +141,7 @@ static NSString * kApplicationJSONType = @"application/json";
NSMutableArray *lowerAccepts = [[NSMutableArray alloc] initWithCapacity:[accepts count]];
for (NSString *string in accepts) {
if ([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0) {
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
[lowerAccepts addObject:[string lowercaseString]];
}
@ -153,12 +153,12 @@ static NSString * kApplicationJSONType = @"application/json";
*/
- (NSString *) selectHeaderContentType:(NSArray *)contentTypes {
if (contentTypes.count == 0) {
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
NSMutableArray *lowerContentTypes = [[NSMutableArray alloc] initWithCapacity:[contentTypes count]];
for (NSString *string in contentTypes) {
if([self.jsonHeaderTypeExpression matchesInString:string options:0 range:NSMakeRange(0, [string length])].count > 0){
return kApplicationJSONType;
return kSWGApplicationJSONType;
}
[lowerContentTypes addObject:[string lowercaseString]];
}

View File

@ -32,6 +32,7 @@
if(!managedObject || !object) {
return;
}
NSManagedObjectContext* context = managedObject.managedObjectContext;
managedObject._id = [object._id copy];
managedObject.name = [object.name copy];

View File

@ -2,38 +2,38 @@
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="9525" systemVersion="15D21" minimumToolsVersion="Xcode 7.0">
<entity name="SWGCategoryManagedObject" representedClassName="SWGCategoryManagedObject" syncable="YES">
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="name" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="name" optional="YES" attributeType="String" syncable="YES"/>
</entity>
<entity name="SWGOrderManagedObject" representedClassName="SWGOrderManagedObject" syncable="YES">
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="petId" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="quantity" optional="YES" attributeType="Integer 16" syncable="YES"/>
<attribute name="shipDate" optional="YES" attributeType="Date" syncable="YES"/>
<attribute name="status" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="complete" optional="YES" attributeType="Boolean" syncable="YES"/>
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="petId" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="quantity" optional="YES" attributeType="Integer 16" syncable="YES"/>
<attribute name="shipDate" optional="YES" attributeType="Date" syncable="YES"/>
<attribute name="status" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="complete" optional="YES" attributeType="Boolean" syncable="YES"/>
</entity>
<entity name="SWGPetManagedObject" representedClassName="SWGPetManagedObject" syncable="YES">
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<relationship name="category" optional="YES" maxCount="1" deletionRule="Cascade" destinationEntity="SWGCategoryManagedObject" syncable="YES"/>
<attribute name="name" attributeType="String" syncable="YES"/>
<attribute name="photoUrls" attributeType="Transformable" syncable="YES"/>
<relationship name="tags" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="SWGTagManagedObject" syncable="YES"/>
<attribute name="status" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<relationship name="category" optional="YES" maxCount="1" deletionRule="Cascade" destinationEntity="SWGCategoryManagedObject" syncable="YES"/>
<attribute name="name" attributeType="String" syncable="YES"/>
<attribute name="photoUrls" attributeType="Transformable" syncable="YES"/>
<relationship name="tags" optional="YES" toMany="YES" ordered="YES" deletionRule="Cascade" destinationEntity="SWGTagManagedObject" syncable="YES"/>
<attribute name="status" optional="YES" attributeType="String" syncable="YES"/>
</entity>
<entity name="SWGTagManagedObject" representedClassName="SWGTagManagedObject" syncable="YES">
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="name" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="name" optional="YES" attributeType="String" syncable="YES"/>
</entity>
<entity name="SWGUserManagedObject" representedClassName="SWGUserManagedObject" syncable="YES">
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="username" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="firstName" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="lastName" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="email" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="password" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="phone" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="userStatus" optional="YES" attributeType="Integer 16" syncable="YES"/>
<attribute name="_id" optional="YES" attributeType="Double" syncable="YES"/>
<attribute name="username" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="firstName" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="lastName" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="email" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="password" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="phone" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="userStatus" optional="YES" attributeType="Integer 16" syncable="YES"/>
</entity>
</model>

View File

@ -32,6 +32,7 @@
if(!managedObject || !object) {
return;
}
NSManagedObjectContext* context = managedObject.managedObjectContext;
managedObject._id = [object._id copy];
managedObject.petId = [object.petId copy];
managedObject.quantity = [object.quantity copy];

View File

@ -42,7 +42,7 @@ NS_ASSUME_NONNULL_BEGIN
@property (nullable, nonatomic, retain) NSArray<NSString*>* photoUrls;
@property (nullable, nonatomic, retain) NSSet<SWGTagManagedObject*>* tags;
@property (nullable, nonatomic, retain) NSOrderedSet<SWGTagManagedObject*>* tags;
/* pet status in the store [optional]
*/
@property (nullable, nonatomic, retain) NSString* status;
@ -51,8 +51,8 @@ NS_ASSUME_NONNULL_BEGIN
@interface SWGPetManagedObject (GeneratedAccessors)
- (void)addTagsObject:(SWGTagManagedObject *)value;
- (void)removeTagsObject:(SWGTagManagedObject *)value;
- (void)addTags:(NSSet<SWGTagManagedObject*> *)values;
- (void)removeTags:(NSSet<SWGTagManagedObject*> *)values;
- (void)addTags:(NSOrderedSet<SWGTagManagedObject*> *)values;
- (void)removeTags:(NSOrderedSet<SWGTagManagedObject*> *)values;
@end

View File

@ -34,6 +34,7 @@
if(!managedObject || !object) {
return;
}
NSManagedObjectContext* context = managedObject.managedObjectContext;
managedObject._id = [object._id copy];
if(!managedObject.category) {
@ -43,8 +44,13 @@
}
managedObject.name = [object.name copy];
managedObject.photoUrls = [object.photoUrls copy];
if(managedObject.tags) {
for (id object in managedObject.tags) {
[context deleteObject:object];
}
}
if(object.tags) {
NSMutableSet * convertedObjs = [NSMutableSet set];
NSMutableOrderedSet * convertedObjs = [NSMutableOrderedSet orderedSet];
for (id innerObject in object.tags) {
id convertedObj = [self.tagsBuilder SWGTagManagedObjectFromSWGTag:innerObject context:managedObject.managedObjectContext];
[convertedObjs addObject:convertedObj];

View File

@ -32,6 +32,7 @@
if(!managedObject || !object) {
return;
}
NSManagedObjectContext* context = managedObject.managedObjectContext;
managedObject._id = [object._id copy];
managedObject.name = [object.name copy];

View File

@ -32,6 +32,7 @@
if(!managedObject || !object) {
return;
}
NSManagedObjectContext* context = managedObject.managedObjectContext;
managedObject._id = [object._id copy];
managedObject.username = [object.username copy];
managedObject.firstName = [object.firstName copy];

View File

@ -214,12 +214,13 @@
isa = PBXNativeTarget;
buildConfigurationList = 6003F5BF195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Example" */;
buildPhases = (
799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */,
799E7E29D924C30424DFBA28 /* [CP] Check Pods Manifest.lock */,
6003F586195388D20070C39A /* Sources */,
6003F587195388D20070C39A /* Frameworks */,
6003F588195388D20070C39A /* Resources */,
429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */,
183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */,
429AF5C69E165ED75311B4B0 /* [CP] Copy Pods Resources */,
183E54C09C54DAEB54B2546F /* [CP] Embed Pods Frameworks */,
FF3F107CF27E0A54D86C49F5 /* Embed Pods Frameworks */,
);
buildRules = (
);
@ -234,12 +235,13 @@
isa = PBXNativeTarget;
buildConfigurationList = 6003F5C2195388D20070C39A /* Build configuration list for PBXNativeTarget "SwaggerClient_Tests" */;
buildPhases = (
7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */,
7B069562A9F91E498732474F /* [CP] Check Pods Manifest.lock */,
6003F5AA195388D20070C39A /* Sources */,
6003F5AB195388D20070C39A /* Frameworks */,
6003F5AC195388D20070C39A /* Resources */,
E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */,
111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */,
E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */,
111D7956304BD6E860AA8709 /* [CP] Embed Pods Frameworks */,
AA7CAD658C61D6EBA222B5F8 /* Embed Pods Frameworks */,
);
buildRules = (
);
@ -258,7 +260,7 @@
isa = PBXProject;
attributes = {
CLASSPREFIX = SWG;
LastUpgradeCheck = 0510;
LastUpgradeCheck = 0730;
ORGANIZATIONNAME = geekerzp;
};
buildConfigurationList = 6003F585195388D10070C39A /* Build configuration list for PBXProject "SwaggerClient" */;
@ -303,14 +305,14 @@
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
111D7956304BD6E860AA8709 /* 📦 Embed Pods Frameworks */ = {
111D7956304BD6E860AA8709 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Embed Pods Frameworks";
name = "[CP] Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
@ -318,14 +320,14 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
183E54C09C54DAEB54B2546F /* 📦 Embed Pods Frameworks */ = {
183E54C09C54DAEB54B2546F /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Embed Pods Frameworks";
name = "[CP] Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
@ -333,14 +335,14 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
429AF5C69E165ED75311B4B0 /* 📦 Copy Pods Resources */ = {
429AF5C69E165ED75311B4B0 /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Copy Pods Resources";
name = "[CP] Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
@ -348,14 +350,14 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-resources.sh\"\n";
showEnvVarsInLog = 0;
};
799E7E29D924C30424DFBA28 /* 📦 Check Pods Manifest.lock */ = {
799E7E29D924C30424DFBA28 /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Check Pods Manifest.lock";
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
@ -363,14 +365,14 @@
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
7B069562A9F91E498732474F /* 📦 Check Pods Manifest.lock */ = {
7B069562A9F91E498732474F /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Check Pods Manifest.lock";
name = "[CP] Check Pods Manifest.lock";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
@ -378,14 +380,29 @@
shellScript = "diff \"${PODS_ROOT}/../Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [[ $? != 0 ]] ; then\n cat << EOM\nerror: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\nEOM\n exit 1\nfi\n";
showEnvVarsInLog = 0;
};
E337D7E459CCFFDF27046FFC /* 📦 Copy Pods Resources */ = {
AA7CAD658C61D6EBA222B5F8 /* Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "📦 Copy Pods Resources";
name = "Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
E337D7E459CCFFDF27046FFC /* [CP] Copy Pods Resources */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "[CP] Copy Pods Resources";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
@ -393,6 +410,21 @@
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Tests/Pods-SwaggerClient_Tests-resources.sh\"\n";
showEnvVarsInLog = 0;
};
FF3F107CF27E0A54D86C49F5 /* Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputPaths = (
);
name = "Embed Pods Frameworks";
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-SwaggerClient_Example/Pods-SwaggerClient_Example-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
@ -463,6 +495,7 @@
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
"CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer";
COPY_PHASE_STRIP = NO;
ENABLE_TESTABILITY = YES;
GCC_C_LANGUAGE_STANDARD = gnu99;
GCC_DYNAMIC_NO_PIC = NO;
GCC_OPTIMIZATION_LEVEL = 0;
@ -527,6 +560,7 @@
GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch";
INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist";
MODULE_NAME = ExampleApp;
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
};
@ -542,6 +576,7 @@
GCC_PREFIX_HEADER = "SwaggerClient/SwaggerClient-Prefix.pch";
INFOPLIST_FILE = "SwaggerClient/SwaggerClient-Info.plist";
MODULE_NAME = ExampleApp;
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = app;
};
@ -563,6 +598,7 @@
"$(inherited)",
);
INFOPLIST_FILE = "Tests/Tests-Info.plist";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = xctest;
};
@ -580,6 +616,7 @@
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "Tests/Tests-Prefix.pch";
INFOPLIST_FILE = "Tests/Tests-Info.plist";
PRODUCT_BUNDLE_IDENTIFIER = "org.cocoapods.demo.${PRODUCT_NAME:rfc1034identifier}";
PRODUCT_NAME = "$(TARGET_NAME)";
WRAPPER_EXTENSION = xctest;
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -6,6 +6,7 @@ This ObjC package is automatically generated by the [Swagger Codegen](https://gi
- API version: 1.0.0
- Package version:
- Build date: 2016-09-14T16:08:31.542+02:00
- Build package: class io.swagger.codegen.languages.ObjcClientCodegen
## Requirements
@ -39,7 +40,7 @@ Import the following:
```objc
#import <SwaggerClient/SWGApiClient.h>
#import <SwaggerClient/SWGConfiguration.h>
#import <SwaggerClient/SWGDefaultConfiguration.h>
// load models
#import <SwaggerClient/SWGCategory.h>
#import <SwaggerClient/SWGOrder.h>
@ -63,7 +64,7 @@ Please follow the [installation procedure](#installation--usage) and then run th
```objc
SWGConfiguration *apiConfig = [SWGConfiguration sharedConfig];
SWGDefaultConfiguration *apiConfig = [SWGDefaultConfiguration sharedConfig];
// Configure OAuth2 access token for authorization: (authentication scheme: petstore_auth)
[apiConfig setAccessToken:@"YOUR_ACCESS_TOKEN"];
@ -123,12 +124,6 @@ Class | Method | HTTP request | Description
## Documentation For Authorization
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## petstore_auth
- **Type**: OAuth
@ -138,6 +133,12 @@ Class | Method | HTTP request | Description
- **write:pets**: modify pets in your account
- **read:pets**: read your pets
## api_key
- **Type**: API key
- **API key parameter name**: api_key
- **Location**: HTTP header
## Author

View File

@ -32,6 +32,6 @@ Pod::Spec.new do |s|
s.dependency 'AFNetworking', '~> 3'
s.dependency 'JSONModel', '~> 1.2'
s.dependency 'ISO8601', '~> 0.5'
s.dependency 'ISO8601', '~> 0.6'
end

View File

@ -32,7 +32,7 @@
extern NSString* kSWGPetApiErrorDomain;
extern NSInteger kSWGPetApiMissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
/// Add a new pet to the store
///
@ -42,7 +42,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:405 message:"Invalid input"
///
/// @return
-(NSNumber*) addPetWithBody: (SWGPet*) body
-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -55,7 +55,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:400 message:"Invalid pet value"
///
/// @return
-(NSNumber*) deletePetWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId
apiKey: (NSString*) apiKey
completionHandler: (void (^)(NSError* error)) handler;
@ -69,7 +69,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:400 message:"Invalid status value"
///
/// @return NSArray<SWGPet>*
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler;
@ -82,7 +82,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:400 message:"Invalid tag value"
///
/// @return NSArray<SWGPet>*
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler;
@ -96,7 +96,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:404 message:"Pet not found"
///
/// @return SWGPet*
-(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error)) handler;
@ -110,7 +110,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:405 message:"Validation exception"
///
/// @return
-(NSNumber*) updatePetWithBody: (SWGPet*) body
-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -124,7 +124,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:405 message:"Invalid input"
///
/// @return
-(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId
-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId
name: (NSString*) name
status: (NSString*) status
completionHandler: (void (^)(NSError* error)) handler;
@ -140,7 +140,7 @@ extern NSInteger kSWGPetApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) uploadFileWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata
file: (NSURL*) file
completionHandler: (void (^)(NSError* error)) handler;

View File

@ -1,11 +1,12 @@
#import "SWGPetApi.h"
#import "SWGQueryParamCollection.h"
#import "SWGApiClient.h"
#import "SWGPet.h"
@interface SWGPetApi ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -19,52 +20,31 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
SWGConfiguration *config = [SWGConfiguration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[SWGApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[SWGApiClient sharedClient]];
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static SWGPetApi *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [SWGApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -76,7 +56,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) addPetWithBody: (SWGPet*) body
-(NSURLSessionTask*) addPetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"];
@ -124,8 +104,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -137,7 +116,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) deletePetWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) deletePetWithPetId: (NSNumber*) petId
apiKey: (NSString*) apiKey
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'petId' is set
@ -202,8 +181,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -213,7 +191,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns NSArray<SWGPet>*
///
-(NSNumber*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
-(NSURLSessionTask*) findPetsByStatusWithStatus: (NSArray<NSString*>*) status
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByStatus"];
@ -264,8 +242,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)data, error);
}
}
];
}];
}
///
@ -275,7 +252,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns NSArray<SWGPet>*
///
-(NSNumber*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
-(NSURLSessionTask*) findPetsByTagsWithTags: (NSArray<NSString*>*) tags
completionHandler: (void (^)(NSArray<SWGPet>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet/findByTags"];
@ -326,8 +303,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSArray<SWGPet>*)data, error);
}
}
];
}];
}
///
@ -337,7 +313,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns SWGPet*
///
-(NSNumber*) getPetByIdWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) getPetByIdWithPetId: (NSNumber*) petId
completionHandler: (void (^)(SWGPet* output, NSError* error)) handler {
// verify the required parameter 'petId' is set
if (petId == nil) {
@ -376,7 +352,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
NSString *requestContentType = [self.apiClient.sanitizer selectHeaderContentType:@[]];
// Authentication setting
NSArray *authSettings = @[@"api_key", @"petstore_auth"];
NSArray *authSettings = @[@"petstore_auth", @"api_key"];
id bodyParam = nil;
NSMutableDictionary *formParams = [[NSMutableDictionary alloc] init];
@ -398,8 +374,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGPet*)data, error);
}
}
];
}];
}
///
@ -409,7 +384,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) updatePetWithBody: (SWGPet*) body
-(NSURLSessionTask*) updatePetWithBody: (SWGPet*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/pet"];
@ -457,8 +432,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -472,7 +446,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) updatePetWithFormWithPetId: (NSString*) petId
-(NSURLSessionTask*) updatePetWithFormWithPetId: (NSString*) petId
name: (NSString*) name
status: (NSString*) status
completionHandler: (void (^)(NSError* error)) handler {
@ -541,8 +515,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -556,7 +529,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) uploadFileWithPetId: (NSNumber*) petId
-(NSURLSessionTask*) uploadFileWithPetId: (NSNumber*) petId
additionalMetadata: (NSString*) additionalMetadata
file: (NSURL*) file
completionHandler: (void (^)(NSError* error)) handler {
@ -623,8 +596,7 @@ NSInteger kSWGPetApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}

View File

@ -32,7 +32,7 @@
extern NSString* kSWGStoreApiErrorDomain;
extern NSInteger kSWGStoreApiMissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
/// Delete purchase order by ID
/// For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors
@ -43,7 +43,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:404 message:"Order not found"
///
/// @return
-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId
completionHandler: (void (^)(NSError* error)) handler;
@ -54,7 +54,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:200 message:"successful operation"
///
/// @return NSDictionary<NSString*, NSNumber*>*
-(NSNumber*) getInventoryWithCompletionHandler:
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* output, NSError* error)) handler;
@ -68,7 +68,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:404 message:"Order not found"
///
/// @return SWGOrder*
-(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler;
@ -81,7 +81,7 @@ extern NSInteger kSWGStoreApiMissingParamErrorCode;
/// code:400 message:"Invalid Order"
///
/// @return SWGOrder*
-(NSNumber*) placeOrderWithBody: (SWGOrder*) body
-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler;

View File

@ -1,11 +1,12 @@
#import "SWGStoreApi.h"
#import "SWGQueryParamCollection.h"
#import "SWGApiClient.h"
#import "SWGOrder.h"
@interface SWGStoreApi ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -19,52 +20,31 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
SWGConfiguration *config = [SWGConfiguration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[SWGApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[SWGApiClient sharedClient]];
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static SWGStoreApi *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [SWGApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -76,7 +56,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) deleteOrderWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) deleteOrderWithOrderId: (NSString*) orderId
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'orderId' is set
if (orderId == nil) {
@ -137,8 +117,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -146,7 +125,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
/// Returns a map of status codes to quantities
/// @returns NSDictionary<NSString*, NSNumber*>*
///
-(NSNumber*) getInventoryWithCompletionHandler:
-(NSURLSessionTask*) getInventoryWithCompletionHandler:
(void (^)(NSDictionary<NSString*, NSNumber*>* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/inventory"];
@ -193,8 +172,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSDictionary<NSString*, NSNumber*>*)data, error);
}
}
];
}];
}
///
@ -204,7 +182,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
///
/// @returns SWGOrder*
///
-(NSNumber*) getOrderByIdWithOrderId: (NSString*) orderId
-(NSURLSessionTask*) getOrderByIdWithOrderId: (NSString*) orderId
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler {
// verify the required parameter 'orderId' is set
if (orderId == nil) {
@ -265,8 +243,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGOrder*)data, error);
}
}
];
}];
}
///
@ -276,7 +253,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
///
/// @returns SWGOrder*
///
-(NSNumber*) placeOrderWithBody: (SWGOrder*) body
-(NSURLSessionTask*) placeOrderWithBody: (SWGOrder*) body
completionHandler: (void (^)(SWGOrder* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/store/order"];
@ -324,8 +301,7 @@ NSInteger kSWGStoreApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGOrder*)data, error);
}
}
];
}];
}

View File

@ -32,7 +32,7 @@
extern NSString* kSWGUserApiErrorDomain;
extern NSInteger kSWGUserApiMissingParamErrorCode;
+(instancetype) sharedAPI;
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient NS_DESIGNATED_INITIALIZER;
/// Create user
/// This can only be done by the logged in user.
@ -42,7 +42,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) createUserWithBody: (SWGUser*) body
-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -54,7 +54,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -66,7 +66,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler;
@ -79,7 +79,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:404 message:"User not found"
///
/// @return
-(NSNumber*) deleteUserWithUsername: (NSString*) username
-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username
completionHandler: (void (^)(NSError* error)) handler;
@ -93,7 +93,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:404 message:"User not found"
///
/// @return SWGUser*
-(NSNumber*) getUserByNameWithUsername: (NSString*) username
-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error)) handler;
@ -107,7 +107,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:400 message:"Invalid username/password supplied"
///
/// @return NSString*
-(NSNumber*) loginUserWithUsername: (NSString*) username
-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username
password: (NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error)) handler;
@ -119,7 +119,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:0 message:"successful operation"
///
/// @return
-(NSNumber*) logoutUserWithCompletionHandler:
-(NSURLSessionTask*) logoutUserWithCompletionHandler:
(void (^)(NSError* error)) handler;
@ -133,7 +133,7 @@ extern NSInteger kSWGUserApiMissingParamErrorCode;
/// code:404 message:"User not found"
///
/// @return
-(NSNumber*) updateUserWithUsername: (NSString*) username
-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username
body: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler;

View File

@ -1,11 +1,12 @@
#import "SWGUserApi.h"
#import "SWGQueryParamCollection.h"
#import "SWGApiClient.h"
#import "SWGUser.h"
@interface SWGUserApi ()
@property (nonatomic, strong) NSMutableDictionary *defaultHeaders;
@property (nonatomic, strong, readwrite) NSMutableDictionary *mutableDefaultHeaders;
@end
@ -19,52 +20,31 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
#pragma mark - Initialize methods
- (instancetype) init {
self = [super init];
if (self) {
SWGConfiguration *config = [SWGConfiguration sharedConfig];
if (config.apiClient == nil) {
config.apiClient = [[SWGApiClient alloc] init];
}
_apiClient = config.apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
}
return self;
return [self initWithApiClient:[SWGApiClient sharedClient]];
}
- (id) initWithApiClient:(SWGApiClient *)apiClient {
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient {
self = [super init];
if (self) {
_apiClient = apiClient;
_defaultHeaders = [NSMutableDictionary dictionary];
_mutableDefaultHeaders = [NSMutableDictionary dictionary];
}
return self;
}
#pragma mark -
+ (instancetype)sharedAPI {
static SWGUserApi *sharedAPI;
static dispatch_once_t once;
dispatch_once(&once, ^{
sharedAPI = [[self alloc] init];
});
return sharedAPI;
}
-(NSString*) defaultHeaderForKey:(NSString*)key {
return self.defaultHeaders[key];
}
-(void) addHeader:(NSString*)value forKey:(NSString*)key {
[self setDefaultHeaderValue:value forKey:key];
return self.mutableDefaultHeaders[key];
}
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key {
[self.defaultHeaders setValue:value forKey:key];
[self.mutableDefaultHeaders setValue:value forKey:key];
}
-(NSUInteger) requestQueueSize {
return [SWGApiClient requestQueueSize];
-(NSDictionary *)defaultHeaders {
return self.mutableDefaultHeaders;
}
#pragma mark - Api Methods
@ -76,7 +56,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) createUserWithBody: (SWGUser*) body
-(NSURLSessionTask*) createUserWithBody: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user"];
@ -124,8 +104,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -135,7 +114,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithArrayInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithArray"];
@ -183,8 +162,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -194,7 +172,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
-(NSURLSessionTask*) createUsersWithListInputWithBody: (NSArray<SWGUser>*) body
completionHandler: (void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/createWithList"];
@ -242,8 +220,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -253,7 +230,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) deleteUserWithUsername: (NSString*) username
-(NSURLSessionTask*) deleteUserWithUsername: (NSString*) username
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'username' is set
if (username == nil) {
@ -314,8 +291,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -325,7 +301,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns SWGUser*
///
-(NSNumber*) getUserByNameWithUsername: (NSString*) username
-(NSURLSessionTask*) getUserByNameWithUsername: (NSString*) username
completionHandler: (void (^)(SWGUser* output, NSError* error)) handler {
// verify the required parameter 'username' is set
if (username == nil) {
@ -386,8 +362,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler((SWGUser*)data, error);
}
}
];
}];
}
///
@ -399,7 +374,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns NSString*
///
-(NSNumber*) loginUserWithUsername: (NSString*) username
-(NSURLSessionTask*) loginUserWithUsername: (NSString*) username
password: (NSString*) password
completionHandler: (void (^)(NSString* output, NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/login"];
@ -453,8 +428,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler((NSString*)data, error);
}
}
];
}];
}
///
@ -462,7 +436,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) logoutUserWithCompletionHandler:
-(NSURLSessionTask*) logoutUserWithCompletionHandler:
(void (^)(NSError* error)) handler {
NSMutableString* resourcePath = [NSMutableString stringWithFormat:@"/user/logout"];
@ -509,8 +483,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}
///
@ -522,7 +495,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
///
/// @returns void
///
-(NSNumber*) updateUserWithUsername: (NSString*) username
-(NSURLSessionTask*) updateUserWithUsername: (NSString*) username
body: (SWGUser*) body
completionHandler: (void (^)(NSError* error)) handler {
// verify the required parameter 'username' is set
@ -585,8 +558,7 @@ NSInteger kSWGUserApiMissingParamErrorCode = 234513;
if(handler) {
handler(error);
}
}
];
}];
}

View File

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

View File

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

View File

@ -1,6 +1,6 @@
#import <Foundation/Foundation.h>
#import "SWGObject.h"
#import "SWGApiClient.h"
@class SWGApiClient;
/**
* Swagger Petstore
@ -28,15 +28,13 @@
@protocol SWGApi <NSObject>
@property(nonatomic, assign) SWGApiClient *apiClient;
@property(readonly, nonatomic, strong) SWGApiClient *apiClient;
-(id) initWithApiClient:(SWGApiClient *)apiClient;
-(void) addHeader:(NSString*)value forKey:(NSString*)key DEPRECATED_MSG_ATTRIBUTE("setDefaultHeaderValue:forKey:");
-(instancetype) initWithApiClient:(SWGApiClient *)apiClient;
-(void) setDefaultHeaderValue:(NSString*) value forKey:(NSString*)key;
-(NSString*) defaultHeaderForKey:(NSString*)key;
-(NSUInteger) requestQueueSize;
-(NSDictionary *)defaultHeaders;
@end

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