Merge branch 'develop_2.0' of https://github.com/swagger-api/swagger-codegen into develop_2.0-fork

This commit is contained in:
Raghav Sidhanti
2015-06-24 11:25:32 -07:00
106 changed files with 5291 additions and 3581 deletions

View File

@@ -145,6 +145,10 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig {
// replace - with _ e.g. created-at => created_at
name = name.replaceAll("-", "_");
if("_".equals(name)) {
name = "_u";
}
// if it's all uppper case, do nothing
if (name.matches("^[A-Z_]*$")) {
return name;

View File

@@ -143,8 +143,10 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("SWGObject.m", sourceFolder, "SWGObject.m"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.h", sourceFolder, "SWGQueryParamCollection.h"));
supportingFiles.add(new SupportingFile("SWGQueryParamCollection.m", sourceFolder, "SWGQueryParamCollection.m"));
supportingFiles.add(new SupportingFile("SWGApiClient.h", sourceFolder, "SWGApiClient.h"));
supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m"));
supportingFiles.add(new SupportingFile("SWGApiClient-header.mustache", sourceFolder, "SWGApiClient.h"));
supportingFiles.add(new SupportingFile("SWGApiClient-body.mustache", sourceFolder, "SWGApiClient.m"));
supportingFiles.add(new SupportingFile("SWGJSONResponseSerializer-header.mustache", sourceFolder, "SWGJSONResponseSerializer.h"));
supportingFiles.add(new SupportingFile("SWGJSONResponseSerializer-body.mustache", sourceFolder, "SWGJSONResponseSerializer.m"));
supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h"));
supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m"));
supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m"));
@@ -215,6 +217,16 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig {
}
return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
String innerTypeDeclaration = getTypeDeclaration(inner);
if (innerTypeDeclaration.endsWith("*")) {
innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1);
}
return getSwaggerType(p) + "* /* NSString, " + innerTypeDeclaration + " */";
} else {
String swaggerType = getSwaggerType(p);

View File

@@ -7,16 +7,16 @@ import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.codegen.CliOption;
import java.io.File;
import java.util.Arrays;
import java.util.HashSet;
public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "SwaggerClient";
protected String groupId = "io.swagger";
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
protected String moduleName = "SwaggerClient";
protected String moduleVersion = "1.0.0";
public PerlClientCodegen() {
super();
@@ -26,8 +26,6 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
apiTemplateFiles.put("api.mustache", ".pm");
templateDir = "perl";
typeMapping.clear();
languageSpecificPrimitives.clear();
reservedWords = new HashSet<String>(
Arrays.asList(
@@ -44,11 +42,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
)
);
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
languageSpecificPrimitives.clear();
languageSpecificPrimitives.add("int");
languageSpecificPrimitives.add("double");
languageSpecificPrimitives.add("string");
@@ -58,6 +52,7 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
languageSpecificPrimitives.add("HASH");
languageSpecificPrimitives.add("object");
typeMapping.clear();
typeMapping.put("integer", "int");
typeMapping.put("long", "int");
typeMapping.put("float", "double");
@@ -71,9 +66,31 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("map", "HASH");
typeMapping.put("object", "object");
supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "ApiClient.pm"));
supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Configuration.pm"));
supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + invokerPackage).replace('/', File.separatorChar), "Object/BaseObject.pm"));
cliOptions.clear();
cliOptions.add(new CliOption("moduleName", "perl module name (convention: CamelCase), default: SwaggerClient"));
cliOptions.add(new CliOption("moduleVersion", "perl module version, default: 1.0.0"));
}
@Override
public void processOpts() {
super.processOpts();
if (additionalProperties.containsKey("moduleVersion")) {
moduleVersion = (String) additionalProperties.get("moduleVersion");
} else {
additionalProperties.put("moduleVersion", moduleVersion);
}
if (additionalProperties.containsKey("moduleName")) {
moduleName = (String) additionalProperties.get("moduleName");
} else {
additionalProperties.put("moduleName", moduleName);
}
supportingFiles.add(new SupportingFile("ApiClient.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "ApiClient.pm"));
supportingFiles.add(new SupportingFile("Configuration.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Configuration.pm"));
supportingFiles.add(new SupportingFile("BaseObject.mustache", ("lib/WWW/" + moduleName).replace('/', File.separatorChar), "Object/BaseObject.pm"));
}
public CodegenType getTag() {
@@ -95,11 +112,11 @@ public class PerlClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String apiFileFolder() {
return (outputFolder + "/lib/WWW/" + invokerPackage + apiPackage()).replace('/', File.separatorChar);
return (outputFolder + "/lib/WWW/" + moduleName + apiPackage()).replace('/', File.separatorChar);
}
public String modelFileFolder() {
return (outputFolder + "/lib/WWW/" + invokerPackage + modelPackage()).replace('/', File.separatorChar);
return (outputFolder + "/lib/WWW/" + moduleName + modelPackage()).replace('/', File.separatorChar);
}
@Override

View File

@@ -7,6 +7,7 @@ import io.swagger.codegen.SupportingFile;
import io.swagger.models.properties.ArrayProperty;
import io.swagger.models.properties.MapProperty;
import io.swagger.models.properties.Property;
import io.swagger.models.properties.RefProperty;
import java.io.File;
import java.util.Arrays;
@@ -14,24 +15,20 @@ import java.util.HashMap;
import java.util.HashSet;
public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
protected String invokerPackage = "io.swagger.client";
protected String groupId = "io.swagger";
protected String invokerPackage = "Swagger\\Client";
protected String groupId = "swagger";
protected String artifactId = "swagger-client";
protected String artifactVersion = "1.0.0";
protected String artifactVersion = null;
public PhpClientCodegen() {
super();
invokerPackage = camelize("SwaggerClient");
String packagePath = invokerPackage + "-php";
modelPackage = packagePath + "/lib/models";
apiPackage = packagePath + "/lib";
outputFolder = "generated-code/php";
modelTemplateFiles.put("model.mustache", ".php");
apiTemplateFiles.put("api.mustache", ".php");
templateDir = "php";
apiPackage = invokerPackage + "\\Api";
modelPackage = invokerPackage + "\\Model";
reservedWords = new HashSet<String>(
Arrays.asList(
@@ -39,6 +36,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
);
additionalProperties.put("invokerPackage", invokerPackage);
additionalProperties.put("modelPackage", modelPackage);
additionalProperties.put("apiPackage", apiPackage);
additionalProperties.put("escapedInvokerPackage", invokerPackage.replace("\\", "\\\\"));
additionalProperties.put("groupId", groupId);
additionalProperties.put("artifactId", artifactId);
additionalProperties.put("artifactVersion", artifactVersion);
@@ -46,6 +46,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
// ref: http://php.net/manual/en/language.types.intro.php
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"bool",
"boolean",
"int",
"integer",
@@ -55,7 +56,9 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
"object",
"DateTime",
"mixed",
"number")
"number",
"void",
"byte")
);
instantiationTypes.put("array", "array");
@@ -69,20 +72,40 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
typeMapping.put("double", "double");
typeMapping.put("string", "string");
typeMapping.put("byte", "int");
typeMapping.put("boolean", "boolean");
typeMapping.put("date", "DateTime");
typeMapping.put("datetime", "DateTime");
typeMapping.put("boolean", "bool");
typeMapping.put("date", "\\DateTime");
typeMapping.put("datetime", "\\DateTime");
typeMapping.put("file", "string");
typeMapping.put("map", "map");
typeMapping.put("array", "array");
typeMapping.put("list", "array");
typeMapping.put("object", "object");
typeMapping.put("DateTime", "\\DateTime");
supportingFiles.add(new SupportingFile("composer.mustache", packagePath.replace('/', File.separatorChar), "composer.json"));
supportingFiles.add(new SupportingFile("configuration.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "Configuration.php"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiClient.php"));
supportingFiles.add(new SupportingFile("ApiException.mustache", (packagePath + "/lib").replace('/', File.separatorChar), "ApiException.php"));
supportingFiles.add(new SupportingFile("require.mustache", packagePath.replace('/', File.separatorChar), invokerPackage + ".php"));
supportingFiles.add(new SupportingFile("composer.mustache", getPackagePath(), "composer.json"));
supportingFiles.add(new SupportingFile("configuration.mustache", toPackagePath(invokerPackage, "lib"), "Configuration.php"));
supportingFiles.add(new SupportingFile("ApiClient.mustache", toPackagePath(invokerPackage, "lib"), "ApiClient.php"));
supportingFiles.add(new SupportingFile("ApiException.mustache", toPackagePath(invokerPackage, "lib"), "ApiException.php"));
supportingFiles.add(new SupportingFile("autoload.mustache", getPackagePath(), "autoload.php"));
}
public String getPackagePath() {
return "SwaggerClient-php";
}
public String toPackagePath(String packageName, String basePath) {
packageName = packageName.replace(invokerPackage, "");
if (basePath != null && basePath.length() > 0) {
basePath = basePath.replaceAll("[\\\\/]?$", "") + File.separatorChar;
}
return (getPackagePath() + File.separatorChar + basePath
// Replace period, backslash, forward slash with file separator in package name
+ packageName.replaceAll("[\\.\\\\/]", File.separator)
// Trim prefix file separators from package path
.replaceAll("^" + File.separator, ""))
// Trim trailing file separators from the overall path
.replaceAll(File.separator + "$", "");
}
public CodegenType getTag() {
@@ -104,11 +127,11 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
@Override
public String apiFileFolder() {
return (outputFolder + "/" + apiPackage()).replace('/', File.separatorChar);
return (outputFolder + "/" + toPackagePath(apiPackage(), "lib"));
}
public String modelFileFolder() {
return (outputFolder + "/" + modelPackage()).replace('/', File.separatorChar);
return (outputFolder + "/" + toPackagePath(modelPackage(), "lib"));
}
@Override
@@ -116,15 +139,27 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
return getTypeDeclaration(inner) + "[]";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
} else if (p instanceof RefProperty) {
String type = super.getTypeDeclaration(p);
return (!languageSpecificPrimitives.contains(type))
? "\\" + modelPackage + "\\" + type : type;
}
return super.getTypeDeclaration(p);
}
@Override
public String getTypeDeclaration(String name) {
if (!languageSpecificPrimitives.contains(name)) {
return "\\" + modelPackage + "\\" + name;
}
return super.getTypeDeclaration(name);
}
@Override
public String getSwaggerType(Property p) {
String swaggerType = super.getSwaggerType(p);

View File

@@ -46,12 +46,21 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
languageSpecificPrimitives.add("string");
languageSpecificPrimitives.add("DateTime");
typeMapping.put("long", "int");
typeMapping.put("integer", "int");
typeMapping.put("Array", "array");
typeMapping.put("String", "string");
typeMapping.put("List", "array");
typeMapping.put("map", "map");
typeMapping.put("string", "String");
typeMapping.put("char", "String");
typeMapping.put("int", "Integer");
typeMapping.put("integer", "Integer");
typeMapping.put("long", "Integer");
typeMapping.put("short", "Integer");
typeMapping.put("float", "Float");
typeMapping.put("double", "Float");
typeMapping.put("number", "Float");
typeMapping.put("DateTime", "DateTime");
typeMapping.put("boolean", "BOOLEAN");
typeMapping.put("array", "Array");
typeMapping.put("List", "Array");
typeMapping.put("map", "Hash");
typeMapping.put("object", "Object");
// remove modelPackage and apiPackage added by default
cliOptions.clear();
@@ -102,6 +111,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
String swaggerFolder = baseFolder + File.separator + "swagger";
supportingFiles.add(new SupportingFile("swagger" + File.separator + "request.mustache", swaggerFolder, "request.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "response.mustache", swaggerFolder, "response.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "api_error.mustache", swaggerFolder, "api_error.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "version.mustache", swaggerFolder, "version.rb"));
supportingFiles.add(new SupportingFile("swagger" + File.separator + "configuration.mustache", swaggerFolder, "configuration.rb"));
String modelFolder = baseFolder + File.separator + modelPackage.replace("/", File.separator);
@@ -153,11 +163,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig {
if (p instanceof ArrayProperty) {
ArrayProperty ap = (ArrayProperty) p;
Property inner = ap.getItems();
return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]";
return getSwaggerType(p) + "<" + getTypeDeclaration(inner) + ">";
} else if (p instanceof MapProperty) {
MapProperty mp = (MapProperty) p;
Property inner = mp.getAdditionalProperties();
return getSwaggerType(p) + "[string," + getTypeDeclaration(inner) + "]";
return getSwaggerType(p) + "<String, " + getTypeDeclaration(inner) + ">";
}
return super.getTypeDeclaration(p);
}

View File

@@ -351,179 +351,139 @@ static bool loggingEnabled = true;
*querys = [NSDictionary dictionaryWithDictionary:querysWithAuth];
}
#pragma mark - Perform Request Methods
#pragma mark - Deserialize methods
-(NSNumber*) dictionary: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSDictionary*, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [AFJSONRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"application/x-www-form-urlencoded"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else if ([requestContentType isEqualToString:@"multipart/form-data"]) {
self.requestSerializer = [AFHTTPRequestSerializer serializer];
}
else {
NSAssert(false, @"unsupport request type %@", requestContentType);
- (id) deserialize:(id) data class:(NSString *) class {
NSRegularExpression *regexp = nil;
NSTextCheckingResult *match = nil;
NSMutableArray *resultArray = nil;
NSMutableDictionary *resultDict = nil;
// return nil if data is nil
if (!data) {
return nil;
}
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
// remove "*" from class, if ends with "*"
if ([class hasSuffix:@"*"]) {
class = [class substringToIndex:[class length] - 1];
}
else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
// pure object
if ([class isEqualToString:@"NSObject"]) {
return [[NSObject alloc] init];
}
// list of models
NSString *arrayOfModelsPat = @"NSArray<(.+)>";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfModelsPat
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
NSString *innerType = [class substringWithRange:[match rangeAtIndex:1]];
resultArray = [NSMutableArray arrayWithCapacity:[data count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:innerType]];
}
];
return resultArray;
}
// list of primitives
NSString *arrayOfPrimitivesPet = @"NSArray";
regexp = [NSRegularExpression regularExpressionWithPattern:arrayOfPrimitivesPet
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
resultArray = [NSMutableArray arrayWithCapacity:[data count]];
[data enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[resultArray addObject:[self deserialize:obj class:NSStringFromClass([obj class])]];
}];
return resultArray;
}
// map
NSString *dictPat = @"NSDictionary\\* /\\* (.+), (.+) \\*/";
regexp = [NSRegularExpression regularExpressionWithPattern:dictPat
options:NSRegularExpressionCaseInsensitive
error:nil];
match = [regexp firstMatchInString:class
options:0
range:NSMakeRange(0, [class length])];
if (match) {
NSString *valueType = [class substringWithRange:[match rangeAtIndex:2]];
resultDict = [NSMutableDictionary dictionaryWithCapacity:[data count]];
[data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
[resultDict setValue:[self deserialize:obj class:valueType] forKey:key];
}];
return resultDict;
}
// auth setting
[self updateHeaderParams:&headerParams queryParams:&queryParams WithAuthSettings:authSettings];
// primitives
NSArray *primitiveTypes = @[@"NSString", @"NSDate", @"BOOL", @"NSNumber"];
NSMutableURLRequest * request = nil;
if (body != nil && [body isKindOfClass:[NSArray class]]){
SWGFile * file;
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
for(id obj in body) {
if([obj isKindOfClass:[SWGFile class]]) {
file = (SWGFile*) obj;
requestContentType = @"multipart/form-data";
if ([primitiveTypes containsObject:class]) {
if ([class isEqualToString:@"NSString"]) {
return [NSString stringWithString:data];
}
else if ([class isEqualToString:@"NSDate"]) {
return [NSDate dateWithISO8601String:data];
}
else if ([class isEqualToString:@"BOOL"]) {
// Returns YES on encountering one of "Y", "y", "T", "t", or a
// digit 1-9—the method ignores any trailing characters
// NSString => BOOL => NSNumber
return [NSNumber numberWithBool:[data boolValue]];
}
else if ([class isEqualToString:@"NSNumber"]) {
// NSNumber from NSNumber
if ([data isKindOfClass:[NSNumber class]]) {
return data;
}
else if([obj isKindOfClass:[NSDictionary class]]) {
for(NSString * key in obj) {
params[key] = obj[key];
}
// NSNumber from NSString
else {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
return [formatter numberFromString:data];
}
}
NSString * urlString = [[NSURL URLWithString:path relativeToURL:self.baseURL] absoluteString];
// request with multipart form
if([requestContentType isEqualToString:@"multipart/form-data"]) {
request = [self.requestSerializer multipartFormRequestWithMethod: @"POST"
URLString: urlString
parameters: nil
constructingBodyWithBlock: ^(id<AFMultipartFormData> formData) {
for(NSString * key in params) {
NSData* data = [params[key] dataUsingEncoding:NSUTF8StringEncoding];
[formData appendPartWithFormData: data name: key];
}
if (file) {
[formData appendPartWithFileData: [file data]
name: [file paramName]
fileName: [file name]
mimeType: [file mimeType]];
}
}
error:nil];
}
// request with form parameters or json
else {
NSString* pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString* urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:params
error:nil];
}
}
else {
NSString * pathWithQueryParams = [self pathWithQueryParamsToString:path queryParams:queryParams];
NSString * urlString = [[NSURL URLWithString:pathWithQueryParams relativeToURL:self.baseURL] absoluteString];
request = [self.requestSerializer requestWithMethod:method
URLString:urlString
parameters:body
error:nil];
}
BOOL hasHeaderParams = false;
if(headerParams != nil && [headerParams count] > 0)
hasHeaderParams = true;
if(offlineState) {
NSLog(@"%@ cache forced", path);
[request setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
}
else if(!hasHeaderParams && [method isEqualToString:@"GET"] && cacheEnabled) {
NSLog(@"%@ cache enabled", path);
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
}
else {
NSLog(@"%@ cache disabled", path);
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
// model
Class ModelClass = NSClassFromString(class);
if ([ModelClass instancesRespondToSelector:@selector(initWithDictionary:error:)]) {
return [[ModelClass alloc] initWithDictionary:data error:nil];
}
if(body != nil) {
if([body isKindOfClass:[NSDictionary class]] || [body isKindOfClass:[NSArray class]]){
[self.requestSerializer setValue:requestContentType forHTTPHeaderField:@"Content-Type"];
}
else if ([body isKindOfClass:[SWGFile class]]) {}
else {
NSAssert(false, @"unsupported post type!");
}
}
if(headerParams != nil){
for(NSString * key in [headerParams keyEnumerator]){
[request setValue:[headerParams valueForKey:key] forHTTPHeaderField:key];
}
}
[self.requestSerializer setValue:responseContentType forHTTPHeaderField:@"Accept"];
// Always disable cookies!
[request setHTTPShouldHandleCookies:NO];
if (self.logRequests) {
[self logRequest:request];
}
NSNumber* requestId = [SWGApiClient queueRequest];
AFHTTPRequestOperation *op =
[self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id JSON) {
if([self executeRequestWithId:requestId]) {
if(self.logServerResponses)
[self logResponse:JSON forRequest:request error:nil];
completionBlock(JSON, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([self executeRequestWithId:requestId]) {
NSMutableDictionary *userInfo = [error.userInfo mutableCopy];
if(operation.responseObject) {
// Add in the (parsed) response body.
userInfo[SWGResponseObjectErrorKey] = operation.responseObject;
}
NSError *augmentedError = [error initWithDomain:error.domain code:error.code userInfo:userInfo];
if(self.logServerResponses)
[self logResponse:nil forRequest:request error:augmentedError];
completionBlock(nil, augmentedError);
}
}
];
[self.operationQueue addOperation:op];
return requestId;
return nil;
}
-(NSNumber*) stringWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(NSString*, NSError *))completionBlock {
#pragma mark - Perform Request Methods
-(NSNumber*) requestWithCompletionBlock: (NSString*) path
method: (NSString*) method
queryParams: (NSDictionary*) queryParams
body: (id) body
headerParams: (NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType: (NSString*) requestContentType
responseContentType: (NSString*) responseContentType
completionBlock: (void (^)(id, NSError *))completionBlock {
// setting request serializer
if ([requestContentType isEqualToString:@"application/json"]) {
self.requestSerializer = [AFJSONRequestSerializer serializer];
@@ -540,7 +500,7 @@ static bool loggingEnabled = true;
// setting response serializer
if ([responseContentType isEqualToString:@"application/json"]) {
self.responseSerializer = [AFJSONResponseSerializer serializer];
self.responseSerializer = [SWGJSONResponseSerializer serializer];
}
else {
self.responseSerializer = [AFHTTPResponseSerializer serializer];
@@ -648,11 +608,11 @@ static bool loggingEnabled = true;
NSNumber* requestId = [SWGApiClient queueRequest];
AFHTTPRequestOperation *op = [self HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
success:^(AFHTTPRequestOperation *operation, id response) {
if([self executeRequestWithId:requestId]) {
if(self.logServerResponses)
[self logResponse:responseObject forRequest:request error:nil];
if(self.logServerResponses) {
[self logResponse:response forRequest:request error:nil];
}
completionBlock(response, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
@@ -683,3 +643,4 @@ static bool loggingEnabled = true;

View File

@@ -1,5 +1,10 @@
#import <Foundation/Foundation.h>
#import <ISO8601/ISO8601.h>
#import "AFHTTPRequestOperationManager.h"
#import "SWGJSONResponseSerializer.h"
{{#models}}{{#model}}#import "{{classname}}.h"
{{/model}}{{/models}}
/**
* A key for `NSError` user info dictionaries.
@@ -159,37 +164,16 @@ extern NSString *const SWGResponseObjectErrorKey;
WithAuthSettings:(NSArray *)authSettings;
/**
* Perform request
* Deserialize the given data to Objective-C object.
*
* Request with non-empty response
*
* @param path Request url.
* @param method Request method.
* @param queryParams Request query parameters.
* @param body Request body.
* @param headerParams Request header parameters.
* @param authSettings Request authentication names.
* @param requestContentType Request content-type.
* @param responseContentType Response content-type.
* @param completionBlock The block will be executed when the request completed.
*
* @return The request id.
* @param data The data will be deserialized.
* @param class The type of objective-c object.
*/
-(NSNumber*) dictionary:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSDictionary*, NSError *))completionBlock;
- (id) deserialize:(id) data class:(NSString *) class;
/**
* Perform request
*
* Request with empty response
*
* @param path Request url.
* @param method Request method.
* @param queryParams Request query parameters.
@@ -202,15 +186,18 @@ extern NSString *const SWGResponseObjectErrorKey;
*
* @return The request id.
*/
-(NSNumber*) stringWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(NSString*, NSError *))completionBlock;
-(NSNumber*) requestWithCompletionBlock:(NSString*) path
method:(NSString*) method
queryParams:(NSDictionary*) queryParams
body:(id) body
headerParams:(NSDictionary*) headerParams
authSettings: (NSArray *) authSettings
requestContentType:(NSString*) requestContentType
responseContentType:(NSString*) responseContentType
completionBlock:(void (^)(id, NSError *))completionBlock;
@end

View File

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

View File

@@ -0,0 +1,6 @@
#import <Foundation/Foundation.h>
#import <AFNetworking/AFURLResponseSerialization.h>
@interface SWGJSONResponseSerializer : AFJSONResponseSerializer
@end

View File

@@ -72,14 +72,16 @@ static NSString * basePath = @"{{basePath}}";
return [SWGApiClient requestQueueSize];
}
#pragma mark - Api Methods
{{#operation}}
/*!
* {{{summary}}}
* {{{notes}}}
{{#allParams}} * \param {{paramName}} {{{description}}}
{{/allParams}} * \returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
*/
///
/// {{{summary}}}
/// {{{notes}}}
/// {{#allParams}} @param {{paramName}} {{{description}}}
///
/// {{/allParams}} @returns {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
///
-(NSNumber*) {{nickname}}WithCompletionBlock{{^allParams}}: {{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}: ({{{dataType}}}) {{paramName}}
{{/allParams}}
{{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}}
@@ -195,27 +197,19 @@ static NSString * basePath = @"{{basePath}}";
}
{{/requiredParams}}
{{/requiredParamCount}}
{{#returnContainer}}
// response is in a container
{{>apiBodyResponseWithContainer}}{{/returnContainer}}
{{#returnSimpleType}}
// non container response
{{#returnTypeIsPrimitive}}
// primitive response
{{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}}
{{#returnBaseType}}
// complex response
{{>apiNonPrimitiveResponse}}{{/returnBaseType}}
{{/returnSimpleType}}
{{^returnSimpleType}}{{^returnContainer}}
// it's void
{{>voidResponse}}
{{/returnContainer}}{{/returnSimpleType}}
return [self.apiClient requestWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(id data, NSError *error) {
{{^returnType}}completionBlock(error);{{/returnType}}
{{#returnType}}completionBlock([self.apiClient deserialize: data class:@"{{{returnType}}}"], error);{{/returnType}}
}
];
}
{{/operation}}

View File

@@ -17,16 +17,15 @@
+(void) setBasePath:(NSString*)basePath;
+(NSString*) getBasePath;
{{#operation}}
/**
{{{summary}}}
{{#notes}}{{{notes}}}{{/notes}}
{{#allParams}}@param {{paramName}} {{description}}
{{/allParams}}
return type: {{{returnType}}}
*/
///
///
/// {{{summary}}}
/// {{#notes}}{{{notes}}}{{/notes}}
///
/// {{#allParams}}@param {{paramName}} {{description}}
/// {{/allParams}}
///
/// @return {{{returnType}}}
-(NSNumber*) {{nickname}}WithCompletionBlock {{^allParams}}:{{/allParams}}{{#allParams}}{{#secondaryParam}} {{paramName}}{{/secondaryParam}}:({{{dataType}}}) {{paramName}} {{#hasMore}}
{{/hasMore}}{{/allParams}}
{{#returnBaseType}}{{#hasParams}}

View File

@@ -1,38 +0,0 @@
// {{returnContainer}} container response type
return [self.apiClient dictionary: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
{{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}{{^returnBaseType}}completionBlock(error);{{/returnBaseType}}
return;
}
{{#isMapContainer}}
NSDictionary *result = nil;
if (data) {
result = [[NSDictionary alloc]initWithDictionary: data];
}
completionBlock(data, nil);
{{/isMapContainer}}{{#isListContainer}}
{{#returnBaseType}}if([data isKindOfClass:[NSArray class]]){
NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]];
for (NSDictionary* dict in (NSArray*)data) {
{{#returnTypeIsPrimitive}}
{{returnBaseType}}* d = [[{{{returnBaseType}}} alloc]initWithString: dict];
{{/returnTypeIsPrimitive}}
{{^returnTypeIsPrimitive}}
{{{returnBaseType}}}* d = [[{{{returnBaseType}}} alloc] initWithDictionary:dict error:nil];
{{/returnTypeIsPrimitive}}
[objs addObject:d];
}
completionBlock(({{{returnType}}})objs, nil);
}
{{/returnBaseType}}
{{/isListContainer}}
}];

View File

@@ -1,24 +0,0 @@
{{^returnTypeIsPrimitive}}
// comples response type
return [self.apiClient dictionary: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSDictionary *data, NSError *error) {
if (error) {
{{#returnBaseType}}completionBlock(nil, error);{{/returnBaseType}}
{{^returnBaseType}}completionBlock(error);{{/returnBaseType}}
return;
}
{{#returnType}}{{returnType}} result = nil;
if (data) {
result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}} initWithDictionary{{/isListContainer}}{{/returnContainer}}{{^returnContainer}} initWithDictionary{{/returnContainer}}:data error:nil];
}
{{#returnType}}completionBlock(result , nil);{{/returnType}}
{{/returnType}}
}];
{{/returnTypeIsPrimitive}}

View File

@@ -1,36 +0,0 @@
// primitive response type
{{#returnBaseType}}return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(nil, error);
return;
}
{{returnBaseType}} *result = data ? [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithString: data] : nil;
completionBlock(result, nil);
}];
{{/returnBaseType}}
{{^returnBaseType}}
// no return base type
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];
{{/returnBaseType}}

View File

@@ -1,15 +0,0 @@
return [self.apiClient stringWithCompletionBlock: requestUrl
method: @"{{httpMethod}}"
queryParams: queryParams
body: bodyDictionary
headerParams: headerParams
authSettings: authSettings
requestContentType: requestContentType
responseContentType: responseContentType
completionBlock: ^(NSString *data, NSError *error) {
if (error) {
completionBlock(error);
return;
}
completionBlock(nil);
}];

View File

@@ -1,4 +1,4 @@
package WWW::{{invokerPackage}}::ApiClient;
package WWW::{{moduleName}}::ApiClient;
use strict;
use warnings;
@@ -18,18 +18,18 @@ use Log::Any qw($log);
use Carp;
use Module::Runtime qw(use_module);
use WWW::{{invokerPackage}}::Configuration;
use WWW::{{moduleName}}::Configuration;
sub new
{
my $class = shift;
my (%args) = (
'ua' => LWP::UserAgent->new,
'base_url' => '{{basePath}}',
@_
);
return bless \%args, $class;
my $class = shift;
my (%args) = (
'ua' => LWP::UserAgent->new,
'base_url' => '{{basePath}}',
@_
);
return bless \%args, $class;
}
# Set the user agent of the API client
@@ -37,8 +37,8 @@ sub new
# @param string $user_agent The user agent of the API client
#
sub set_user_agent {
my ($self, $user_agent) = @_;
$self->{http_user_agent}= $user_agent;
my ($self, $user_agent) = @_;
$self->{http_user_agent}= $user_agent;
}
# Set timeout
@@ -46,11 +46,11 @@ sub set_user_agent {
# @param integer $seconds Number of seconds before timing out [set to 0 for no timeout]
#
sub set_timeout {
my ($self, $seconds) = @_;
if (!looks_like_number($seconds)) {
croak('Timeout variable must be numeric.');
}
$self->{http_timeout} = $seconds;
my ($self, $seconds) = @_;
if (!looks_like_number($seconds)) {
croak('Timeout variable must be numeric.');
}
$self->{http_timeout} = $seconds;
}
# make the HTTP request
@@ -61,71 +61,71 @@ sub set_timeout {
# @param array $headerParams parameters to be place in request header
# @return mixed
sub call_api {
my $self = shift;
my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_;
# update parameters based on authentication settings
$self->update_params_for_auth($header_params, $query_params, $auth_settings);
my $_url = $self->{base_url} . $resource_path;
# build query
if (%$query_params) {
$_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify });
}
# body data
$body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string
my $_body_data = %$post_params ? $post_params : $body_data;
# Make the HTTP request
my $_request;
if ($method eq 'POST') {
# multipart
$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
'form-data' : $header_params->{'Content-Type'};
$_request = POST($_url, %$header_params, Content => $_body_data);
}
elsif ($method eq 'PUT') {
# multipart
$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
'form-data' : $header_params->{'Content-Type'};
$_request = PUT($_url, %$header_params, Content => $_body_data);
}
elsif ($method eq 'GET') {
my $headers = HTTP::Headers->new(%$header_params);
$_request = GET($_url, %$header_params);
}
elsif ($method eq 'HEAD') {
my $headers = HTTP::Headers->new(%$header_params);
$_request = HEAD($_url,%$header_params);
}
elsif ($method eq 'DELETE') { #TODO support form data
my $headers = HTTP::Headers->new(%$header_params);
$_request = DELETE($_url, %$headers);
}
elsif ($method eq 'PATCH') { #TODO
}
else {
}
$self->{ua}->timeout($self->{http_timeout} || $WWW::{{invokerPackage}}::Configuration::http_timeout);
$self->{ua}->agent($self->{http_user_agent} || $WWW::{{invokerPackage}}::Configuration::http_user_agent);
my $self = shift;
my ($resource_path, $method, $query_params, $post_params, $header_params, $body_data, $auth_settings) = @_;
# update parameters based on authentication settings
$self->update_params_for_auth($header_params, $query_params, $auth_settings);
my $_url = $self->{base_url} . $resource_path;
# build query
if (%$query_params) {
$_url = ($_url . '?' . eval { URI::Query->new($query_params)->stringify });
}
# body data
$body_data = to_json($body_data->to_hash) if defined $body_data && $body_data->can('to_hash'); # model to json string
my $_body_data = %$post_params ? $post_params : $body_data;
# Make the HTTP request
my $_request;
if ($method eq 'POST') {
# multipart
$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
'form-data' : $header_params->{'Content-Type'};
$_request = POST($_url, %$header_params, Content => $_body_data);
}
elsif ($method eq 'PUT') {
# multipart
$header_params->{'Content-Type'} = lc $header_params->{'Content-Type'} eq 'multipart/form' ?
'form-data' : $header_params->{'Content-Type'};
$_request = PUT($_url, %$header_params, Content => $_body_data);
}
elsif ($method eq 'GET') {
my $headers = HTTP::Headers->new(%$header_params);
$_request = GET($_url, %$header_params);
}
elsif ($method eq 'HEAD') {
my $headers = HTTP::Headers->new(%$header_params);
$_request = HEAD($_url,%$header_params);
}
elsif ($method eq 'DELETE') { #TODO support form data
my $headers = HTTP::Headers->new(%$header_params);
$_request = DELETE($_url, %$headers);
}
elsif ($method eq 'PATCH') { #TODO
}
else {
}
$self->{ua}->timeout($self->{http_timeout} || $WWW::{{moduleName}}::Configuration::http_timeout);
$self->{ua}->agent($self->{http_user_agent} || $WWW::{{moduleName}}::Configuration::http_user_agent);
my $_response = $self->{ua}->request($_request);
unless ($_response->is_success) {
croak("API Exception(".$_response->code."): ".$_response->message);
}
return $_response->content;
my $_response = $self->{ua}->request($_request);
unless ($_response->is_success) {
croak("API Exception(".$_response->code."): ".$_response->message);
}
return $_response->content;
}
# Take value and turn it into a string suitable for inclusion in
@@ -180,13 +180,13 @@ sub to_form_value {
# @param string $value the value of the parameter
# @return string the header string
sub to_string {
my ($self, $value) = @_;
if (ref($value) eq "DateTime") { # datetime in ISO8601 format
return $value->datetime();
}
else {
return $value;
}
my ($self, $value) = @_;
if (ref($value) eq "DateTime") { # datetime in ISO8601 format
return $value->datetime();
}
else {
return $value;
}
}
# Deserialize a JSON string into an object
@@ -196,55 +196,55 @@ sub to_string {
# @return object an instance of $class
sub deserialize
{
my ($self, $class, $data) = @_;
$log->debugf("deserializing %s for %s", $data, $class);
if (not defined $data) {
return undef;
} elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash
if ($class =~ /^HASH\[(.*),(.*)\]$/) {
my ($key_type, $type) = ($1, $2);
my %hash;
my $decoded_data = decode_json $data;
foreach my $key (keys %$decoded_data) {
if (ref $decoded_data->{$key} eq 'HASH') {
$hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key});
my ($self, $class, $data) = @_;
$log->debugf("deserializing %s for %s", $data, $class);
if (not defined $data) {
return undef;
} elsif ( (substr($class, 0, 5)) eq 'HASH[') { #hash
if ($class =~ /^HASH\[(.*),(.*)\]$/) {
my ($key_type, $type) = ($1, $2);
my %hash;
my $decoded_data = decode_json $data;
foreach my $key (keys %$decoded_data) {
if (ref $decoded_data->{$key} eq 'HASH') {
$hash{$key} = $self->deserialize($type, encode_json $decoded_data->{$key});
} else {
$hash{$key} = $self->deserialize($type, $decoded_data->{$key});
}
}
return \%hash;
} else {
$hash{$key} = $self->deserialize($type, $decoded_data->{$key});
#TODO log error
}
} elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data
return $data if $data eq '[]'; # return if empty array
my $_sub_class = substr($class, 6, -1);
my $_json_data = decode_json $data;
my @_values = ();
foreach my $_value (@$_json_data) {
if (ref $_value eq 'ARRAY') {
push @_values, $self->deserialize($_sub_class, encode_json $_value);
} else {
push @_values, $self->deserialize($_sub_class, $_value);
}
}
return \@_values;
} elsif ($class eq 'DateTime') {
return DateTime->from_epoch(epoch => str2time($data));
} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) {
return $data;
} else { # model
my $_instance = use_module("WWW::{{moduleName}}::Object::$class")->new;
if (ref $data eq "HASH") {
return $_instance->from_hash($data);
} else { # string, need to json decode first
return $_instance->from_hash(decode_json $data);
}
}
return \%hash;
} else {
#TODO log error
}
} elsif ( (substr($class, 0, 6)) eq 'ARRAY[' ) { # array of data
return $data if $data eq '[]'; # return if empty array
my $_sub_class = substr($class, 6, -1);
my $_json_data = decode_json $data;
my @_values = ();
foreach my $_value (@$_json_data) {
if (ref $_value eq 'ARRAY') {
push @_values, $self->deserialize($_sub_class, encode_json $_value);
} else {
push @_values, $self->deserialize($_sub_class, $_value);
}
}
return \@_values;
} elsif ($class eq 'DateTime') {
return DateTime->from_epoch(epoch => str2time($data));
} elsif (grep /^$class$/, ('string', 'int', 'float', 'bool', 'object')) {
return $data;
} else { # model
my $_instance = use_module("WWW::SwaggerClient::Object::$class")->new;
if (ref $data eq "HASH") {
return $_instance->from_hash($data);
} else { # string, need to json decode first
return $_instance->from_hash(decode_json $data);
}
}
}
# return 'Accept' based on an array of accept provided
@@ -252,16 +252,16 @@ sub deserialize
# @return String Accept (e.g. application/json)
sub select_header_accept
{
my ($self, @header) = @_;
if (@header == 0 || (@header == 1 && $header[0] eq '')) {
return undef;
} elsif (grep(/^application\/json$/i, @header)) {
return 'application/json';
} else {
return join(',', @header);
}
my ($self, @header) = @_;
if (@header == 0 || (@header == 1 && $header[0] eq '')) {
return undef;
} elsif (grep(/^application\/json$/i, @header)) {
return 'application/json';
} else {
return join(',', @header);
}
}
# return the content type based on an array of content-type provided
@@ -269,16 +269,16 @@ sub select_header_accept
# @return String Content-Type (e.g. application/json)
sub select_header_content_type
{
my ($self, @header) = @_;
if (@header == 0 || (@header == 1 && $header[0] eq '')) {
return 'application/json'; # default to application/json
} elsif (grep(/^application\/json$/i, @header)) {
return 'application/json';
} else {
return join(',', @header);
}
my ($self, @header) = @_;
if (@header == 0 || (@header == 1 && $header[0] eq '')) {
return 'application/json'; # default to application/json
} elsif (grep(/^application\/json$/i, @header)) {
return 'application/json';
} else {
return join(',', @header);
}
}
# Get API key (with prefix if set)
@@ -287,10 +287,10 @@ sub select_header_content_type
sub get_api_key_with_prefix
{
my ($self, $api_key) = @_;
if ($WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}) {
return $WWW::{{invokerPackage}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{invokerPackage}}::Configuration::api_key->{$api_key};
if ($WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}) {
return $WWW::{{moduleName}}::Configuration::api_key_prefix->{$api_key}." ".$WWW::{{moduleName}}::Configuration::api_key->{$api_key};
} else {
return $WWW::{{invokerPackage}}::Configuration::api_key->{$api_key};
return $WWW::{{moduleName}}::Configuration::api_key->{$api_key};
}
}
@@ -300,24 +300,24 @@ sub get_api_key_with_prefix
# @param array $queryParams query parameters (by ref)
# @param array $authSettings array of authentication scheme (e.g ['api_key'])
sub update_params_for_auth {
my ($self, $header_params, $query_params, $auth_settings) = @_;
return if (!defined($auth_settings) || scalar(@$auth_settings) == 0);
# one endpoint can have more than 1 auth settings
foreach my $auth (@$auth_settings) {
# determine which one to use
if (!defined($auth)) {
my ($self, $header_params, $query_params, $auth_settings) = @_;
return if (!defined($auth_settings) || scalar(@$auth_settings) == 0);
# one endpoint can have more than 1 auth settings
foreach my $auth (@$auth_settings) {
# determine which one to use
if (!defined($auth)) {
}
{{#authMethods}}elsif ($auth eq '{{name}}') {
{{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{moduleName}}::Configuration::username.":".$WWW::{{moduleName}}::Configuration::password);{{/isBasic}}
{{#isOAuth}}# TODO support oauth{{/isOAuth}}
}
{{/authMethods}}
else {
# TODO show warning about security definition not found
}
}
{{#authMethods}}elsif ($auth eq '{{name}}') {
{{#isApiKey}}{{#isKeyInHeader}}$header_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$query_params->{'{{keyParamName}}'} = $self->get_api_key_with_prefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$header_params->{'Authorization'} = 'Basic '.encode_base64($WWW::{{invokerPackage}}::Configuration::username.":".$WWW::{{invokerPackage}}::Configuration::password);{{/isBasic}}
{{#isOAuth}}# TODO support oauth{{/isOAuth}}
}
{{/authMethods}}
else {
# TODO show warning about security definition not found
}
}
}

View File

@@ -1,4 +1,4 @@
package WWW::{{invokerPackage}}::Object::BaseObject;
package WWW::{{moduleName}}::Object::BaseObject;
require 5.6.0;
use strict;
@@ -21,56 +21,56 @@ use DateTime;
# return json string
sub to_hash {
return decode_json(JSON->new->convert_blessed->encode( shift ));
return decode_json(JSON->new->convert_blessed->encode( shift ));
}
# used by JSON for serialization
sub TO_JSON {
my $self = shift;
my $_data = {};
foreach my $_key (keys $self->get_attribute_map) {
if (defined $self->{$_key}) {
$_data->{$self->get_attribute_map->{$_key}} = $self->{$_key};
my $self = shift;
my $_data = {};
foreach my $_key (keys $self->get_attribute_map) {
if (defined $self->{$_key}) {
$_data->{$self->get_attribute_map->{$_key}} = $self->{$_key};
}
}
}
return $_data;
return $_data;
}
# from json string
sub from_hash {
my ($self, $hash) = @_;
# loop through attributes and use swagger_types to deserialize the data
while ( my ($_key, $_type) = each $self->get_swagger_types ) {
if ($_type =~ /^array\[/i) { # array
my $_subclass = substr($_type, 6, -1);
my @_array = ();
foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) {
push @_array, $self->_deserialize($_subclass, $_element);
}
$self->{$_key} = \@_array;
} elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime
$self->{$_key} = $self->_deserialize($_type, $hash->{$_key});
} else {
$log->debugf("warning: %s not defined\n", $_key);
my ($self, $hash) = @_;
# loop through attributes and use swagger_types to deserialize the data
while ( my ($_key, $_type) = each $self->get_swagger_types ) {
if ($_type =~ /^array\[/i) { # array
my $_subclass = substr($_type, 6, -1);
my @_array = ();
foreach my $_element (@{$hash->{$self->get_attribute_map->{$_key}}}) {
push @_array, $self->_deserialize($_subclass, $_element);
}
$self->{$_key} = \@_array;
} elsif (defined $hash->{$_key}) { #hash(model), primitive, datetime
$self->{$_key} = $self->_deserialize($_type, $hash->{$_key});
} else {
$log->debugf("warning: %s not defined\n", $_key);
}
}
}
return $self;
return $self;
}
# deserialize non-array data
sub _deserialize {
my ($self, $type, $data) = @_;
$log->debugf("deserializing %s with %s",Dumper($data), $type);
if ($type eq 'DateTime') {
return DateTime->from_epoch(epoch => str2time($data));
} elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) {
return $data;
} else { # hash(model)
my $_instance = eval "WWW::{{invokerPackage}}::Object::$type->new()";
return $_instance->from_hash($data);
}
my ($self, $type, $data) = @_;
$log->debugf("deserializing %s with %s",Dumper($data), $type);
if ($type eq 'DateTime') {
return DateTime->from_epoch(epoch => str2time($data));
} elsif ( grep( /^$type$/, ('int', 'double', 'string', 'boolean'))) {
return $data;
} else { # hash(model)
my $_instance = eval "WWW::{{moduleName}}::Object::$type->new()";
return $_instance->from_hash($data);
}
}
1;

View File

@@ -1,4 +1,4 @@
package WWW::{{invokerPackage}}::Configuration;
package WWW::{{moduleName}}::Configuration;
use strict;
use warnings;
@@ -7,6 +7,8 @@ use utf8;
use Log::Any qw($log);
use Carp;
use constant VERSION => '{{moduleVersion}}';
# class/static variables
our $api_client;
our $http_timeout = 180;

View File

@@ -17,7 +17,7 @@
# NOTE: This class is auto generated by the swagger code generator program.
# Do not edit the class manually.
#
package WWW::{{invokerPackage}}::{{classname}};
package WWW::{{moduleName}}::{{classname}};
require 5.6.0;
use strict;
@@ -27,18 +27,12 @@ use Exporter;
use Carp qw( croak );
use Log::Any qw($log);
use WWW::{{invokerPackage}}::ApiClient;
use WWW::{{invokerPackage}}::Configuration;
{{#operations}}
our @EXPORT_OK = qw(
{{#operation}}{{{nickname}}}
{{/operation}}
);
use WWW::{{moduleName}}::ApiClient;
use WWW::{{moduleName}}::Configuration;
sub new {
my $class = shift;
my $default_api_client = $WWW::{{invokerPackage}}::Configuration::api_client ? $WWW::{{invokerPackage}}::Configuration::api_client : WWW::{{invokerPackage}}::ApiClient->new;
my $default_api_client = $WWW::{{moduleName}}::Configuration::api_client ? $WWW::{{moduleName}}::Configuration::api_client : WWW::{{moduleName}}::ApiClient->new;
my (%self) = (
'api_client' => $default_api_client,
@_
@@ -52,89 +46,90 @@ sub new {
bless \%self, $class;
}
{{#operations}}
{{#operation}}
#
# {{{nickname}}}
#
# {{{summary}}}
#
{{#allParams}} # @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}}
{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
#
sub {{nickname}} {
my ($self, %args) = @_;
{{#operation}}
#
# {{{nickname}}}
#
# {{{summary}}}
#
{{#allParams}}# @param {{dataType}} ${{paramName}} {{description}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}}
{{/allParams}}# @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}
#
sub {{nickname}} {
my ($self, %args) = @_;
{{#allParams}}{{#required}}
# verify the required parameter '{{paramName}}' is set
unless (exists $args{'{{paramName}}'}) {
croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}");
}
{{/required}}{{/allParams}}
{{#allParams}}{{#required}}
# verify the required parameter '{{paramName}}' is set
unless (exists $args{'{{paramName}}'}) {
croak("Missing the required parameter '{{paramName}}' when calling {{nickname}}");
}
{{/required}}{{/allParams}}
# parse inputs
my $_resource_path = '{{path}}';
$_resource_path =~ s/{format}/json/; # default format to json
# parse inputs
my $_resource_path = '{{path}}';
$_resource_path =~ s/{format}/json/; # default format to json
my $_method = '{{httpMethod}}';
my $query_params = {};
my $header_params = {};
my $form_params = {};
my $_method = '{{httpMethod}}';
my $query_params = {};
my $header_params = {};
my $form_params = {};
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}});
if ($_header_accept) {
# 'Accept' and 'Content-Type' header
my $_header_accept = $self->{api_client}->select_header_accept({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}});
if ($_header_accept) {
$header_params->{'Accept'} = $_header_accept;
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}});
}
$header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type({{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}});
{{#queryParams}}# query params
if ( exists $args{'{{paramName}}'}) {
{{#queryParams}}# query params
if ( exists $args{'{{paramName}}'}) {
$query_params->{'{{baseName}}'} = $self->{api_client}->to_query_value($args{'{{paramName}}'});
}{{/queryParams}}
{{#headerParams}}# header params
if ( exists $args{'{{paramName}}'}) {
}{{/queryParams}}
{{#headerParams}}# header params
if ( exists $args{'{{paramName}}'}) {
$header_params->{'{{baseName}}'} = $self->{api_client}->to_header_value($args{'{{paramName}}'});
}{{/headerParams}}
{{#pathParams}}# path params
if ( exists $args{'{{paramName}}'}) {
}{{/headerParams}}
{{#pathParams}}# path params
if ( exists $args{'{{paramName}}'}) {
my $_base_variable = "{" . "{{baseName}}" . "}";
my $_base_value = $self->{api_client}->to_path_value($args{'{{paramName}}'});
$_resource_path =~ s/$_base_variable/$_base_value/g;
}{{/pathParams}}
{{#formParams}}# form params
if ( exists $args{'{{paramName}}'} ) {
}{{/pathParams}}
{{#formParams}}# form params
if ( exists $args{'{{paramName}}'} ) {
{{#isFile}}$form_params->{'{{baseName}}'} = [] unless defined $form_params->{'{{baseName}}'};
push $form_params->{'{{baseName}}'}, $args{'{{paramName}}'};
{{/isFile}}
{{^isFile}}$form_params->{'{{baseName}}'} = $self->{api_client}->to_form_value($args{'{{paramName}}'});
{{/isFile}}
}{{/formParams}}
my $_body_data;
{{#bodyParams}}# body params
if ( exists $args{'{{paramName}}'}) {
}{{/formParams}}
my $_body_data;
{{#bodyParams}}# body params
if ( exists $args{'{{paramName}}'}) {
$_body_data = $args{'{{paramName}}'};
}{{/bodyParams}}
}{{/bodyParams}}
# authentication setting, if any
my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}];
# authentication setting, if any
my $auth_settings = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}];
# make the API Call
{{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
# make the API Call
{{#returnType}}my $response = $self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
if (!$response) {
return;
}
my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response);
return $_response_object;{{/returnType}}
{{^returnType}}$self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
return;
{{/returnType}}
}
{{/operation}}
}
my $_response_object = $self->{api_client}->deserialize('{{returnType}}', $response);
return $_response_object;{{/returnType}}
{{^returnType}}$self->{api_client}->call_api($_resource_path, $_method,
$query_params, $form_params,
$header_params, $_body_data, $auth_settings);
return;
{{/returnType}}
}
{{/operation}}
{{newline}}
{{/operations}}

View File

@@ -1,6 +1,6 @@
{{#models}}
{{#model}}
package WWW::{{invokerPackage}}::Object::{{classname}};
package WWW::{{moduleName}}::Object::{{classname}};
require 5.6.0;
use strict;
@@ -13,7 +13,7 @@ use Log::Any qw($log);
use Date::Parse;
use DateTime;
use base "WWW::{{invokerPackage}}::Object::BaseObject";
use base "WWW::{{moduleName}}::Object::BaseObject";
#
#{{description}}
@@ -22,13 +22,13 @@ use base "WWW::{{invokerPackage}}::Object::BaseObject";
#
my $swagger_types = {
{{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}},
{{/hasMore}}{{/vars}}
{{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}},
{{/hasMore}}{{/vars}}
};
my $attribute_map = {
{{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}},
{{/hasMore}}{{/vars}}
{{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}},
{{/hasMore}}{{/vars}}
};
# new object
@@ -45,12 +45,12 @@ sub new {
# get swagger type of the attribute
sub get_swagger_types {
return $swagger_types;
return $swagger_types;
}
# get attribute mappping
sub get_attribute_map {
return $attribute_map;
return $attribute_map;
}
1;

View File

@@ -24,17 +24,14 @@ class ApiClient {
public static $GET = "GET";
public static $PUT = "PUT";
public static $DELETE = "DELETE";
/** @var string[] Array of default headers where the key is the header name and the value is the header value */
private $default_header = array();
/*
* @var string timeout (second) of the HTTP request, by default set to 0, no timeout
*/
/** @var string timeout (second) of the HTTP request, by default set to 0, no timeout */
protected $curl_timeout = 0;
/*
* @var string user agent of the HTTP request, set to "PHP-Swagger" by default
*/
/** @var string user agent of the HTTP request, set to "PHP-Swagger" by default */
protected $user_agent = "PHP-Swagger";
/**
@@ -386,8 +383,8 @@ class ApiClient {
$deserialized[$key] = $this->deserialize($value, $subClass);
}
}
} elseif (strcasecmp(substr($class, 0, 6),'array[') == 0) {
$subClass = substr($class, 6, -1);
} elseif (strcasecmp(substr($class, -2),'[]') == 0) {
$subClass = substr($class, 0, -2);
$values = array();
foreach ($data as $key => $value) {
$values[] = $this->deserialize($value, $subClass);
@@ -399,7 +396,6 @@ class ApiClient {
settype($data, $class);
$deserialized = $data;
} else {
$class = "{{invokerPackage}}\\models\\".$class;
$instance = new $class();
foreach ($instance::$swaggerTypes as $property => $type) {
$original_property_name = $instance::$attributeMap[$property];

View File

@@ -21,14 +21,10 @@ use \Exception;
class ApiException extends Exception {
/**
* The HTTP body of the server response.
*/
/** @var string The HTTP body of the server response. */
protected $response_body;
/**
* The HTTP header of the server response.
*/
/** @var string[] The HTTP header of the server response. */
protected $response_headers;
public function __construct($message="", $code=0, $responseHeaders=null, $responseBody=null) {

View File

@@ -20,11 +20,17 @@
* NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.
*/
namespace {{invokerPackage}};
namespace {{apiPackage}};
use \{{invokerPackage}}\ApiClient;
use \{{invokerPackage}}\Configuration;
{{#operations}}
class {{classname}} {
/**
* @param \{{invokerPackage}}\ApiClient|null $apiClient The api client to use. Defaults to getting it from Configuration
*/
function __construct($apiClient = null) {
if (null === $apiClient) {
if (Configuration::$apiClient === null) {
@@ -38,17 +44,18 @@ class {{classname}} {
}
}
private $apiClient; // instance of the ApiClient
/** @var \{{invokerPackage}}\ApiClient instance of the ApiClient */
private $apiClient;
/**
* get the API client
* @return \{{invokerPackage}}\ApiClient get the API client
*/
public function getApiClient() {
return $this->apiClient;
}
/**
* set the API client
* @param \{{invokerPackage}} $apiClient set the API client
*/
public function setApiClient($apiClient) {
$this->apiClient = $apiClient;
@@ -123,7 +130,6 @@ class {{classname}} {
$response = $this->apiClient->callAPI($resourcePath, $method,
$queryParams, $httpBody,
$headerParams, $authSettings);
{{#returnType}}if(! $response) {
return null;
}

View File

@@ -0,0 +1,41 @@
<?php
/**
* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the \{{invokerPackage}}\Baz\Qux class
* from /path/to/project/lib/Baz/Qux.php:
*
* new \{{invokerPackage}}\Baz\Qux;
*
* @param string $class The fully-qualified class name.
* @return void
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = '{{escapedInvokerPackage}}\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/lib/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});

View File

@@ -1,5 +1,6 @@
{
"name": "{{invokerPackage}}/{{invokerPackage}}-php",
"name": "{{groupId}}/{{artifactId}}",{{#artifactVersion}}
"version": "{{artifactVersion}}",{{/artifactVersion}}
"description": "{{description}}",
"keywords": [
"swagger",
@@ -27,6 +28,6 @@
"squizlabs/php_codesniffer": "~2.0"
},
"autoload": {
"psr-4": { "{{invokerPackage}}\\" : "lib/" }
"psr-4": { "{{escapedInvokerPackage}}\\" : "lib/" }
}
}

View File

@@ -17,41 +17,29 @@
namespace {{invokerPackage}};
use \{{invokerPackage}}\ApiClient;
class Configuration {
/**
* Associate array to store API key(s)
*/
/** @var string[] Associate array to store API key(s) */
public static $apiKey = array();
/**
* Associate array to store API prefix (e.g. Bearer)
*/
/** string[] Associate array to store API prefix (e.g. Bearer) */
public static $apiKeyPrefix = array();
/**
* Username for HTTP basic authentication
*/
/** @var string Username for HTTP basic authentication */
public static $username = '';
/**
* Password for HTTP basic authentication
*/
/** @var string Password for HTTP basic authentication */
public static $password = '';
/**
* The default instance of ApiClient
*/
/** @var \{{invokerPackage}}\ApiClient The default instance of ApiClient */
public static $apiClient;
/**
* Debug switch (default set to false)
*/
/** @var bool Debug switch (default set to false) */
public static $debug = false;
/**
* Debug file location (log to STDOUT by default)
*/
/** @var string Debug file location (log to STDOUT by default) */
public static $debug_file = 'php://output';
/*
@@ -63,4 +51,3 @@ class Configuration {
}
}

View File

@@ -24,29 +24,31 @@
*
*/
namespace {{invokerPackage}}\models;
namespace {{modelPackage}};
use \ArrayAccess;
class {{classname}} implements ArrayAccess {
/** @var string[] Array of property to type mappings. Used for (de)serialization */
static $swaggerTypes = array(
{{#vars}}'{{name}}' => '{{{datatype}}}'{{#hasMore}},
{{/hasMore}}{{/vars}}
);
/** @var string[] Array of attributes where the key is the local name, and the value is the original name */
static $attributeMap = array(
{{#vars}}'{{name}}' => '{{baseName}}'{{#hasMore}},
{{/hasMore}}{{/vars}}
);
{{#vars}}{{#description}}
{{#vars}}
/** @var {{datatype}} ${{name}} {{#description}}{{{description}}} {{/description}}*/
public ${{name}};
{{/vars}}
/**
* {{{description}}}
*/{{/description}}
public ${{name}}; /* {{{datatype}}} */{{/vars}}
* @param mixed[] Array of parameters to initialize the object with
*/
public function __construct(array $data = null) {
{{#vars}}$this->{{name}} = $data["{{name}}"];{{#hasMore}}
{{#vars}}$this->{{name}} = @$data["{{name}}"];{{#hasMore}}
{{/hasMore}}{{/vars}}
}

View File

@@ -1,13 +0,0 @@
<?php
// load models defined for endpoints
foreach (glob(dirname(__FILE__)."/lib/models/*.php") as $filename)
{
require_once $filename;
}
// load classes for accessing the endpoints
foreach (glob(dirname(__FILE__)."/lib/*.php") as $filename)
{
require_once $filename;
}
?>

View File

@@ -11,7 +11,7 @@ module {{moduleName}}
# {{notes}}
{{#allParams}}{{#required}} # @param {{paramName}} {{description}}
{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters
{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}}
{{#allParams}}{{^required}} # @option opts [{{{dataType}}}] :{{paramName}} {{description}}
{{/required}}{{/allParams}} # @return [{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}nil{{/returnType}}]
def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {})
{{#allParams}}{{#required}}
@@ -51,8 +51,8 @@ module {{moduleName}}
{{/bodyParam}}
auth_names = [{{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}]
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make.body
{{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
{{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
response.deserialize('{{{returnType}}}'){{/returnType}}{{^returnType}}Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body, :auth_names => auth_names}).make
nil{{/returnType}}
end
{{/operation}}

View File

@@ -2,20 +2,11 @@ module {{moduleName}}
# base class containing fundamental method such as to_hash, build_from_hash and more
class BaseObject
# return the object in the form of hash
def to_body
body = {}
self.class.attribute_map.each_pair do |key, value|
body[value] = self.send(key) unless self.send(key).nil?
end
body
end
# build the object from hash
def build_from_hash(attributes)
return nil unless attributes.is_a?(Hash)
self.class.swagger_types.each_pair do |key, type|
if type =~ /^array\[(.*)\]/i
if type =~ /^Array<(.*)>/i
if attributes[self.class.attribute_map[key]].is_a?(Array)
self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } )
else
@@ -35,13 +26,13 @@ module {{moduleName}}
case type.to_sym
when :DateTime
DateTime.parse(value)
when :string
when :String
value.to_s
when :int
when :Integer
value.to_i
when :double
when :Float
value.to_f
when :boolean
when :BOOLEAN
if value =~ /^(true|t|yes|y|1)$/i
true
else
@@ -53,7 +44,16 @@ module {{moduleName}}
end
end
# to_body is an alias to to_body (backward compatibility)
def to_s
to_hash.to_s
end
# to_body is an alias to to_body (backward compatibility))
def to_body
to_hash
end
# return the object in the form of hash
def to_hash
hash = {}
self.class.attribute_map.each_pair do |key, value|

View File

@@ -1,90 +1,82 @@
# module Swagger
class Object
unless Object.method_defined? :blank?
def blank?
respond_to?(:empty?) ? empty? : !self
end
class Object
unless Object.method_defined? :blank?
def blank?
respond_to?(:empty?) ? empty? : !self
end
unless Object.method_defined? :present?
def present?
!blank?
end
end
end
class String
unless String.method_defined? :underscore
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
unless String.method_defined? :camelize
def camelize(first_letter_in_uppercase = true)
if first_letter_in_uppercase != :lower
self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else
self.to_s[0].chr.downcase + camelize(self)[1..-1]
end
end
unless Object.method_defined? :present?
def present?
!blank?
end
end
end
class String
unless String.method_defined? :underscore
def underscore
self.gsub(/::/, '/').
gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2').
gsub(/([a-z\d])([A-Z])/,'\1_\2').
tr("-", "_").
downcase
end
end
class Hash
unless Hash.method_defined? :stringify_keys
def stringify_keys
inject({}) do |options, (key, value)|
options[key.to_s] = value
options
end
unless String.method_defined? :camelize
def camelize(first_letter_in_uppercase = true)
if first_letter_in_uppercase != :lower
self.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase }
else
self.to_s[0].chr.downcase + camelize(self)[1..-1]
end
end
unless Hash.method_defined? :stringify_keys!
def stringify_keys!
self.replace(self.stringify_keys)
end
end
unless Hash.method_defined? :symbolize_keys
def symbolize_keys
inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_keys!
def symbolize_keys!
self.replace(self.symbolize_keys)
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys
def symbolize_and_underscore_keys
inject({}) do |options, (key, value)|
options[(key.to_s.underscore.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys)
end
end
end
# end
end
class Hash
unless Hash.method_defined? :stringify_keys
def stringify_keys
inject({}) do |options, (key, value)|
options[key.to_s] = value
options
end
end
end
unless Hash.method_defined? :stringify_keys!
def stringify_keys!
self.replace(self.stringify_keys)
end
end
unless Hash.method_defined? :symbolize_keys
def symbolize_keys
inject({}) do |options, (key, value)|
options[(key.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_keys!
def symbolize_keys!
self.replace(self.symbolize_keys)
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys
def symbolize_and_underscore_keys
inject({}) do |options, (key, value)|
options[(key.to_s.underscore.to_sym rescue key) || key] = value
options
end
end
end
unless Hash.method_defined? :symbolize_and_underscore_keys!
def symbolize_and_underscore_keys!
self.replace(self.symbolize_and_underscore_keys)
end
end
end

View File

@@ -52,7 +52,7 @@ module {{moduleName}}
return if Swagger.authenticated?
if Swagger.configuration.username.blank? || Swagger.configuration.password.blank?
raise ClientError, "Username and password are required to authenticate."
raise ApiError, "Username and password are required to authenticate."
end
request = Swagger::Request.new(
@@ -69,10 +69,4 @@ module {{moduleName}}
end
end
end
class ServerError < StandardError
end
class ClientError < StandardError
end
end

View File

@@ -0,0 +1,26 @@
module {{moduleName}}
module Swagger
class ApiError < StandardError
attr_reader :code, :response_headers, :response_body
# Usage examples:
# ApiError.new
# ApiError.new("message")
# ApiError.new(:code => 500, :response_headers => {}, :response_body => "")
# ApiError.new(:code => 404, :message => "Not Found")
def initialize(arg = nil)
if arg.is_a? Hash
arg.each do |k, v|
if k.to_s == 'message'
super v
else
instance_variable_set "@#{k}", v
end
end
else
super arg
end
end
end
end
end

View File

@@ -2,15 +2,18 @@ module {{moduleName}}
module Swagger
class Response
require 'json'
require 'date'
attr_accessor :raw
def initialize(raw)
self.raw = raw
case self.code
when 500..510 then raise(ServerError, self.error_message)
when 299..426 then raise(ClientError, self.error_message)
unless raw.success?
fail ApiError.new(:code => code,
:response_headers => headers,
:response_body => body),
raw.status_message
end
end
@@ -18,19 +21,65 @@ module {{moduleName}}
raw.code
end
# Account for error messages that take different forms...
def error_message
body['message']
rescue
body
def body
raw.body
end
# If body is JSON, parse it
# Otherwise return raw string
def body
JSON.parse(raw.body, :symbolize_names => true)
rescue
raw.body
# Deserialize the raw response body to the given return type.
#
# @param [String] return_type some examples: "User", "Array[User]", "Hash[String,Integer]"
def deserialize(return_type)
return nil if body.blank?
# ensuring a default content type
content_type = raw.headers_hash['Content-Type'] || 'application/json'
unless content_type.start_with?('application/json')
fail "Content-Type is not supported: #{content_type}"
end
begin
data = JSON.parse(body, :symbolize_names => true)
rescue JSON::ParserError => e
if return_type == 'String'
return body
else
raise e
end
end
build_models data, return_type
end
# Walk through the given data and, when necessary, build model(s) from
# Hash data for array/hash values of the response.
def build_models(data, return_type)
case return_type
when 'String', 'Integer', 'Float', 'BOOLEAN'
# primitives, return directly
data
when 'DateTime'
# parse date time (expecting ISO 8601 format)
DateTime.parse data
when 'Object'
# generic object, return directly
data
when /\AArray<(.+)>\z/
# e.g. Array<Pet>
sub_type = $1
data.map {|item| build_models(item, sub_type) }
when /\AHash\<String, (.+)\>\z/
# e.g. Hash<String, Integer>
sub_type = $1
{}.tap do |hash|
data.each {|k, v| hash[k] = build_models(v, sub_type) }
end
else
# models, e.g. Pet
{{moduleName}}.const_get(return_type).new.tap do |model|
model.build_from_hash data
end
end
end
# `headers_hash` is a Typhoeus-specific extension of Hash,
@@ -58,7 +107,7 @@ module {{moduleName}}
def pretty_body
return unless body.present?
case format
when 'json' then JSON.pretty_generate(body).gsub(/\n/, '<br/>')
when 'json' then JSON.pretty_generate(JSON.parse(body)).gsub(/\n/, '<br/>')
end
end

View File

@@ -2,6 +2,7 @@
require '{{gemName}}/monkey'
require '{{gemName}}/swagger'
require '{{gemName}}/swagger/configuration'
require '{{gemName}}/swagger/api_error'
require '{{gemName}}/swagger/request'
require '{{gemName}}/swagger/response'
require '{{gemName}}/swagger/version'

View File

@@ -3,6 +3,7 @@ package Java
import io.swagger.codegen.languages.JavaClientCodegen
import io.swagger.models._
import io.swagger.models.properties._
import io.swagger.util.Json
import org.junit.runner.RunWith
import org.scalatest.{FlatSpec, Matchers}
import org.scalatest.junit.JUnitRunner
@@ -344,3 +345,32 @@ class JavaModelTest extends FlatSpec with Matchers {
cm.classname should be("WithDots")
}
}
@RunWith(classOf[JUnitRunner])
class JavaModelTest2 extends FlatSpec with Matchers {
it should "translate an invalid param name" in {
val model = new ModelImpl()
.description("a model with a 2nd char upper-case property names")
.property("_", new StringProperty())
val codegen = new JavaClientCodegen()
val cm = codegen.fromModel("sample", model)
cm.name should be("sample")
cm.classname should be("Sample")
cm.vars.size should be(1)
val vars = cm.vars
Json.prettyPrint(vars.get(0))
vars.get(0).baseName should be("_")
vars.get(0).getter should be("getU")
vars.get(0).setter should be("setU")
vars.get(0).datatype should be("String")
vars.get(0).name should be("u")
vars.get(0).defaultValue should be("null")
vars.get(0).baseType should be("String")
vars.get(0).hasMore should equal(null)
vars.get(0).isNotContainer should equal(true)
}
}

View File

@@ -118,7 +118,7 @@ class ObjcModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("translations")
vars.get(0).datatype should be("NSDictionary*")
vars.get(0).datatype should be("NSDictionary* /* NSString, NSString */")
vars.get(0).name should be("translations")
vars.get(0).baseType should be("NSDictionary")
vars.get(0).containerType should be("map")
@@ -192,7 +192,7 @@ class ObjcModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("children")
vars.get(0).complexType should be("SWGChildren")
vars.get(0).datatype should be("NSDictionary*")
vars.get(0).datatype should be("NSDictionary* /* NSString, SWGChildren */")
vars.get(0).name should be("children")
vars.get(0).baseType should be("NSDictionary")
vars.get(0).containerType should be("map")

View File

@@ -51,16 +51,16 @@ class PhpModelTest extends FlatSpec with Matchers {
vars.get(1).isNotContainer should equal(true)
vars.get(2).baseName should be("createdAt")
vars.get(2).complexType should be(null)
vars.get(2).datatype should be("DateTime")
vars.get(2).complexType should be("\\DateTime")
vars.get(2).datatype should be("\\DateTime")
vars.get(2).name should be("created_at")
vars.get(2).defaultValue should be("null")
vars.get(2).baseType should be("DateTime")
vars.get(2).baseType should be("\\DateTime")
vars.get(2).hasMore should equal(null)
vars.get(2).required should equal(null)
vars.get(2).isNotContainer should equal(true)
cm.imports.size() should be(0)
cm.imports.size() should be(1)
}
it should "convert a model with list property" in {
@@ -91,7 +91,7 @@ class PhpModelTest extends FlatSpec with Matchers {
vars.get(0).isNotContainer should equal(true)
vars.get(1).baseName should be("urls")
vars.get(1).datatype should be("array[string]")
vars.get(1).datatype should be("string[]")
vars.get(1).name should be("urls")
vars.get(1).baseType should be("array")
vars.get(1).hasMore should be(null)
@@ -142,7 +142,7 @@ class PhpModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("children")
vars.get(0).datatype should be("Children")
vars.get(0).datatype should be("\\Swagger\\Client\\Model\\Children")
vars.get(0).name should be("children")
vars.get(0).baseType should be("Children")
vars.get(0).required should equal(null)
@@ -166,7 +166,7 @@ class PhpModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("children")
vars.get(0).complexType should be("Children")
vars.get(0).datatype should be("array[Children]")
vars.get(0).datatype should be("\\Swagger\\Client\\Model\\Children[]")
vars.get(0).name should be("children")
vars.get(0).baseType should be("array")
vars.get(0).containerType should be("array")
@@ -192,7 +192,7 @@ class PhpModelTest extends FlatSpec with Matchers {
val vars = cm.vars
vars.get(0).baseName should be("children")
vars.get(0).complexType should be("Children")
vars.get(0).datatype should be("map[string,Children]")
vars.get(0).datatype should be("map[string,\\Swagger\\Client\\Model\\Children]")
vars.get(0).name should be("children")
vars.get(0).baseType should be("map")
vars.get(0).containerType should be("map")