From 87b85e5b9356495c158f4c02a2b39be1bf8b3e91 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 24 Mar 2015 02:33:08 +0800 Subject: [PATCH 01/21] remove old php model files --- .../client/petstore/php/models/category.php | 60 ------------- samples/client/petstore/php/models/order.php | 79 ----------------- samples/client/petstore/php/models/pet.php | 79 ----------------- samples/client/petstore/php/models/tag.php | 60 ------------- samples/client/petstore/php/models/user.php | 87 ------------------- 5 files changed, 365 deletions(-) delete mode 100644 samples/client/petstore/php/models/category.php delete mode 100644 samples/client/petstore/php/models/order.php delete mode 100644 samples/client/petstore/php/models/pet.php delete mode 100644 samples/client/petstore/php/models/tag.php delete mode 100644 samples/client/petstore/php/models/user.php diff --git a/samples/client/petstore/php/models/category.php b/samples/client/petstore/php/models/category.php deleted file mode 100644 index c7226ee1b6f..00000000000 --- a/samples/client/petstore/php/models/category.php +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/php/models/order.php b/samples/client/petstore/php/models/order.php deleted file mode 100644 index 72046f63fa3..00000000000 --- a/samples/client/petstore/php/models/order.php +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'pet_id' => 'int', - 'quantity' => 'int', - 'ship_date' => 'DateTime', - 'status' => 'string', - 'complete' => 'boolean' - ); - - static $attributeMap = array( - 'id' => 'id', - 'pet_id' => 'petId', - 'quantity' => 'quantity', - 'ship_date' => 'shipDate', - 'status' => 'status', - 'complete' => 'complete' - ); - - - public $id; /* int */ - public $pet_id; /* int */ - public $quantity; /* int */ - public $ship_date; /* DateTime */ - /** - * Order Status - */ - public $status; /* string */ - public $complete; /* boolean */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->pet_id = $data["pet_id"]; - $this->quantity = $data["quantity"]; - $this->ship_date = $data["ship_date"]; - $this->status = $data["status"]; - $this->complete = $data["complete"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/php/models/pet.php b/samples/client/petstore/php/models/pet.php deleted file mode 100644 index e980d858a2f..00000000000 --- a/samples/client/petstore/php/models/pet.php +++ /dev/null @@ -1,79 +0,0 @@ - 'int', - 'category' => 'Category', - 'name' => 'string', - 'photo_urls' => 'array[string]', - 'tags' => 'array[Tag]', - 'status' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'category' => 'category', - 'name' => 'name', - 'photo_urls' => 'photoUrls', - 'tags' => 'tags', - 'status' => 'status' - ); - - - public $id; /* int */ - public $category; /* Category */ - public $name; /* string */ - public $photo_urls; /* array[string] */ - public $tags; /* array[Tag] */ - /** - * pet status in the store - */ - public $status; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->category = $data["category"]; - $this->name = $data["name"]; - $this->photo_urls = $data["photo_urls"]; - $this->tags = $data["tags"]; - $this->status = $data["status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/php/models/tag.php b/samples/client/petstore/php/models/tag.php deleted file mode 100644 index 00ad8efbb37..00000000000 --- a/samples/client/petstore/php/models/tag.php +++ /dev/null @@ -1,60 +0,0 @@ - 'int', - 'name' => 'string' - ); - - static $attributeMap = array( - 'id' => 'id', - 'name' => 'name' - ); - - - public $id; /* int */ - public $name; /* string */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->name = $data["name"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} diff --git a/samples/client/petstore/php/models/user.php b/samples/client/petstore/php/models/user.php deleted file mode 100644 index 1ae88e5e2aa..00000000000 --- a/samples/client/petstore/php/models/user.php +++ /dev/null @@ -1,87 +0,0 @@ - 'int', - 'username' => 'string', - 'first_name' => 'string', - 'last_name' => 'string', - 'email' => 'string', - 'password' => 'string', - 'phone' => 'string', - 'user_status' => 'int' - ); - - static $attributeMap = array( - 'id' => 'id', - 'username' => 'username', - 'first_name' => 'firstName', - 'last_name' => 'lastName', - 'email' => 'email', - 'password' => 'password', - 'phone' => 'phone', - 'user_status' => 'userStatus' - ); - - - public $id; /* int */ - public $username; /* string */ - public $first_name; /* string */ - public $last_name; /* string */ - public $email; /* string */ - public $password; /* string */ - public $phone; /* string */ - /** - * User Status - */ - public $user_status; /* int */ - - public function __construct(array $data) { - $this->id = $data["id"]; - $this->username = $data["username"]; - $this->first_name = $data["first_name"]; - $this->last_name = $data["last_name"]; - $this->email = $data["email"]; - $this->password = $data["password"]; - $this->phone = $data["phone"]; - $this->user_status = $data["user_status"]; - } - - public function offsetExists($offset) { - return isset($this->$offset); - } - - public function offsetGet($offset) { - return $this->$offset; - } - - public function offsetSet($offset, $value) { - $this->$offset = $value; - } - - public function offsetUnset($offset) { - unset($this->$offset); - } -} From 07237f8eb9f330b1357cf094d0bcd081fb978602 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 24 Mar 2015 11:55:20 +0800 Subject: [PATCH 02/21] add model attribute name json key mapping in python clent --- .../src/main/resources/python/model.mustache | 12 +++++++++++- .../src/main/resources/python/swagger.mustache | 14 +++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index f6e95c72dc6..ff81820ca33 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -17,12 +17,17 @@ Copyright 2015 Reverb Technologies, Inc. {{#models}} {{#model}} -class {{classname}}: +class {{classname}}(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually.""" def __init__(self): + """ + Attributes: + swaggerTypes (dict): The key is attribute name and the value is attribute type. + attributeMap (dict): The key is attribute name and the value is json key in definition. + """ self.swaggerTypes = { {{#vars}} '{{name}}': '{{{datatype}}}'{{#hasMore}}, @@ -30,6 +35,11 @@ class {{classname}}: {{/vars}}{{newline}} } + self.attributeMap = { + {{#vars}} + '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } {{#vars}} {{#description}}#{{description}} diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 7864c201866..1cfc60981be 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -131,10 +131,14 @@ class ApiClient(object): if isinstance(obj, dict): objDict = obj else: - objDict = obj.__dict__ + # Convert model obj to dict except attributes `swaggerTypes`, `attributeMap` + # and attributes which value is not None. + # Convert attribute name to json key in model definition for request. + objDict = {obj.attributeMap[key]: val + for key, val in obj.__dict__.iteritems() + if key != 'swaggerTypes' and key != 'attributeMap' and val is not None} return {key: ApiClient.sanitizeForSerialization(val) - for (key, val) in objDict.iteritems() - if key != 'swaggerTypes'} + for (key, val) in objDict.iteritems()} def buildMultipartFormData(self, postData, files): def escape_quotes(s): @@ -199,8 +203,8 @@ class ApiClient(object): instance = objClass() for attr, attrType in instance.swaggerTypes.iteritems(): - if obj is not None and attr in obj and type(obj) in [list, dict]: - value = obj[attr] + if obj is not None and instance.attributeMap[attr] in obj and type(obj) in [list, dict]: + value = obj[instance.attributeMap[attr]] if attrType in ['str', 'int', 'long', 'float', 'bool']: attrType = eval(attrType) try: From ee096569c4da05dbb01f5be4996583567796a143 Mon Sep 17 00:00:00 2001 From: MerkushevKirill Date: Tue, 24 Mar 2015 00:26:49 +0300 Subject: [PATCH 03/21] rft - only codestyle with indents, remove wildcard imports and use string-utils from apache --- .../swagger/codegen/DefaultGenerator.java | 250 ++++++++++-------- 1 file changed, 135 insertions(+), 115 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java index 3552e066c68..cb0bc5e6523 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultGenerator.java @@ -1,15 +1,30 @@ package com.wordnik.swagger.codegen; -import com.wordnik.swagger.models.*; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import com.wordnik.swagger.models.Contact; +import com.wordnik.swagger.models.Info; +import com.wordnik.swagger.models.License; +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.Operation; +import com.wordnik.swagger.models.Path; +import com.wordnik.swagger.models.Swagger; import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.swagger.util.*; -import com.samskivert.mustache.*; - +import com.wordnik.swagger.util.Json; import org.apache.commons.io.FileUtils; -import java.util.*; -import java.util.regex.*; -import java.io.*; +import java.io.File; +import java.io.Reader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.apache.commons.lang3.StringUtils.capitalize; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; public class DefaultGenerator extends AbstractGenerator implements Generator { protected CodegenConfig config; @@ -20,64 +35,71 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { this.opts = opts; this.swagger = opts.getSwagger(); - ClientOpts clientOpts = opts.getOpts(); this.config = opts.getConfig(); - this.config.additionalProperties().putAll(clientOpts.getProperties()); + this.config.additionalProperties().putAll(opts.getOpts().getProperties()); return this; } public List generate() { - if(swagger == null || config == null) { + if (swagger == null || config == null) { throw new RuntimeException("missing swagger input or config!"); } - if(System.getProperty("debugSwagger") != null) { + if (System.getProperty("debugSwagger") != null) { Json.prettyPrint(swagger); } List files = new ArrayList(); try { config.processOpts(); - if(swagger.getInfo() != null) { + if (swagger.getInfo() != null) { Info info = swagger.getInfo(); - if(info.getTitle() != null) + if (info.getTitle() != null) { config.additionalProperties().put("appName", info.getTitle()); - if(info.getVersion() != null) + } + if (info.getVersion() != null) { config.additionalProperties().put("appVersion", info.getVersion()); - if(info.getDescription() != null) + } + if (info.getDescription() != null) { config.additionalProperties().put("appDescription", info.getDescription()); - if(info.getContact() != null) { + } + if (info.getContact() != null) { Contact contact = info.getContact(); config.additionalProperties().put("infoUrl", contact.getUrl()); - if(contact.getEmail() != null) + if (contact.getEmail() != null) { config.additionalProperties().put("infoEmail", contact.getEmail()); + } } - if(info.getLicense() != null) { + if (info.getLicense() != null) { License license = info.getLicense(); - if(license.getName() != null) + if (license.getName() != null) { config.additionalProperties().put("licenseInfo", license.getName()); - if(license.getUrl() != null) + } + if (license.getUrl() != null) { config.additionalProperties().put("licenseUrl", license.getUrl()); + } } - if(info.getVersion() != null) { + if (info.getVersion() != null) { config.additionalProperties().put("version", info.getVersion()); } } StringBuilder hostBuilder = new StringBuilder(); - if(swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { + if (swagger.getSchemes() != null && swagger.getSchemes().size() > 0) { hostBuilder.append(swagger.getSchemes().get(0).toValue()); hostBuilder.append("://"); - } - else + } else { hostBuilder.append("https://"); - if(swagger.getHost() != null) + } + if (swagger.getHost() != null) { hostBuilder.append(swagger.getHost()); - else + } else { hostBuilder.append("localhost"); - if(swagger.getBasePath() != null) + } + if (swagger.getBasePath() != null) { hostBuilder.append(swagger.getBasePath()); - else + } else { hostBuilder.append("/"); + } String contextPath = swagger.getBasePath() == null ? "/" : swagger.getBasePath(); String basePath = hostBuilder.toString(); @@ -87,41 +109,41 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { // models Map definitions = swagger.getDefinitions(); - if(definitions != null) { - for(String name: definitions.keySet()) { + if (definitions != null) { + for (String name : definitions.keySet()) { Model model = definitions.get(name); Map modelMap = new HashMap(); modelMap.put(name, model); Map models = processModels(config, modelMap); models.putAll(config.additionalProperties()); - allModels.add(((List)models.get("models")).get(0)); + allModels.add(((List) models.get("models")).get(0)); - for(String templateName : config.modelTemplateFiles().keySet()) { + for (String templateName : config.modelTemplateFiles().keySet()) { String suffix = config.modelTemplateFiles().get(templateName); String filename = config.modelFileFolder() + File.separator + config.toModelFilename(name) + suffix; String template = readTemplate(config.templateDir() + File.separator + templateName); Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - public Reader getTemplate (String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); - }; - }) - .defaultValue("") - .compile(template); + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + }) + .defaultValue("") + .compile(template); writeToFile(filename, tmpl.execute(models)); files.add(new File(filename)); } } } - if(System.getProperty("debugModels") != null) { + if (System.getProperty("debugModels") != null) { System.out.println("############ Model info ############"); Json.prettyPrint(allModels); } // apis Map> paths = processPaths(swagger.getPaths()); - for(String tag : paths.keySet()) { + for (String tag : paths.keySet()) { List ops = paths.get(tag); Map operation = processOperations(config, tag, ops); operation.put("basePath", basePath); @@ -131,36 +153,37 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); - + allOperations.add(new HashMap(operation)); - for(int i = 0; i < allOperations.size(); i++) { + for (int i = 0; i < allOperations.size(); i++) { Map oo = (Map) allOperations.get(i); - if(i < (allOperations.size() -1)) + if (i < (allOperations.size() - 1)) { oo.put("hasMore", "true"); + } } - for(String templateName : config.apiTemplateFiles().keySet()) { + for (String templateName : config.apiTemplateFiles().keySet()) { String suffix = config.apiTemplateFiles().get(templateName); String filename = config.apiFileFolder() + - File.separator + - config.toApiFilename(tag) + - suffix; + File.separator + + config.toApiFilename(tag) + + suffix; String template = readTemplate(config.templateDir() + File.separator + templateName); Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - public Reader getTemplate (String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); - }; - }) - .defaultValue("") - .compile(template); + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + }) + .defaultValue("") + .compile(template); writeToFile(filename, tmpl.execute(operation)); files.add(new File(filename)); } } - if(System.getProperty("debugOperations") != null) { + if (System.getProperty("debugOperations") != null) { System.out.println("############ Operation info ############"); Json.prettyPrint(allOperations); } @@ -172,7 +195,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Map apis = new HashMap(); apis.put("apis", allOperations); - if(swagger.getHost() != null) { + if (swagger.getHost() != null) { bundle.put("host", swagger.getHost()); } bundle.put("basePath", basePath); @@ -184,7 +207,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { if (swagger.getExternalDocs() != null) { bundle.put("externalDocs", swagger.getExternalDocs()); } - for(int i = 0; i < allModels.size() - 1; i++) { + for (int i = 0; i < allModels.size() - 1; i++) { HashMap cm = (HashMap) allModels.get(i); CodegenModel m = cm.get("model"); m.hasMoreModels = true; @@ -192,35 +215,36 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { config.postProcessSupportingFileData(bundle); - if(System.getProperty("debugSupportingFiles") != null) { + if (System.getProperty("debugSupportingFiles") != null) { System.out.println("############ Supporting file info ############"); Json.prettyPrint(bundle); } - for(SupportingFile support : config.supportingFiles()) { + for (SupportingFile support : config.supportingFiles()) { String outputFolder = config.outputFolder(); - if(support.folder != null && !"".equals(support.folder)) + if (isNotEmpty(support.folder)) { outputFolder += File.separator + support.folder; + } File of = new File(outputFolder); - if(!of.isDirectory()) + if (!of.isDirectory()) { of.mkdirs(); + } String outputFilename = outputFolder + File.separator + support.destinationFilename; - if(support.templateFile.endsWith("mustache")) { + if (support.templateFile.endsWith("mustache")) { String template = readTemplate(config.templateDir() + File.separator + support.templateFile); Template tmpl = Mustache.compiler() - .withLoader(new Mustache.TemplateLoader() { - public Reader getTemplate (String name) { - return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); - }; - }) - .defaultValue("") - .compile(template); + .withLoader(new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return getTemplateReader(config.templateDir() + File.separator + name + ".mustache"); + } + }) + .defaultValue("") + .compile(template); writeToFile(outputFilename, tmpl.execute(bundle)); files.add(new File(outputFilename)); - } - else { + } else { String template = readTemplate(config.templateDir() + File.separator + support.templateFile); FileUtils.writeStringToFile(new File(outputFilename), template); System.out.println("copying file to " + outputFilename); @@ -229,8 +253,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } config.processSwagger(swagger); - } - catch (Exception e) { + } catch (Exception e) { e.printStackTrace(); } return files; @@ -238,9 +261,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { public Map> processPaths(Map paths) { Map> ops = new HashMap>(); - List tags = null; - for(String resourcePath : paths.keySet()) { + for (String resourcePath : paths.keySet()) { Path path = paths.get(resourcePath); processOperation(resourcePath, "get", path.getGet(), ops); processOperation(resourcePath, "put", path.getPut(), ops); @@ -254,18 +276,15 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { public SecuritySchemeDefinition fromSecurity(String name) { Map map = swagger.getSecurityDefinitions(); - if(map == null) + if (map == null) { return null; - SecuritySchemeDefinition scheme = map.get(name); - if(scheme == null) - return null; - return scheme; + } + return map.get(name); } - public void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations) { - if(operation != null) { + if (operation != null) { List tags = operation.getTags(); if (tags == null) { tags = new ArrayList(); @@ -279,20 +298,22 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { config.addOperationToGroup(sanitizeTag(tag), resourcePath, operation, co, operations); List>> securities = operation.getSecurity(); - if(securities == null) + if (securities == null) { continue; + } Map authMethods = new HashMap(); for (Map> security : securities) { if (security.size() != 1) { //Not sure what to do continue; } - String securityName = security.keySet().iterator().next(); + String securityName = security.keySet().iterator().next(); SecuritySchemeDefinition securityDefinition = fromSecurity(securityName); - if(securityDefinition != null) + if (securityDefinition != null) { authMethods.put(securityName, securityDefinition); + } } - if(!authMethods.isEmpty()) { + if (!authMethods.isEmpty()) { co.authMethods = config.fromSecurity(authMethods); } } @@ -301,13 +322,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { protected String sanitizeTag(String tag) { // remove spaces and make strong case - String [] parts = tag.split(" "); - StringBuffer buf = new StringBuffer(); - for(String part: parts) { - if(!"".equals(part)) { - buf.append(Character.toUpperCase(part.charAt(0))); - if(part.length() > 1) - buf.append(part.substring(1)); + String[] parts = tag.split(" "); + StringBuilder buf = new StringBuilder(); + for (String part : parts) { + if (isNotEmpty(part)) { + buf.append(capitalize(part)); } } return buf.toString().replaceAll("[^a-zA-Z ]", ""); @@ -322,30 +341,31 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operations.put("package", config.apiPackage()); Set allImports = new LinkedHashSet(); - for(CodegenOperation op: ops) { + for (CodegenOperation op : ops) { allImports.addAll(op.imports); } List> imports = new ArrayList>(); - for(String i: allImports) { + for (String nextImport : allImports) { Map im = new LinkedHashMap(); - String m = config.importMapping().get(i); - if(m == null) - m = config.toModelImport(i); - if(m != null) { - im.put("import", m); + String mapping = config.importMapping().get(nextImport); + if (mapping == null) { + mapping = config.toModelImport(nextImport); + } + if (mapping != null) { + im.put("import", mapping); imports.add(im); } } operations.put("imports", imports); config.postProcessOperations(operations); - if(objs.size() > 0) { + if (objs.size() > 0) { List os = (List) objs.get("operation"); - if(os != null && os.size() > 0) { + if (os != null && os.size() > 0) { CodegenOperation op = os.get(os.size() - 1); - op.hasMore = null; + op.hasMore = null; } } return operations; @@ -355,9 +375,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { Map objs = new HashMap(); objs.put("package", config.modelPackage()); List models = new ArrayList(); - List model = new ArrayList(); Set allImports = new LinkedHashSet(); - for(String key: definitions.keySet()) { + for (String key : definitions.keySet()) { Model mm = definitions.get(key); CodegenModel cm = config.fromModel(key, mm); Map mo = new HashMap(); @@ -368,19 +387,20 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { objs.put("models", models); List> imports = new ArrayList>(); - for(String i: allImports) { + for (String nextImport : allImports) { Map im = new LinkedHashMap(); - String m = config.importMapping().get(i); - if(m == null) - m = config.toModelImport(i); - if(m != null && !config.defaultIncludes().contains(m)) { - im.put("import", m); + String mapping = config.importMapping().get(nextImport); + if (mapping == null) { + mapping = config.toModelImport(nextImport); + } + if (mapping != null && !config.defaultIncludes().contains(mapping)) { + im.put("import", mapping); imports.add(im); } // add instantiation types - m = config.instantiationTypes().get(i); - if(m != null && !config.defaultIncludes().contains(m)) { - im.put("import", m); + mapping = config.instantiationTypes().get(nextImport); + if (mapping != null && !config.defaultIncludes().contains(mapping)) { + im.put("import", mapping); imports.add(im); } } From 810716254056993d5e152f36d6e66f859f5a58a1 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 24 Mar 2015 16:24:31 +0800 Subject: [PATCH 04/21] update ruby codgen for better naming convention --- .../codegen/languages/RubyClientCodegen.java | 68 +++- samples/client/petstore/ruby/lib/Pet_api.rb | 324 ------------------ samples/client/petstore/ruby/lib/Store_api.rb | 109 ------ samples/client/petstore/ruby/lib/User_api.rb | 297 ---------------- .../ruby/lib/{PetApi.rb => pet_api.rb} | 28 +- .../ruby/lib/{StoreApi.rb => store_api.rb} | 12 +- .../ruby/lib/{UserApi.rb => user_api.rb} | 0 .../ruby/models/{Category.rb => category.rb} | 0 .../ruby/models/{Order.rb => order.rb} | 14 +- .../petstore/ruby/models/{Pet.rb => pet.rb} | 8 +- .../petstore/ruby/models/{Tag.rb => tag.rb} | 0 .../petstore/ruby/models/{User.rb => user.rb} | 20 +- 12 files changed, 108 insertions(+), 772 deletions(-) delete mode 100644 samples/client/petstore/ruby/lib/Pet_api.rb delete mode 100644 samples/client/petstore/ruby/lib/Store_api.rb delete mode 100644 samples/client/petstore/ruby/lib/User_api.rb rename samples/client/petstore/ruby/lib/{PetApi.rb => pet_api.rb} (92%) rename samples/client/petstore/ruby/lib/{StoreApi.rb => store_api.rb} (93%) rename samples/client/petstore/ruby/lib/{UserApi.rb => user_api.rb} (100%) rename samples/client/petstore/ruby/models/{Category.rb => category.rb} (100%) rename samples/client/petstore/ruby/models/{Order.rb => order.rb} (75%) rename samples/client/petstore/ruby/models/{Pet.rb => pet.rb} (86%) rename samples/client/petstore/ruby/models/{Tag.rb => tag.rb} (100%) rename samples/client/petstore/ruby/models/{User.rb => user.rb} (68%) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java index ee65073be1b..7afa202f7cf 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java @@ -39,7 +39,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "int") + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", "break", "do", "false", "next", "rescue", "then", "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", "if", "not", "return", "undef", "yield") ); additionalProperties.put("invokerPackage", invokerPackage); @@ -117,4 +117,70 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public String toDefaultValue(Property p) { return "null"; } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // if it's all uppper case, convert to lower case + if (name.matches("^[A-Z_]*$")) + name = name.toLowerCase(); + + // camelize (lower first character) the variable name + // petId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if(reservedWords.contains(name) || name.matches("^\\d.*")) + name = escapeReservedWord(name); + + return name; + } + + @Override + public String toParamName(String name) { + // should be the same as variable name + return toVarName(name); + } + + @Override + public String toModelName(String name) { + // model name cannot use reserved keyword, e.g. return + if(reservedWords.contains(name)) + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + + // camelize the model name + // phone_number => PhoneNumber + return camelize(name); + } + + @Override + public String toModelFilename(String name) { + // model name cannot use reserved keyword, e.g. return + if(reservedWords.contains(name)) + throw new RuntimeException(name + " (reserved word) cannot be used as a model name"); + + // underscore the model file name + // PhoneNumber.rb => phone_number.rb + return underscore(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); + + // e.g. PhoneNumberApi.rb => phone_number_api.rb + return underscore(name) + "_api"; + } + + @Override + public String toApiName(String name) { + if(name.length() == 0) + return "DefaultApi"; + // e.g. phone_number_api => PhoneNumberApi + return camelize(name) + "Api"; + } + } diff --git a/samples/client/petstore/ruby/lib/Pet_api.rb b/samples/client/petstore/ruby/lib/Pet_api.rb deleted file mode 100644 index 6eabb746b68..00000000000 --- a/samples/client/petstore/ruby/lib/Pet_api.rb +++ /dev/null @@ -1,324 +0,0 @@ -require "uri" - -class Pet_api - basePath = "http://petstore.swagger.wordnik.com/api" - # apiInvoker = APIInvoker - - def self.escapeString(string) - URI.encode(string.to_s) - end - - def self.get_pet_by_id (pet_id,opts={}) - query_param_keys = [] - - # verify existence of params - raise "pet_id is required" if pet_id.nil? - # set default values and merge with input - options = { - :pet_id => pet_id}.merge(opts) - - #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - Pet.new(response) - - end - -def self.delete_pet (pet_id,opts={}) - query_param_keys = [] - - # verify existence of params - raise "pet_id is required" if pet_id.nil? - # set default values and merge with input - options = { - :pet_id => pet_id}.merge(opts) - - #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.partial_update (pet_id,body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "pet_id is required" if pet_id.nil? - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :pet_id => pet_id, - :body => body}.merge(opts) - - #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - response = Swagger::Request.new(:PATCH, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - response.map {|response|Pet.new(response)} - - end - -def self.update_pet_with_form (pet_id,name,status,opts={}) - query_param_keys = [] - - # verify existence of params - raise "pet_id is required" if pet_id.nil? - # set default values and merge with input - options = { - :pet_id => pet_id, - :name => name, - :status => status}.merge(opts) - - #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.upload_file (additional_metadata,body,opts={}) - query_param_keys = [] - - # set default values and merge with input - options = { - :additional_metadata => additional_metadata, - :body => body}.merge(opts) - - #resource path - path = "/pet/uploadImage".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.add_pet (body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :body => body}.merge(opts) - - #resource path - path = "/pet".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.update_pet (body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :body => body}.merge(opts) - - #resource path - path = "/pet".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.find_pets_by_status (status= "available",opts={}) - query_param_keys = [:status] - - # verify existence of params - raise "status is required" if status.nil? - # set default values and merge with input - options = { - :status => status}.merge(opts) - - #resource path - path = "/pet/findByStatus".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - response.map {|response|Pet.new(response)} - - end - -def self.find_pets_by_tags (tags,opts={}) - query_param_keys = [:tags] - - # verify existence of params - raise "tags is required" if tags.nil? - # set default values and merge with input - options = { - :tags => tags}.merge(opts) - - #resource path - path = "/pet/findByTags".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - response.map {|response|Pet.new(response)} - - end - -end - diff --git a/samples/client/petstore/ruby/lib/Store_api.rb b/samples/client/petstore/ruby/lib/Store_api.rb deleted file mode 100644 index 40964dbf99f..00000000000 --- a/samples/client/petstore/ruby/lib/Store_api.rb +++ /dev/null @@ -1,109 +0,0 @@ -require "uri" - -class Store_api - basePath = "http://petstore.swagger.wordnik.com/api" - # apiInvoker = APIInvoker - - def self.escapeString(string) - URI.encode(string.to_s) - end - - def self.get_order_by_id (order_id,opts={}) - query_param_keys = [] - - # verify existence of params - raise "order_id is required" if order_id.nil? - # set default values and merge with input - options = { - :order_id => order_id}.merge(opts) - - #resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - Order.new(response) - - end - -def self.delete_order (order_id,opts={}) - query_param_keys = [] - - # verify existence of params - raise "order_id is required" if order_id.nil? - # set default values and merge with input - options = { - :order_id => order_id}.merge(opts) - - #resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.place_order (body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :body => body}.merge(opts) - - #resource path - path = "/store/order".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -end - diff --git a/samples/client/petstore/ruby/lib/User_api.rb b/samples/client/petstore/ruby/lib/User_api.rb deleted file mode 100644 index 205bda90503..00000000000 --- a/samples/client/petstore/ruby/lib/User_api.rb +++ /dev/null @@ -1,297 +0,0 @@ -require "uri" - -class User_api - basePath = "http://petstore.swagger.wordnik.com/api" - # apiInvoker = APIInvoker - - def self.escapeString(string) - URI.encode(string.to_s) - end - - def self.update_user (username,body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "username is required" if username.nil? - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :username => username, - :body => body}.merge(opts) - - #resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:PUT, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.delete_user (username,opts={}) - query_param_keys = [] - - # verify existence of params - raise "username is required" if username.nil? - # set default values and merge with input - options = { - :username => username}.merge(opts) - - #resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - Swagger::Request.new(:DELETE, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.get_user_by_name (username,opts={}) - query_param_keys = [] - - # verify existence of params - raise "username is required" if username.nil? - # set default values and merge with input - options = { - :username => username}.merge(opts) - - #resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', escapeString(username)) - - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - User.new(response) - - end - -def self.login_user (username,password,opts={}) - query_param_keys = [:username,:password] - - # verify existence of params - raise "username is required" if username.nil? - raise "password is required" if password.nil? - # set default values and merge with input - options = { - :username => username, - :password => password}.merge(opts) - - #resource path - path = "/user/login".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - response = Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body }).make.body - string.new(response) - - end - -def self.logout_user (opts={}) - query_param_keys = [] - - # set default values and merge with input - options = { - }.merge(opts) - - #resource path - path = "/user/logout".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - Swagger::Request.new(:GET, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.create_user (body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :body => body}.merge(opts) - - #resource path - path = "/user".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.create_users_with_array_input (body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :body => body}.merge(opts) - - #resource path - path = "/user/createWithArray".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -def self.create_users_with_list_input (body,opts={}) - query_param_keys = [] - - # verify existence of params - raise "body is required" if body.nil? - # set default values and merge with input - options = { - :body => body}.merge(opts) - - #resource path - path = "/user/createWithList".sub('{format}','json') - - - # pull querystring keys from options - queryopts = options.select do |key,value| - query_param_keys.include? key - end - - headers = nil - post_body = nil - if body != nil - if body.is_a?(Array) - array = Array.new - body.each do |item| - if item.respond_to?("to_body".to_sym) - array.push item.to_body - else - array.push item - end - end - post_body = array - - else - if body.respond_to?("to_body".to_sym) - post_body = body.to_body - else - post_body = body - end - end - end - Swagger::Request.new(:POST, path, {:params=>queryopts,:headers=>headers, :body=>post_body}).make - - - end - -end - diff --git a/samples/client/petstore/ruby/lib/PetApi.rb b/samples/client/petstore/ruby/lib/pet_api.rb similarity index 92% rename from samples/client/petstore/ruby/lib/PetApi.rb rename to samples/client/petstore/ruby/lib/pet_api.rb index d80009a5380..e8b9644453c 100644 --- a/samples/client/petstore/ruby/lib/PetApi.rb +++ b/samples/client/petstore/ruby/lib/pet_api.rb @@ -215,19 +215,19 @@ class PetApi end - def self.getPetById (petId, opts={}) + def self.getPetById (pet_id, opts={}) query_param_keys = [] # set default values and merge with input options = { - :'petId' => petId + :'pet_id' => pet_id }.merge(opts) #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) # pull querystring keys from options @@ -257,21 +257,21 @@ class PetApi end - def self.updatePetWithForm (petId,name,status, opts={}) + def self.updatePetWithForm (pet_id,name,status, opts={}) query_param_keys = [] # set default values and merge with input options = { - :'petId' => petId, + :'pet_id' => pet_id, :'name' => name, :'status' => status }.merge(opts) #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) # pull querystring keys from options @@ -302,7 +302,7 @@ class PetApi end - def self.deletePet (api_key,petId, opts={}) + def self.deletePet (api_key,pet_id, opts={}) query_param_keys = [] @@ -310,12 +310,12 @@ class PetApi # set default values and merge with input options = { :'api_key' => api_key, - :'petId' => petId + :'pet_id' => pet_id }.merge(opts) #resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) # pull querystring keys from options @@ -344,21 +344,21 @@ class PetApi end - def self.uploadFile (petId,additionalMetadata,file, opts={}) + def self.uploadFile (pet_id,additional_metadata,file, opts={}) query_param_keys = [] # set default values and merge with input options = { - :'petId' => petId, - :'additionalMetadata' => additionalMetadata, + :'pet_id' => pet_id, + :'additional_metadata' => additional_metadata, :'file' => file }.merge(opts) #resource path - path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(petId)) + path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', escapeString(pet_id)) # pull querystring keys from options @@ -378,7 +378,7 @@ class PetApi # form parameters form_parameter_hash = {} - form_parameter_hash["additionalMetadata"] = additionalMetadata + form_parameter_hash["additionalMetadata"] = additional_metadata form_parameter_hash["file"] = file diff --git a/samples/client/petstore/ruby/lib/StoreApi.rb b/samples/client/petstore/ruby/lib/store_api.rb similarity index 93% rename from samples/client/petstore/ruby/lib/StoreApi.rb rename to samples/client/petstore/ruby/lib/store_api.rb index 2e9f8fe7ea9..4c553185ef3 100644 --- a/samples/client/petstore/ruby/lib/StoreApi.rb +++ b/samples/client/petstore/ruby/lib/store_api.rb @@ -112,19 +112,19 @@ class StoreApi end - def self.getOrderById (orderId, opts={}) + def self.getOrderById (order_id, opts={}) query_param_keys = [] # set default values and merge with input options = { - :'orderId' => orderId + :'order_id' => order_id }.merge(opts) #resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(orderId)) + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) # pull querystring keys from options @@ -154,19 +154,19 @@ class StoreApi end - def self.deleteOrder (orderId, opts={}) + def self.deleteOrder (order_id, opts={}) query_param_keys = [] # set default values and merge with input options = { - :'orderId' => orderId + :'order_id' => order_id }.merge(opts) #resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(orderId)) + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', escapeString(order_id)) # pull querystring keys from options diff --git a/samples/client/petstore/ruby/lib/UserApi.rb b/samples/client/petstore/ruby/lib/user_api.rb similarity index 100% rename from samples/client/petstore/ruby/lib/UserApi.rb rename to samples/client/petstore/ruby/lib/user_api.rb diff --git a/samples/client/petstore/ruby/models/Category.rb b/samples/client/petstore/ruby/models/category.rb similarity index 100% rename from samples/client/petstore/ruby/models/Category.rb rename to samples/client/petstore/ruby/models/category.rb diff --git a/samples/client/petstore/ruby/models/Order.rb b/samples/client/petstore/ruby/models/order.rb similarity index 75% rename from samples/client/petstore/ruby/models/Order.rb rename to samples/client/petstore/ruby/models/order.rb index e7db88e16c9..5434fbd8e2d 100644 --- a/samples/client/petstore/ruby/models/Order.rb +++ b/samples/client/petstore/ruby/models/order.rb @@ -1,13 +1,13 @@ class Order - attr_accessor :id, :petId, :quantity, :shipDate, :status, :complete + attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete # :internal => :external def self.attribute_map { :id => :'id', - :petId => :'petId', + :pet_id => :'petId', :quantity => :'quantity', - :shipDate => :'shipDate', + :ship_date => :'shipDate', :status => :'status', :complete => :'complete' @@ -22,16 +22,16 @@ class Order @id = attributes["id"] end - if self.class.attribute_map[:"petId"] - @petId = attributes["petId"] + if self.class.attribute_map[:"pet_id"] + @pet_id = attributes["petId"] end if self.class.attribute_map[:"quantity"] @quantity = attributes["quantity"] end - if self.class.attribute_map[:"shipDate"] - @shipDate = attributes["shipDate"] + if self.class.attribute_map[:"ship_date"] + @ship_date = attributes["shipDate"] end if self.class.attribute_map[:"status"] diff --git a/samples/client/petstore/ruby/models/Pet.rb b/samples/client/petstore/ruby/models/pet.rb similarity index 86% rename from samples/client/petstore/ruby/models/Pet.rb rename to samples/client/petstore/ruby/models/pet.rb index b279ad5eb3e..38767b46dd7 100644 --- a/samples/client/petstore/ruby/models/Pet.rb +++ b/samples/client/petstore/ruby/models/pet.rb @@ -1,13 +1,13 @@ class Pet - attr_accessor :id, :category, :name, :photoUrls, :tags, :status + attr_accessor :id, :category, :name, :photo_urls, :tags, :status # :internal => :external def self.attribute_map { :id => :'id', :category => :'category', :name => :'name', - :photoUrls => :'photoUrls', + :photo_urls => :'photoUrls', :tags => :'tags', :status => :'status' @@ -30,9 +30,9 @@ class Pet @name = attributes["name"] end - if self.class.attribute_map[:"photoUrls"] + if self.class.attribute_map[:"photo_urls"] if (value = attributes["photoUrls"]).is_a?(Array) - @photoUrls = value + @photo_urls = value end end diff --git a/samples/client/petstore/ruby/models/Tag.rb b/samples/client/petstore/ruby/models/tag.rb similarity index 100% rename from samples/client/petstore/ruby/models/Tag.rb rename to samples/client/petstore/ruby/models/tag.rb diff --git a/samples/client/petstore/ruby/models/User.rb b/samples/client/petstore/ruby/models/user.rb similarity index 68% rename from samples/client/petstore/ruby/models/User.rb rename to samples/client/petstore/ruby/models/user.rb index f70f6794ebe..e270392a3b8 100644 --- a/samples/client/petstore/ruby/models/User.rb +++ b/samples/client/petstore/ruby/models/user.rb @@ -1,17 +1,17 @@ class User - attr_accessor :id, :username, :firstName, :lastName, :email, :password, :phone, :userStatus + attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status # :internal => :external def self.attribute_map { :id => :'id', :username => :'username', - :firstName => :'firstName', - :lastName => :'lastName', + :first_name => :'firstName', + :last_name => :'lastName', :email => :'email', :password => :'password', :phone => :'phone', - :userStatus => :'userStatus' + :user_status => :'userStatus' } end @@ -28,12 +28,12 @@ class User @username = attributes["username"] end - if self.class.attribute_map[:"firstName"] - @firstName = attributes["firstName"] + if self.class.attribute_map[:"first_name"] + @first_name = attributes["firstName"] end - if self.class.attribute_map[:"lastName"] - @lastName = attributes["lastName"] + if self.class.attribute_map[:"last_name"] + @last_name = attributes["lastName"] end if self.class.attribute_map[:"email"] @@ -48,8 +48,8 @@ class User @phone = attributes["phone"] end - if self.class.attribute_map[:"userStatus"] - @userStatus = attributes["userStatus"] + if self.class.attribute_map[:"user_status"] + @user_status = attributes["userStatus"] end end From fb3e44ecc426f1285ea2b0d0040e9d62de385b66 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 24 Mar 2015 16:34:41 +0800 Subject: [PATCH 05/21] break down ruby reservedWord list into multiple lines --- .../swagger/codegen/languages/RubyClientCodegen.java | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java index 7afa202f7cf..f2f0f00df87 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/RubyClientCodegen.java @@ -39,7 +39,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", "break", "do", "false", "next", "rescue", "then", "when", "END", "case", "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", "if", "not", "return", "undef", "yield") + "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "begin", "defined?", "ensure", "module", "redo", "super", "until", "BEGIN", + "break", "do", "false", "next", "rescue", "then", "when", "END", "case", + "else", "for", "nil", "retry", "true", "while", "alias", "class", "elsif", + "if", "not", "return", "undef", "yield") ); additionalProperties.put("invokerPackage", invokerPackage); From 8ba444141ecabc5206bb0a1e3f34e4155db68dcb Mon Sep 17 00:00:00 2001 From: MerkushevKirill Date: Wed, 25 Mar 2015 01:59:55 +0300 Subject: [PATCH 06/21] add - new command line interface in distribution module can replace Codegen and MetaGenerator classes. Provides a bit different cli interface based on refactored pom from #541, affects #349 ``` usage: swagger [] The most commonly used swagger commands are: generate Generate code with chosen lang help Display help information langs Shows available langs meta MetaGenerator. Generator for creating a new template set and configuration for Codegen. The output will be based on the language you specify, and includes default templates to include. ``` **generate** and **meta** commands have same as current cli options --- modules/swagger-codegen-distribution/pom.xml | 173 ++++++++++-------- .../swagger/codegen/SwaggerCodegen.java | 30 +++ .../wordnik/swagger/codegen/cmd/Generate.java | 120 ++++++++++++ .../wordnik/swagger/codegen/cmd/Langs.java | 23 +++ .../com/wordnik/swagger/codegen/cmd/Meta.java | 144 +++++++++++++++ 5 files changed, 411 insertions(+), 79 deletions(-) create mode 100644 modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java create mode 100644 modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java create mode 100644 modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java create mode 100644 modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java diff --git a/modules/swagger-codegen-distribution/pom.xml b/modules/swagger-codegen-distribution/pom.xml index 634ad084c0c..aea6ed3be63 100644 --- a/modules/swagger-codegen-distribution/pom.xml +++ b/modules/swagger-codegen-distribution/pom.xml @@ -1,80 +1,95 @@ - - - com.wordnik - swagger-codegen-project - 2.1.3-M1-SNAPSHOT - ../.. - - 4.0.0 - com.wordnik - swagger-codegen-distribution - jar - swagger-codegen (executable) - 2.1.3-M1-SNAPSHOT - - src/test/scala - target/classes - target/test-classes - install - target - ${project.artifactId}-${project.version} - - - org.apache.maven.plugins - maven-jar-plugin - - - - com.wordnik.swagger.codegen.Codegen - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - package - - shade - - - false - true - - ${java.io.tmpdir}/dependency-reduced-pom.xml - - - - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - package - - shade - - - - - - - - - - - - - - com.wordnik - swagger-codegen - ${project.parent.version} - - + + + com.wordnik + swagger-codegen-project + 2.1.3-M1-SNAPSHOT + ../.. + + 4.0.0 + + swagger-codegen-distribution + jar + + swagger-codegen (executable) + + + swagger-cli + + + org.apache.maven.plugins + maven-jar-plugin + + + + com.wordnik.swagger.codegen.SwaggerCodegen + + + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + + reduced-pom + package + + shade + + + false + true + + ${java.io.tmpdir}/dependency-reduced-pom.xml + + + + + process-resources + package + + shade + + + + + + + + + + + + + + + + com.wordnik + swagger-codegen + ${project.version} + + + + + io.airlift + airline + 0.7 + + + + com.googlecode.lambdaj + lambdaj + 2.3.3 + + + + org.slf4j + slf4j-simple + ${slf4j-version} + + + + \ No newline at end of file diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java new file mode 100644 index 00000000000..61bb55c54b0 --- /dev/null +++ b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java @@ -0,0 +1,30 @@ +package com.wordnik.swagger.codegen; + +import com.wordnik.swagger.codegen.cmd.Generate; +import com.wordnik.swagger.codegen.cmd.Langs; +import com.wordnik.swagger.codegen.cmd.Meta; +import io.airlift.airline.Cli; +import io.airlift.airline.Help; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 17:56 + */ +public class SwaggerCodegen { + + + public static void main(String[] args) { + Cli.CliBuilder builder = Cli.builder("swagger") + .withDescription("Swagger code generator CLI. More info on swagger.io") + .withDefaultCommand(Langs.class) + .withCommands( + Generate.class, + Meta.class, + Langs.class, + Help.class + ); + + builder.build().parse(args).run(); + } +} diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java new file mode 100644 index 00000000000..94523867bbe --- /dev/null +++ b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java @@ -0,0 +1,120 @@ +package com.wordnik.swagger.codegen.cmd; + +import com.wordnik.swagger.codegen.ClientOptInput; +import com.wordnik.swagger.codegen.ClientOpts; +import com.wordnik.swagger.codegen.CodegenConfig; +import com.wordnik.swagger.codegen.DefaultGenerator; +import com.wordnik.swagger.models.Swagger; +import io.airlift.airline.Command; +import io.airlift.airline.Option; +import io.swagger.parser.SwaggerParser; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.ServiceLoader; + +import static java.util.ServiceLoader.load; +import static org.apache.commons.lang3.StringUtils.isNotEmpty; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 20:22 + */ + +@Command(name = "generate", description = "Generate code with chosen lang") +public class Generate implements Runnable { + + public static final Logger LOG = LoggerFactory.getLogger(Generate.class); + + public static final String TEMPLATE_DIR_PARAM = "templateDir"; + + @Option(name = {"-v", "--verbose"}, description = "verbose mode") + public boolean verbose; + + @Option(name = {"-l", "--lang"}, title = "language", required = true, + description = "client language to generate (maybe class name in classpath, required)") + public String lang; + + @Option(name = {"-o", "--output"}, title = "output directory", + description = "where to write the generated files (current dir by default)") + public String output = ""; + + @Option(name = {"-i", "--input-spec"}, title = "spec file", required = true, + description = "location of the swagger spec, as URL or file (required)") + public String spec; + + @Option(name = {"-t", "--template-dir"}, title = "template directory", + description = "folder containing the template files") + public String templateDir; + + @Option(name = {"-a", "--auth"}, title = "authorization", + description = "adds authorization headers when fetching the swagger definitions remotely. " + + "Pass in a URL-encoded string of name:header with a comma separating multiple values") + public String auth; + + @Override + public void run() { + verbosed(verbose); + + ClientOptInput input = new ClientOptInput(); + + if (isNotEmpty(auth)) { + input.setAuth(auth); + } + + CodegenConfig config = forName(lang); + config.setOutputDir(new File(output).getAbsolutePath()); + + if (null != templateDir) { + config.additionalProperties().put(TEMPLATE_DIR_PARAM, new File(templateDir).getAbsolutePath()); + } + + input.setConfig(config); + + Swagger swagger = new SwaggerParser().read(spec, input.getAuthorizationValues(), true); + new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); + } + + /** + * If true parameter, adds system properties which enables debug mode in generator + * @param verbose - if true, enables debug mode + */ + private void verbosed(boolean verbose) { + if (!verbose) { + return; + } + LOG.info("\nVERBOSE MODE: ON. Additional debug options are injected" + + "\n - [debugSwagger] prints the swagger specification as interpreted by the codegen" + + "\n - [debugModels] prints models passed to the template engine" + + "\n - [debugOperations] prints operations passed to the template engine" + + "\n - [debugSupportingFiles] prints additional data passed to the template engine"); + + System.setProperty("debugSwagger", ""); + System.setProperty("debugModels", ""); + System.setProperty("debugOperations", ""); + System.setProperty("debugSupportingFiles", ""); + } + + /** + * Tries to load config class with SPI first, then with class name directly from classpath + * @param name name of config, or full qualified class name in classpath + * @return config class + */ + private static CodegenConfig forName(String name) { + ServiceLoader loader = load(CodegenConfig.class); + for (CodegenConfig config : loader) { + if (config.getName().equals(name)) { + return config; + } + } + + // else try to load directly + try { + return (CodegenConfig) Class.forName(name).newInstance(); + } catch (Exception e) { + throw new RuntimeException("Can't load config class with name ".concat(name), e); + } + } +} diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java new file mode 100644 index 00000000000..7942804d434 --- /dev/null +++ b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java @@ -0,0 +1,23 @@ +package com.wordnik.swagger.codegen.cmd; + +import ch.lambdaj.collection.LambdaIterable; +import com.wordnik.swagger.codegen.CodegenConfig; +import io.airlift.airline.Command; + +import static ch.lambdaj.Lambda.on; +import static ch.lambdaj.collection.LambdaCollections.with; +import static java.util.ServiceLoader.load; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 20:25 + */ +@Command(name = "langs", description = "Shows available langs") +public class Langs implements Runnable { + @Override + public void run() { + LambdaIterable langs = with(load(CodegenConfig.class)).extract(on(CodegenConfig.class).getName()); + System.out.printf("Available languages: %s%n", langs); + } +} diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java new file mode 100644 index 00000000000..5f070c43bfd --- /dev/null +++ b/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java @@ -0,0 +1,144 @@ +package com.wordnik.swagger.codegen.cmd; + +import ch.lambdaj.function.convert.Converter; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import com.samskivert.mustache.Mustache; +import com.wordnik.swagger.codegen.DefaultGenerator; +import com.wordnik.swagger.codegen.SupportingFile; +import io.airlift.airline.Command; +import io.airlift.airline.Option; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.Reader; +import java.util.List; +import java.util.Map; + +import static ch.lambdaj.collection.LambdaCollections.with; +import static com.google.common.base.Joiner.on; + +/** + * User: lanwen + * Date: 24.03.15 + * Time: 20:22 + */ + +@Command(name = "meta", description = "MetaGenerator. Generator for creating a new template set " + + "and configuration for Codegen. The output will be based on the language you " + + "specify, and includes default templates to include.") +public class Meta implements Runnable { + + public static final Logger LOG = LoggerFactory.getLogger(Meta.class); + + public static final String TEMPLATE_DIR_CLASSPATH = "codegen"; + public static final String MUSTACHE_EXTENSION = ".mustache"; + + @Option(name = {"-o", "--output"}, title = "output directory", + description = "where to write the generated files (current dir by default)") + public String outputFolder = ""; + + @Option(name = {"-n", "--name"}, title = "name", + description = "the human-readable name of the generator") + public String name = "default"; + + @Option(name = {"-p", "--package"}, title = "package", + description = "the package to put the main class into (defaults to com.wordnik.swagger.codegen)") + public String targetPackage = "com.wordnik.swagger.codegen"; + + @Override + public void run() { + final File targetDir = new File(outputFolder); + LOG.info("writing to folder [{}]", targetDir.getAbsolutePath()); + + String mainClass = StringUtils.capitalize(name) + "Generator"; + + List supportingFiles = ImmutableList.of( + new SupportingFile("pom.mustache", "", "pom.xml"), + new SupportingFile("generatorClass.mustache", + on(File.separator).join("src/main/java", asPath(targetPackage)), mainClass.concat(".java")), + new SupportingFile("README.mustache", "", "README.md"), + new SupportingFile("api.template", "src/main/resources" + File.separator + name, "api.mustache"), + new SupportingFile("model.template", "src/main/resources" + File.separator + name, "model.mustache"), + new SupportingFile("services.mustache", + "src/main/resources/META-INF/services", "com.wordnik.swagger.codegen.CodegenConfig") + ); + + Map data = new ImmutableMap.Builder() + .put("generatorPackage", targetPackage) + .put("generatorClass", mainClass) + .put("name", name) + .put("fullyQualifiedGeneratorClass", targetPackage + "." + mainClass).build(); + + + with(supportingFiles).convert(processFiles(targetDir, data)); + } + + /** + * Converter method to process supporting files: execute with mustache, + * or simply copy to destination directory + * @param targetDir - destination directory + * @param data - map with additional params needed to process templates + * @return converter object to pass to lambdaj + */ + private Converter processFiles(final File targetDir, final Map data) { + return new Converter() { + private DefaultGenerator generator = new DefaultGenerator(); + + @Override + public File convert(SupportingFile support) { + try { + File destinationFolder = new File(new File(targetDir.getAbsolutePath()), support.folder); + File outputFile = new File(destinationFolder, support.destinationFilename); + + String template = generator + .readTemplate(new File(TEMPLATE_DIR_CLASSPATH, support.templateFile).getPath()); + String formatted = template; + + if (support.templateFile.endsWith(MUSTACHE_EXTENSION)) { + LOG.info("writing file to {}", outputFile.getAbsolutePath()); + formatted = Mustache.compiler().withLoader(loader(generator)) + .defaultValue("") + .compile(template) + .execute(data); + } else { + LOG.info("copying file to {}", outputFile.getAbsolutePath()); + } + + FileUtils.writeStringToFile(outputFile, formatted); + return outputFile; + + } catch (IOException e) { + throw new RuntimeException("Can't generate project", e); + } + } + }; + } + + /** + * Creates mustache loader for template using classpath loader + * @param generator - class with reader getter + * @return loader for template + */ + private Mustache.TemplateLoader loader(final DefaultGenerator generator) { + return new Mustache.TemplateLoader() { + public Reader getTemplate(String name) { + return generator.getTemplateReader(TEMPLATE_DIR_CLASSPATH + + File.separator + name.concat(MUSTACHE_EXTENSION)); + } + }; + } + + /** + * Converts package name to path on file system + * @param packageName - package name to convert + * @return relative path + */ + private String asPath(String packageName) { + return packageName.replace(".", File.separator); + } +} From de0e108d2713b1239ad99f4272c8c7d4c8bdabbc Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 17:02:03 -0700 Subject: [PATCH 07/21] added property for app name --- .../codegen/languages/ObjcClientCodegen.java | 61 +++++++++++++++---- 1 file changed, 50 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 62f22ee2f44..47c34ad9031 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -34,7 +34,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { templateDir = "objc"; modelPackage = ""; - additionalProperties.put("projectName", "swaggerClient"); + String appName = System.getProperty("appName"); + if(appName == null) { + appName = "swaggerClient"; + } + additionalProperties.put("projectName", appName); defaultIncludes = new HashSet( Arrays.asList( @@ -44,6 +48,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSArray", "NSNumber", + "NSDate", "NSDictionary", "NSMutableArray", "NSMutableDictionary") @@ -52,6 +57,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Arrays.asList( "NSNumber", "NSString", + "NSDate", "NSObject", "bool") ); @@ -66,9 +72,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping = new HashMap(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "SWGDate"); - typeMapping.put("DateTime", "SWGDate"); - // typeMapping.put("Date", "SWGDate"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); typeMapping.put("integer", "NSNumber"); @@ -83,13 +88,13 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "NSObject"); importMapping = new HashMap (); - importMapping.put("Date", "SWGDate"); foundationClasses = new HashSet ( Arrays.asList( "NSNumber", "NSObject", "NSString", + "NSDate", "NSDictionary") ); @@ -147,11 +152,45 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) - return toModelName(swaggerType); - else - return swaggerType + "*"; + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerType = getSwaggerType(inner); + + // In this codition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray*' + if (languageSpecificPrimitives.contains(innerType)) + return getSwaggerType(p) + "*"; + + // In this codition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + else { + String swaggerType = getSwaggerType(p); + + // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this codition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this codition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `' + else { + return swaggerType + "*"; + } + } } @Override @@ -229,4 +268,4 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public String escapeReservedWord(String name) { return "_" + name; } -} \ No newline at end of file +} From db14a3fd05d1673daab03ddf03bad6f8352ee832 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 17:02:12 -0700 Subject: [PATCH 08/21] added property for app name --- bin/objc-petstore.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index 0e4da6eb4b3..7d478719d19 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -33,4 +33,4 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc" -java $JAVA_OPTS -jar $executable $ags +java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags From 31418b39364809f07b0e8938f81332e317457b8d Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 17:02:03 -0700 Subject: [PATCH 09/21] added property for app name --- bin/objc-petstore.sh | 2 +- .../codegen/languages/ObjcClientCodegen.java | 61 +++++++++++++++---- 2 files changed, 51 insertions(+), 12 deletions(-) diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index 0e4da6eb4b3..7d478719d19 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -33,4 +33,4 @@ fi export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc" -java $JAVA_OPTS -jar $executable $ags +java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 62f22ee2f44..47c34ad9031 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -34,7 +34,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { templateDir = "objc"; modelPackage = ""; - additionalProperties.put("projectName", "swaggerClient"); + String appName = System.getProperty("appName"); + if(appName == null) { + appName = "swaggerClient"; + } + additionalProperties.put("projectName", appName); defaultIncludes = new HashSet( Arrays.asList( @@ -44,6 +48,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSArray", "NSNumber", + "NSDate", "NSDictionary", "NSMutableArray", "NSMutableDictionary") @@ -52,6 +57,7 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Arrays.asList( "NSNumber", "NSString", + "NSDate", "NSObject", "bool") ); @@ -66,9 +72,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping = new HashMap(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "SWGDate"); - typeMapping.put("DateTime", "SWGDate"); - // typeMapping.put("Date", "SWGDate"); + typeMapping.put("Date", "NSDate"); + typeMapping.put("DateTime", "NSDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); typeMapping.put("integer", "NSNumber"); @@ -83,13 +88,13 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "NSObject"); importMapping = new HashMap (); - importMapping.put("Date", "SWGDate"); foundationClasses = new HashSet ( Arrays.asList( "NSNumber", "NSObject", "NSString", + "NSDate", "NSDictionary") ); @@ -147,11 +152,45 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String getTypeDeclaration(Property p) { - String swaggerType = getSwaggerType(p); - if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) - return toModelName(swaggerType); - else - return swaggerType + "*"; + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + String innerType = getSwaggerType(inner); + + // In this codition, type of property p is array of primitive, + // return container type with pointer, e.g. `NSArray*' + if (languageSpecificPrimitives.contains(innerType)) + return getSwaggerType(p) + "*"; + + // In this codition, type of property p is array of model, + // return container type combine inner type with pointer, e.g. `NSArray*' + String innerTypeDeclaration = getTypeDeclaration(inner); + + if (innerTypeDeclaration.endsWith("*")) + innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); + + return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; + } + else { + String swaggerType = getSwaggerType(p); + + // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', + // return type of p with pointer, e.g. `NSNumber*' + if (languageSpecificPrimitives.contains(swaggerType) && + foundationClasses.contains(swaggerType)) { + return swaggerType + "*"; + } + // In this codition, type of p is c primitive type, e.g. `bool', + // return type of p, e.g. `bool' + else if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + // In this codition, type of p is objective-c object type, e.g. `SWGPet', + // return type of p with pointer, e.g. `' + else { + return swaggerType + "*"; + } + } } @Override @@ -229,4 +268,4 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { public String escapeReservedWord(String name) { return "_" + name; } -} \ No newline at end of file +} From e82ecf695d5e5b24601fd03d2d5540b90b148c46 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 19:56:04 -0700 Subject: [PATCH 10/21] added array support --- .../main/java/com/wordnik/swagger/codegen/DefaultCodegen.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java index ac7db378602..f0664a72c72 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/DefaultCodegen.java @@ -745,6 +745,8 @@ public class DefaultCodegen { op.isMapContainer = Boolean.TRUE; else if ("list".equalsIgnoreCase(cm.containerType)) op.isListContainer = Boolean.TRUE; + else if ("array".equalsIgnoreCase(cm.containerType)) + op.isListContainer = Boolean.TRUE; } else op.returnSimpleType = true; From 2ce0049ce40e9cf99f3fd895973cd55c0ead359e Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 19:56:28 -0700 Subject: [PATCH 11/21] updated templates to fix petstore build error --- .../src/main/resources/objc/api-body.mustache | 34 +++++++++++++++---- .../objc/apiNonPrimitiveResponse.mustache | 9 +++-- 2 files changed, 32 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache index 2998682cbad..ffead406a86 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -110,18 +110,25 @@ static NSString * basePath = @"{{basePath}}"; } {{/bodyParam}} {{^bodyParam}} - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - {{#formParams}}{{#notFile}} + {{#formParams}} + {{#notFile}} formParams[@"{{paramName}}"] = {{paramName}}; {{/notFile}}{{#isFile}} requestContentType = @"multipart/form-data"; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } [bodyDictionary addObject:{{paramName}}]; {{paramName}}.paramName = @"{{baseName}}"; - {{/isFile}}{{/formParams}} + {{/isFile}} + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } [bodyDictionary addObject:formParams]; + {{/formParams}} {{/bodyParam}} {{#requiredParamCount}} @@ -134,11 +141,26 @@ static NSString * basePath = @"{{basePath}}"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; - {{#returnContainer}}{{>apiBodyResponseWithContainer}}{{/returnContainer}} + {{#returnContainer}} + // response is in a container + {{>apiBodyResponseWithContainer}}{{/returnContainer}} + {{#returnSimpleType}} - {{#returnTypeIsPrimitive}}{{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} - {{#returnBaseType}}{{>apiNonPrimitiveResponse}}{{/returnBaseType}} + // non container response + + {{#returnTypeIsPrimitive}} + // primitive response + {{>apiPrimitiveResponse}}{{/returnTypeIsPrimitive}} + + {{#returnBaseType}} + // complex response + {{>apiNonPrimitiveResponse}}{{/returnBaseType}} {{/returnSimpleType}} + + {{^returnSimpleType}}{{^returnContainer}} + // it's void + {{>voidResponse}} + {{/returnContainer}}{{/returnSimpleType}} } {{/operation}} diff --git a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache index 1ab814c0589..d27a9f601ed 100644 --- a/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/apiNonPrimitiveResponse.mustache @@ -13,12 +13,11 @@ {{^returnBaseType}}completionBlock(error);{{/returnBaseType}} return; } - {{#returnBaseType}} - {{returnBaseType}} *result = nil; + {{#returnType}}{{returnType}} result = nil; if (data) { - result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc]initWithValues: data]; + result = [[{{#instantiationType}}NSClassFromString(@"{{{instantiationType}}}") {{/instantiationType}}{{^instantiationType}}{{{returnBaseType}}} {{/instantiationType}} alloc] {{#returnContainer}}{{#isMapContainer}}initWithDictionary{{/isMapContainer}}{{#isListContainer}}initWithValues{{/isListContainer}}{{/returnContainer}}{{^returnContainer}}initWithValues {{/returnContainer}}: data]; } - {{#returnBaseType}}completionBlock(result , nil);{{/returnBaseType}} - {{/returnBaseType}} + {{#returnType}}completionBlock(result , nil);{{/returnType}} + {{/returnType}} }]; {{/returnTypeIsPrimitive}} \ No newline at end of file From 30acfc1869e68df332087ede87d695f99d727018 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 19:56:38 -0700 Subject: [PATCH 12/21] added sys property --- .../codegen/languages/ObjcClientCodegen.java | 53 ++++--------------- 1 file changed, 9 insertions(+), 44 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java index 47c34ad9031..2e91cafa992 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/ObjcClientCodegen.java @@ -48,7 +48,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { "NSObject", "NSArray", "NSNumber", - "NSDate", "NSDictionary", "NSMutableArray", "NSMutableDictionary") @@ -57,7 +56,6 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { Arrays.asList( "NSNumber", "NSString", - "NSDate", "NSObject", "bool") ); @@ -72,8 +70,9 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping = new HashMap(); typeMapping.put("enum", "NSString"); - typeMapping.put("Date", "NSDate"); - typeMapping.put("DateTime", "NSDate"); + typeMapping.put("Date", "SWGDate"); + typeMapping.put("DateTime", "SWGDate"); + // typeMapping.put("Date", "SWGDate"); typeMapping.put("boolean", "NSNumber"); typeMapping.put("string", "NSString"); typeMapping.put("integer", "NSNumber"); @@ -88,13 +87,13 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("object", "NSObject"); importMapping = new HashMap (); + importMapping.put("Date", "SWGDate"); foundationClasses = new HashSet ( Arrays.asList( "NSNumber", "NSObject", "NSString", - "NSDate", "NSDictionary") ); @@ -152,45 +151,11 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String getTypeDeclaration(Property p) { - if (p instanceof ArrayProperty) { - ArrayProperty ap = (ArrayProperty) p; - Property inner = ap.getItems(); - String innerType = getSwaggerType(inner); - - // In this codition, type of property p is array of primitive, - // return container type with pointer, e.g. `NSArray*' - if (languageSpecificPrimitives.contains(innerType)) - return getSwaggerType(p) + "*"; - - // In this codition, type of property p is array of model, - // return container type combine inner type with pointer, e.g. `NSArray*' - String innerTypeDeclaration = getTypeDeclaration(inner); - - if (innerTypeDeclaration.endsWith("*")) - innerTypeDeclaration = innerTypeDeclaration.substring(0, innerTypeDeclaration.length() - 1); - - return getSwaggerType(p) + "<" + innerTypeDeclaration + ">*"; - } - else { - String swaggerType = getSwaggerType(p); - - // In this codition, type of p is objective-c primitive type, e.g. `NSSNumber', - // return type of p with pointer, e.g. `NSNumber*' - if (languageSpecificPrimitives.contains(swaggerType) && - foundationClasses.contains(swaggerType)) { - return swaggerType + "*"; - } - // In this codition, type of p is c primitive type, e.g. `bool', - // return type of p, e.g. `bool' - else if (languageSpecificPrimitives.contains(swaggerType)) { - return swaggerType; - } - // In this codition, type of p is objective-c object type, e.g. `SWGPet', - // return type of p with pointer, e.g. `' - else { - return swaggerType + "*"; - } - } + String swaggerType = getSwaggerType(p); + if(languageSpecificPrimitives.contains(swaggerType) && !foundationClasses.contains(swaggerType)) + return toModelName(swaggerType); + else + return swaggerType + "*"; } @Override From 85463f049c765a820c8d7c89d59b1bb03b4512e3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 19:56:45 -0700 Subject: [PATCH 13/21] rebuilt sample --- .../PetstoreClient/ViewController.m | 16 +- samples/client/petstore/objc/Podfile | 2 +- samples/client/petstore/objc/Podfile.lock | 2 +- .../client/petstore/objc/client/SWGPetApi.m | 176 ++++++++++++++++-- .../client/petstore/objc/client/SWGStoreApi.m | 57 ++++-- .../client/petstore/objc/client/SWGUserApi.m | 119 ++++++++---- 6 files changed, 291 insertions(+), 81 deletions(-) diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m index ebdb5a42e99..631a18f44e9 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient/ViewController.m @@ -22,15 +22,15 @@ SWGPetApi * api = [[SWGPetApi alloc] init]; -// [api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) { -// NSLog(@"%@", [output asDictionary]); -// [output set_id:@101]; -// [api addPetWithCompletionBlock:output completionHandler:^(NSError *error) { -// NSLog(@"Done!"); -// }]; + [api getPetByIdWithCompletionBlock:@10 completionHandler:^(SWGPet *output, NSError *error) { + NSLog(@"%@", [output asDictionary]); + [output set_id:@101]; + [api addPetWithCompletionBlock:output completionHandler:^(NSError *error) { + NSLog(@"Done!"); + }]; - // load data into file -// }]; +// load data into file + }]; NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test-1" ofType:@"png"]; NSData *myData = [NSData dataWithContentsOfFile:filePath]; diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile index e6b8aab6518..08674feba4c 100644 --- a/samples/client/petstore/objc/Podfile +++ b/samples/client/petstore/objc/Podfile @@ -1,3 +1,3 @@ platform :ios, '6.0' -xcodeproj 'swaggerClient/swaggerClient.xcodeproj' +xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' pod 'AFNetworking', '~> 2.1' diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index a3466a08296..ed27b0f2376 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -27,4 +27,4 @@ DEPENDENCIES: SPEC CHECKSUMS: AFNetworking: 8bee59492a6ff15d69130efa4d0dc67e0094a52a -COCOAPODS: 0.35.0 +COCOAPODS: 0.36.0 diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 1305f552c8d..5d134bb1f27 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -109,6 +109,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"PUT" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } @@ -170,6 +190,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } @@ -199,18 +239,18 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // response is in a container // array container response type return [client dictionary: requestUrl method: @"GET" @@ -225,8 +265,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return; } + if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + + + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + + [objs addObject:d]; + } + completionBlock(objs, nil); + } + + }]; + + + } @@ -256,18 +312,18 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // response is in a container // array container response type return [client dictionary: requestUrl method: @"GET" @@ -282,8 +338,24 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return; } + if([data isKindOfClass:[NSArray class]]){ + NSMutableArray * objs = [[NSMutableArray alloc] initWithCapacity:[data count]]; + for (NSDictionary* dict in (NSArray*)data) { + + + SWGPet* d = [[SWGPet alloc]initWithValues: dict]; + + [objs addObject:d]; + } + completionBlock(objs, nil); + } + + }]; + + + } @@ -312,12 +384,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -325,8 +395,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // non container response + + + + // complex response // comples response type return [client dictionary: requestUrl @@ -342,16 +418,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return; } - - SWGPet *result = nil; + SWGPet* result = nil; if (data) { - result = [[SWGPet alloc]initWithValues: data]; + result = [[SWGPet alloc] initWithValues : data]; } completionBlock(result , nil); }]; + + } -(NSNumber*) updatePetWithFormWithCompletionBlock: (NSString*) petId @@ -381,23 +458,53 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + formParams[@"name"] = name; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } + [bodyDictionary addObject:formParams]; + + formParams[@"status"] = status; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } [bodyDictionary addObject:formParams]; + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"POST" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } @@ -429,12 +536,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -442,6 +547,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } @@ -472,31 +597,44 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; + formParams[@"additionalMetadata"] = additionalMetadata; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } + [bodyDictionary addObject:formParams]; + + requestContentType = @"multipart/form-data"; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } [bodyDictionary addObject:file]; file.paramName = @"file"; + if(bodyDictionary == nil) { + bodyDictionary = [[NSMutableArray alloc] init]; + } [bodyDictionary addObject:formParams]; + SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + - // primitive response type + - - // no return base type - return [client stringWithCompletionBlock: requestUrl + // it's void + return [client stringWithCompletionBlock: requestUrl method: @"POST" queryParams: queryParams body: bodyDictionary @@ -510,9 +648,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } completionBlock(nil); }]; - - - + } diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index b0c42e7d982..3eb015ebc0a 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -73,18 +73,18 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // response is in a container // map container response type return [client dictionary: requestUrl method: @"GET" @@ -107,6 +107,9 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; }]; + + + } @@ -168,8 +171,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // non container response + + + + // complex response // comples response type return [client dictionary: requestUrl @@ -185,16 +194,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return; } - - SWGOrder *result = nil; + SWGOrder* result = nil; if (data) { - result = [[SWGOrder alloc]initWithValues: data]; + result = [[SWGOrder alloc] initWithValues : data]; } completionBlock(result , nil); }]; + + } -(NSNumber*) getOrderByIdWithCompletionBlock: (NSString*) orderId @@ -222,12 +232,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -235,8 +243,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // non container response + + + + // complex response // comples response type return [client dictionary: requestUrl @@ -252,16 +266,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return; } - - SWGOrder *result = nil; + SWGOrder* result = nil; if (data) { - result = [[SWGOrder alloc]initWithValues: data]; + result = [[SWGOrder alloc] initWithValues : data]; } completionBlock(result , nil); }]; + + } -(NSNumber*) deleteOrderWithCompletionBlock: (NSString*) orderId @@ -289,12 +304,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -302,6 +315,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index fbaafa76fa5..6e33862d111 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -108,12 +108,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + - // primitive response type + - - // no return base type - return [client stringWithCompletionBlock: requestUrl + // it's void + return [client stringWithCompletionBlock: requestUrl method: @"POST" queryParams: queryParams body: bodyDictionary @@ -127,9 +127,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } completionBlock(nil); }]; - - - + } @@ -191,12 +189,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + - // primitive response type + - - // no return base type - return [client stringWithCompletionBlock: requestUrl + // it's void + return [client stringWithCompletionBlock: requestUrl method: @"POST" queryParams: queryParams body: bodyDictionary @@ -210,9 +208,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } completionBlock(nil); }]; - - - + } @@ -274,12 +270,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + - // primitive response type + - - // no return base type - return [client stringWithCompletionBlock: requestUrl + // it's void + return [client stringWithCompletionBlock: requestUrl method: @"POST" queryParams: queryParams body: bodyDictionary @@ -293,9 +289,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } completionBlock(nil); }]; - - - + } @@ -328,12 +322,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -341,7 +333,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // non container response + + + // primitive response // primitive response type return [client stringWithCompletionBlock: requestUrl method: @"GET" @@ -361,8 +358,13 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; + + + // complex response + + } -(NSNumber*) logoutUserWithCompletionBlock: @@ -388,12 +390,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -401,12 +401,12 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + - // primitive response type + - - // no return base type - return [client stringWithCompletionBlock: requestUrl + // it's void + return [client stringWithCompletionBlock: requestUrl method: @"GET" queryParams: queryParams body: bodyDictionary @@ -420,9 +420,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; } completionBlock(nil); }]; - - - + } @@ -451,12 +449,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -464,8 +460,14 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + // non container response + + + + // complex response // comples response type return [client dictionary: requestUrl @@ -481,16 +483,17 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; return; } - - SWGUser *result = nil; + SWGUser* result = nil; if (data) { - result = [[SWGUser alloc]initWithValues: data]; + result = [[SWGUser alloc] initWithValues : data]; } completionBlock(result , nil); }]; + + } -(NSNumber*) updateUserWithCompletionBlock: (NSString*) username @@ -553,6 +556,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"PUT" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } @@ -581,12 +604,10 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; id bodyDictionary = nil; - bodyDictionary = [[NSMutableArray alloc] init]; NSMutableDictionary * formParams = [[NSMutableDictionary alloc]init]; - [bodyDictionary addObject:formParams]; @@ -594,6 +615,26 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; SWGApiClient* client = [SWGApiClient sharedClientFromPool:basePath]; + + + + + // it's void + return [client stringWithCompletionBlock: requestUrl + method: @"DELETE" + queryParams: queryParams + body: bodyDictionary + headerParams: headerParams + requestContentType: requestContentType + responseContentType: responseContentType + completionBlock: ^(NSString *data, NSError *error) { + if (error) { + completionBlock(error); + return; + } + completionBlock(nil); + }]; + } From 56104566fce557bf8b1156ae57e08baffa12a1b2 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 19:57:51 -0700 Subject: [PATCH 14/21] added void response --- .../src/main/resources/objc/voidResponse.mustache | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache diff --git a/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache new file mode 100644 index 00000000000..b128bfd21cc --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/voidResponse.mustache @@ -0,0 +1,14 @@ + return [client 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); + }]; From ceffa10ab7ddfc340437e70a986534b3149781ec Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Tue, 24 Mar 2015 23:24:13 -0700 Subject: [PATCH 15/21] added command-line tests --- pom.xml | 13 ++ .../PetstoreClient.xcodeproj/project.pbxproj | 14 +- .../xcschemes/PetstoreClient.xcscheme | 6 +- .../PetstoreClient/ViewController.m | 3 +- .../PetstoreClientTests/PetApiTest.h | 9 + .../PetstoreClientTests/PetApiTest.m | 181 ++++++++++++++++++ .../PetstoreClientTests/PetstoreClientTests.m | 34 ---- .../petstore/objc/PetstoreClient/pom.xml | 24 +++ 8 files changed, 243 insertions(+), 41 deletions(-) create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.h create mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m delete mode 100644 samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m create mode 100644 samples/client/petstore/objc/PetstoreClient/pom.xml diff --git a/pom.xml b/pom.xml index 13cfee6ca66..24bd8f8a455 100644 --- a/pom.xml +++ b/pom.xml @@ -277,6 +277,19 @@ + + + samples + + + env + samples + + + + samples/client/petstore/objc + + modules/swagger-codegen diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index 349c3f59a88..66a244ebf3a 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -22,7 +22,8 @@ EA6699BD1811D2FB00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; EA6699BE1811D2FB00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; }; EA6699C61811D2FB00A70D03 /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = EA6699C41811D2FB00A70D03 /* InfoPlist.strings */; }; - EA6699C81811D2FB00A70D03 /* PetstoreClientTests.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */; }; + EA6699C81811D2FB00A70D03 /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699C71811D2FB00A70D03 /* PetApiTest.m */; }; + EA8CD3ED1AC2763600C47D0B /* SenTestingKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA8CD3EC1AC2763600C47D0B /* SenTestingKit.framework */; }; EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */; }; EAEA85E51811D3AE00F06E69 /* SWGCategory.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */; }; EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D11811D3AE00F06E69 /* SWGDate.m */; }; @@ -73,7 +74,9 @@ EA6699BB1811D2FB00A70D03 /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = XCTest.framework; path = Library/Frameworks/XCTest.framework; sourceTree = DEVELOPER_DIR; }; EA6699C31811D2FB00A70D03 /* PetstoreClientTests-Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = "PetstoreClientTests-Info.plist"; sourceTree = ""; }; EA6699C51811D2FB00A70D03 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; - EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PetstoreClientTests.m; sourceTree = ""; }; + EA6699C71811D2FB00A70D03 /* PetApiTest.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = PetApiTest.m; sourceTree = ""; }; + EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = PetApiTest.h; sourceTree = ""; }; + EA8CD3EC1AC2763600C47D0B /* SenTestingKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SenTestingKit.framework; path = Library/Frameworks/SenTestingKit.framework; sourceTree = DEVELOPER_DIR; }; EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGApiClient.h; sourceTree = ""; }; EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGApiClient.m; sourceTree = ""; }; EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGCategory.h; sourceTree = ""; }; @@ -120,6 +123,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + EA8CD3ED1AC2763600C47D0B /* SenTestingKit.framework in Frameworks */, EAEA85F11811D8F100F06E69 /* libPods.a in Frameworks */, EA6699BC1811D2FB00A70D03 /* XCTest.framework in Frameworks */, EA6699BE1811D2FB00A70D03 /* UIKit.framework in Frameworks */, @@ -163,6 +167,7 @@ EA6699981811D2FA00A70D03 /* Frameworks */ = { isa = PBXGroup; children = ( + EA8CD3EC1AC2763600C47D0B /* SenTestingKit.framework */, EAEA85F01811D8F100F06E69 /* libPods.a */, EA6699991811D2FA00A70D03 /* Foundation.framework */, EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */, @@ -203,7 +208,8 @@ EA6699C11811D2FB00A70D03 /* PetstoreClientTests */ = { isa = PBXGroup; children = ( - EA6699C71811D2FB00A70D03 /* PetstoreClientTests.m */, + EA8CD3EB1AC274BE00C47D0B /* PetApiTest.h */, + EA6699C71811D2FB00A70D03 /* PetApiTest.m */, EA6699C21811D2FB00A70D03 /* Supporting Files */, ); path = PetstoreClientTests; @@ -409,7 +415,7 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - EA6699C81811D2FB00A70D03 /* PetstoreClientTests.m in Sources */, + EA6699C81811D2FB00A70D03 /* PetApiTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme index 00830cf82b3..fd55bb26268 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/xcuserdata/tony.xcuserdatad/xcschemes/PetstoreClient.xcscheme @@ -58,7 +58,8 @@ ignoresPersistentStateOnLaunch = "NO" debugDocumentVersioning = "YES" allowLocationSimulation = "YES"> - + - + +#import "SWGPetApi.h" + +@interface PetApiTest : XCTestCase { +@private + SWGPetApi * api; +} + +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m new file mode 100644 index 00000000000..0859bccf37d --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m @@ -0,0 +1,181 @@ +#import "PetApiTest.h" +#import "SWGFile.h" + +@implementation PetApiTest + +- (void)setUp { + [super setUp]; + api = [[SWGPetApi alloc ]init]; + [SWGPetApi setBasePath:@"http://localhost:8002/api"]; +} + +- (void)tearDown { + [super tearDown]; +} + +- (void)testGetPetById { + [api getPetByIdWithCompletionBlock:@1 completionHandler:^(SWGPet *output, NSError *error) { + if(error){ + XCTFail(@"got error %@", error); + } + if(output){ + XCTAssertNotNil([output _id], @"token was nil"); + } + }]; +} + +- (void) testAddPet { + SWGPet * petToAdd = [[SWGPet alloc] init]; + [petToAdd set_id:@1000]; + NSMutableArray* tags = [[NSMutableArray alloc] init]; + for(int i = 0; i < 5; i++){ + SWGTag * tag = [[SWGTag alloc] init]; + [tag set_id:[NSNumber numberWithInt:i]]; + [tag setName:[NSString stringWithFormat:@"tag-%d", i]]; + [tags addObject:tag]; + } + [petToAdd setTags:tags]; + [petToAdd setStatus:@"lost"]; + + SWGCategory * category = [[SWGCategory alloc] init]; + [category setName:@"sold"]; + [petToAdd setCategory:category]; + [petToAdd setName:@"dragon"]; + + NSMutableArray* photos = [[NSMutableArray alloc] init]; + for(int i = 0; i < 10; i++){ + NSString * url = [NSString stringWithFormat:@"http://foo.com/photo/%d", i]; + [photos addObject:url]; + } + [petToAdd setPhotoUrls:photos]; + + [api addPetWithCompletionBlock:petToAdd completionHandler:^(NSError *error) { + if(error){ + XCTFail(@"got error %@", error); + } + }]; +} + +- (void) testUpdatePet { + SWGPet * petToAdd = [[SWGPet alloc] init]; + [petToAdd set_id:[NSNumber numberWithInt:1000]]; + NSMutableArray* tags = [[NSMutableArray alloc] init]; + for(int i = 0; i < 5; i++){ + SWGTag * tag = [[SWGTag alloc] init]; + [tag set_id:[NSNumber numberWithInt:i]]; + [tag setName:[NSString stringWithFormat:@"tag-%d", i]]; + [tags addObject:tag]; + } + [petToAdd setTags:tags]; + [petToAdd setStatus:@"lost"]; + + SWGCategory * category = [[SWGCategory alloc] init]; + [category setName:@"sold"]; + [petToAdd setCategory:category]; + [petToAdd setName:@"dragon"]; + + NSMutableArray* photos = [[NSMutableArray alloc] init]; + for(int i = 0; i < 10; i++){ + NSString * url = [NSString stringWithFormat:@"http://foo.com/photo/%d", i]; + [photos addObject:url]; + } + [petToAdd setPhotoUrls:photos]; + + static bool hasResponse = false; + [api addPetWithCompletionBlock:petToAdd completionHandler:^(NSError *error) { + if(error) { + XCTFail(@"got error %@", error); + } + else { + [api getPetByIdWithCompletionBlock:[NSString stringWithFormat:@"%@",[petToAdd _id]] completionHandler:^(SWGPet *output, NSError *error) { + if(error) { + XCTFail(@"got error %@", error); + } + if(output == nil){ + NSLog(@"failed to fetch pet"); + } + else { + SWGPet* pet = [[SWGPet alloc] initWithValues:[output asDictionary]]; + NSLog(@"got the pet"); + + [pet setName:@"programmer"]; + [pet setStatus:@"confused"]; + + [api updatePetWithCompletionBlock:pet + completionHandler:^(NSError *error) { + if(error) { + XCTFail(@"got error %@", error); + } + [api getPetByIdWithCompletionBlock:@1000 completionHandler:^(SWGPet *output, NSError *error) { + if(error) { + XCTFail(@"got error %@", error); + } + if(output == nil){ + NSLog(@"failed to fetch pet"); + } + else { + SWGPet* pet = [[SWGPet alloc] initWithValues:[output asDictionary]]; + XCTAssertNotNil([pet _id], @"pet was nil"); + XCTAssertEqualObjects([pet name], @"programmer", @"pet name was not updated"); + XCTAssertEqualObjects([pet status], @"confused", @"pet status was not updated"); + } + }]; + }]; + } + }]; + } + }]; +} + +- (void)testGetPetByStatus { + bool done = false; + static NSMutableArray* pets = nil; + static NSError * gError = nil; + [api findPetsByStatusWithCompletionBlock:@"available" completionHandler:^(NSArray *output, NSError *error) { + if(error) { + gError = error; + } + if(output == nil){ + NSLog(@"failed to fetch pets"); + } + else { + pets = [[NSMutableArray alloc]init]; + for(SWGPet* pet in output) { + [pets addObject:[[SWGPet alloc] initWithValues:[pet asDictionary]]]; + } + } + }]; + NSDate * loopUntil = [NSDate dateWithTimeIntervalSinceNow:10]; + while(!done && [loopUntil timeIntervalSinceNow] > 0){ + if(gError){ + XCTFail(@"got error %@", gError); + done = true; + } + if(pets){ + for(SWGPet * pet in pets) { + XCTAssertEqualObjects([pet status], @"available", @"got invalid status for pets"); + } + done = true; + } + } +} + +- (void)testGetPetByTags { + [api findPetsByTagsWithCompletionBlock:@"tag1,tag2" completionHandler:^(NSArray *output, NSError *error) { + if(error){ + XCTFail(@"got error %@", error); + } + if(output){ + for(SWGPet * pet in output) { + bool hasTag = false; + for(SWGTag * tag in [pet tags]){ + if([[tag name] isEqualToString:@"tag1"] || [[tag name] isEqualToString:@"tag2"]) + hasTag = true; + } + if(!hasTag) + XCTFail(@"failed to find tag in pet"); + } + } + }]; +} +@end \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m deleted file mode 100644 index f523807b470..00000000000 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetstoreClientTests.m +++ /dev/null @@ -1,34 +0,0 @@ -// -// PetstoreClientTests.m -// PetstoreClientTests -// -// Created by Tony Tam on 10/18/13. -// Copyright (c) 2013 Reverb. All rights reserved. -// - -#import - -@interface PetstoreClientTests : XCTestCase - -@end - -@implementation PetstoreClientTests - -- (void)setUp -{ - [super setUp]; - // Put setup code here. This method is called before the invocation of each test method in the class. -} - -- (void)tearDown -{ - // Put teardown code here. This method is called after the invocation of each test method in the class. - [super tearDown]; -} - -- (void)testExample -{ - XCTFail(@"No implementation for \"%s\"", __PRETTY_FUNCTION__); -} - -@end diff --git a/samples/client/petstore/objc/PetstoreClient/pom.xml b/samples/client/petstore/objc/PetstoreClient/pom.xml new file mode 100644 index 00000000000..513976e90b0 --- /dev/null +++ b/samples/client/petstore/objc/PetstoreClient/pom.xml @@ -0,0 +1,24 @@ + + 4.0.0 + de.felixschulze.my-project + PetstoreClient + xcode + 1.0-SNAPSHOT + Swagger Petstore Client + + + + de.felixschulze.maven.plugins.xcode + xcode-maven-plugin + 1.2 + + PetstoreClient.xcodeproj + PetstoreClient + Debug + iphoneos + + true + + + + From be373f88d46a50c306b18e8c68dd29e5300524d3 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 25 Mar 2015 09:27:12 -0700 Subject: [PATCH 16/21] fixed test errors --- .../PetstoreClientTests/PetApiTest.m | 35 +++-- samples/client/petstore/objc/pom.xml | 128 ++++++++++++++++++ 2 files changed, 148 insertions(+), 15 deletions(-) create mode 100644 samples/client/petstore/objc/pom.xml diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m index 0859bccf37d..398010461e1 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m @@ -6,6 +6,7 @@ - (void)setUp { [super setUp]; api = [[SWGPetApi alloc ]init]; +// [[SWGApiClient sharedClientFromPool]setLoggingEnabled:true]; [SWGPetApi setBasePath:@"http://localhost:8002/api"]; } @@ -14,6 +15,7 @@ } - (void)testGetPetById { + XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetById"]; [api getPetByIdWithCompletionBlock:@1 completionHandler:^(SWGPet *output, NSError *error) { if(error){ XCTFail(@"got error %@", error); @@ -21,10 +23,14 @@ if(output){ XCTAssertNotNil([output _id], @"token was nil"); } + [expectation fulfill]; }]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; } - (void) testAddPet { + XCTestExpectation *expectation = [self expectationWithDescription:@"testAddPet"]; + SWGPet * petToAdd = [[SWGPet alloc] init]; [petToAdd set_id:@1000]; NSMutableArray* tags = [[NSMutableArray alloc] init]; @@ -53,10 +59,14 @@ if(error){ XCTFail(@"got error %@", error); } + [expectation fulfill]; }]; + + [self waitForExpectationsWithTimeout:2.0 handler:nil]; } - (void) testUpdatePet { + XCTestExpectation *expectation = [self expectationWithDescription:@"testUpdatePet"]; SWGPet * petToAdd = [[SWGPet alloc] init]; [petToAdd set_id:[NSNumber numberWithInt:1000]]; NSMutableArray* tags = [[NSMutableArray alloc] init]; @@ -80,7 +90,8 @@ [photos addObject:url]; } [petToAdd setPhotoUrls:photos]; - + dispatch_semaphore_t sema = dispatch_semaphore_create(0); + static bool hasResponse = false; [api addPetWithCompletionBlock:petToAdd completionHandler:^(NSError *error) { if(error) { @@ -119,16 +130,19 @@ XCTAssertEqualObjects([pet name], @"programmer", @"pet name was not updated"); XCTAssertEqualObjects([pet status], @"confused", @"pet status was not updated"); } + [expectation fulfill]; + }]; }]; } }]; } }]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; } - (void)testGetPetByStatus { - bool done = false; + XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByStatus"]; static NSMutableArray* pets = nil; static NSError * gError = nil; [api findPetsByStatusWithCompletionBlock:@"available" completionHandler:^(NSArray *output, NSError *error) { @@ -145,22 +159,11 @@ } } }]; - NSDate * loopUntil = [NSDate dateWithTimeIntervalSinceNow:10]; - while(!done && [loopUntil timeIntervalSinceNow] > 0){ - if(gError){ - XCTFail(@"got error %@", gError); - done = true; - } - if(pets){ - for(SWGPet * pet in pets) { - XCTAssertEqualObjects([pet status], @"available", @"got invalid status for pets"); - } - done = true; - } - } + [self waitForExpectationsWithTimeout:2.0 handler:nil]; } - (void)testGetPetByTags { + XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByTags"]; [api findPetsByTagsWithCompletionBlock:@"tag1,tag2" completionHandler:^(NSArray *output, NSError *error) { if(error){ XCTFail(@"got error %@", error); @@ -176,6 +179,8 @@ XCTFail(@"failed to find tag in pet"); } } + [expectation fulfill]; }]; + [self waitForExpectationsWithTimeout:2.0 handler:nil]; } @end \ No newline at end of file diff --git a/samples/client/petstore/objc/pom.xml b/samples/client/petstore/objc/pom.xml new file mode 100644 index 00000000000..02d38ca25aa --- /dev/null +++ b/samples/client/petstore/objc/pom.xml @@ -0,0 +1,128 @@ + + 4.0.0 + de.felixschulze.my-project + PetstoreClient + pom + 1.0-SNAPSHOT + Objective-C Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.mortbay.jetty + jetty-maven-plugin + ${jetty-version} + + true + 15 + ${project.build.directory}/swagger-java-jersey-sample-app-${webapp-version}.war + + / + + 8079 + stopit + + + 8002 + 60000 + 8443 + + + + + + start-jetty + pre-integration-test + + run-war + + + 0 + true + + + + stop-jetty + post-integration-test + + stop + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + install-pods + pre-integration-test + + exec + + + pod + + install + + + + + xcodebuild-test + integration-test + + exec + + + xcodebuild + + -workspace + PetstoreClient.xcworkspace + -scheme + PetstoreClient + test + -destination + platform=iOS Simulator,name=iPhone 6,OS=8.2 + + + + + + + + + + com.wordnik + swagger-java-jersey-sample-app + ${webapp-version} + war + test + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 1.5.4-M1-SNAPSHOT + 8.1.11.v20130520 + + From d2f5b9ea65dff008ea655b329536f3cfcfe16b00 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 25 Mar 2015 11:11:04 -0700 Subject: [PATCH 17/21] added recursion check --- .../codegen/examples/ExampleGenerator.java | 30 ++++++++++++------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java index c03f15a1466..80063625440 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/ExampleGenerator.java @@ -24,6 +24,7 @@ public class ExampleGenerator { public List> generate(Map examples, List mediaTypes, Property property) { List> output = new ArrayList>(); + Set processedModels = new HashSet(); if(examples == null ) { if(mediaTypes == null) { // assume application/json for this @@ -33,7 +34,7 @@ public class ExampleGenerator { Map kv = new HashMap(); kv.put("contentType", mediaType); if(property != null && mediaType.startsWith("application/json")) { - String example = Json.pretty(resolvePropertyToExample(mediaType, property)); + String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); if(example != null) { example = example.replaceAll("\n", "\\\\n"); @@ -69,7 +70,7 @@ public class ExampleGenerator { return output; } - protected Object resolvePropertyToExample(String mediaType, Property property) { + protected Object resolvePropertyToExample(String mediaType, Property property, Set processedModels) { if(property.getExample() != null) { return property.getExample(); } @@ -83,7 +84,7 @@ public class ExampleGenerator { Property innerType = ((ArrayProperty)property).getItems(); if(innerType != null) { Object[] output = new Object[]{ - resolvePropertyToExample(mediaType, innerType) + resolvePropertyToExample(mediaType, innerType, processedModels) }; return output; } @@ -116,11 +117,11 @@ public class ExampleGenerator { Map mp = new HashMap(); if(property.getName() != null) { mp.put(property.getName(), - resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties())); + resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels)); } else { mp.put("key", - resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties())); + resolvePropertyToExample(mediaType, ((MapProperty)property).getAdditionalProperties(), processedModels)); } return mp; } @@ -128,9 +129,10 @@ public class ExampleGenerator { return "{}"; } else if(property instanceof RefProperty) { - Model model = examples.get(((RefProperty)property).getSimpleRef()); + String simpleName = ((RefProperty)property).getSimpleRef(); + Model model = examples.get(simpleName); if(model != null) - return resolveModelToExample(mediaType, model); + return resolveModelToExample(simpleName, mediaType, model, processedModels); } else if(property instanceof UUIDProperty) { return "046b6c7f-0b8a-43b9-b35d-6489e6daee91"; @@ -139,14 +141,20 @@ public class ExampleGenerator { return ""; } - public Object resolveModelToExample(String mediaType, Model model) { + public Object resolveModelToExample(String name, String mediaType, Model model, Set processedModels) { + if(processedModels.contains(name)) { + return ""; + } if(model instanceof ModelImpl) { + processedModels.add(name); ModelImpl impl = (ModelImpl) model; Map values = new HashMap(); - for(String name : impl.getProperties().keySet()) { - Property property = impl.getProperties().get(name); - values.put(name, resolvePropertyToExample(mediaType, property)); + if(impl != null && impl.getProperties() != null) { + for(String propertyName : impl.getProperties().keySet()) { + Property property = impl.getProperties().get(propertyName); + values.put(propertyName, resolvePropertyToExample(mediaType, property, processedModels)); + } } return values; From f577345b143abaf78916984b85a4d50464b23fc7 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 25 Mar 2015 12:11:40 -0700 Subject: [PATCH 18/21] fixed examples, readme --- README.md | 10 +++++----- bin/android-java-petstore.sh | 9 ++------- bin/android-java-wordnik-api.sh | 9 ++------- bin/dynamic-html.sh | 9 ++------- bin/html-petstore.sh | 9 ++------- bin/java-petstore.sh | 9 ++------- bin/java-wordnik-api.sh | 9 ++------- bin/jaxrs-petstore-server.sh | 9 ++------- bin/nodejs-petstore-server.sh | 9 ++------- bin/objc-petstore.sh | 9 ++------- bin/objc-wordnik-api.sh | 9 ++------- bin/php-petstore.sh | 9 ++------- bin/python-petstore.sh | 9 ++------- bin/ruby-petstore.sh | 9 ++------- bin/scala-async-petstore.sh | 9 ++------- bin/scala-petstore.sh | 9 ++------- bin/scala-wordnik-api.sh | 9 ++------- bin/scalatra-petstore-server.sh | 9 ++------- bin/tizen-petstore.sh | 9 ++------- 19 files changed, 41 insertions(+), 131 deletions(-) diff --git a/README.md b/README.md index 2f0b62d89de..ec3c7e67a44 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ You can build a client against the swagger sample [petstore](http://petstore.swa This will run the generator with this command: ``` -java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.3-M1-SNAPSHOT.jar \ +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ -l java \ -o samples/client/petstore/java @@ -97,7 +97,7 @@ You can look at `modules/swagger-codegen/src/main/resources/${your-language}` fo If you're starting a project with a new language and don't see what you need, swagger-codegen can help you create a project to generate your own libraries: ``` -java -cp modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.3-M1-SNAPSHOT.jar \ +java -cp modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ com.wordnik.swagger.codegen.MetaGenerator \ -o output/myLibrary -n myClientCodegen -p com.my.company.codegen ``` @@ -200,7 +200,7 @@ You can also use the codegen to generate a server for a couple different framewo ### node.js ``` -java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.3-M1-SNAPSHOT.jar \ +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ -l nodejs \ -o samples/server/petstore/nodejs @@ -212,7 +212,7 @@ java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distributi ### scala scalatra ``` -java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.3-M1-SNAPSHOT.jar \ +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ -l scalatra \ -o samples/server/petstore/scalatra @@ -221,7 +221,7 @@ java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distributi ### java jax-rs ``` -java -jar modules/swagger-codegen-distribution/target/swagger-codegen-distribution-2.1.3-M1-SNAPSHOT.jar \ +java -jar modules/swagger-codegen-cli/target/swagger-codegen-cli.jar generate \ -i http://petstore.swagger.io/v2/swagger.json \ -l jaxrs \ -o samples/server/petstore/jaxrs diff --git a/bin/android-java-petstore.sh b/bin/android-java-petstore.sh index 5747ff49531..2f228bc29a7 100755 --- a/bin/android-java-petstore.sh +++ b/bin/android-java-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android-java" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l android -o samples/client/petstore/android-java" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/android-java-wordnik-api.sh b/bin/android-java-wordnik-api.sh index 3f2654a1685..551afcfa09b 100755 --- a/bin/android-java-wordnik-api.sh +++ b/bin/android-java-wordnik-api.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l android -o samples/client/wordnik/android-java" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l android -o samples/client/wordnik/android-java" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/dynamic-html.sh b/bin/dynamic-html.sh index b19a18cfb96..37e9c71294d 100755 --- a/bin/dynamic-html.sh +++ b/bin/dynamic-html.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l dynamic-html -o samples/dynamic-html" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l dynamic-html -o samples/dynamic-html" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/html-petstore.sh b/bin/html-petstore.sh index 00ce8c174b9..7c0791284ca 100755 --- a/bin/html-petstore.sh +++ b/bin/html-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l html -o samples/html" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l html -o samples/html" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-petstore.sh b/bin/java-petstore.sh index 04345b346ab..3beff2f07ce 100755 --- a/bin/java-petstore.sh +++ b/bin/java-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l java -o samples/client/petstore/java" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/java-wordnik-api.sh b/bin/java-wordnik-api.sh index b4cae8590bc..38b5afd37f4 100755 --- a/bin/java-wordnik-api.sh +++ b/bin/java-wordnik-api.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l java -o samples/client/wordnik/java" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l java -o samples/client/wordnik/java" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh index be8f17502f7..1154fffbd1c 100755 --- a/bin/jaxrs-petstore-server.sh +++ b/bin/jaxrs-petstore-server.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/nodejs-petstore-server.sh b/bin/nodejs-petstore-server.sh index 53bedc84b4d..5d797903791 100755 --- a/bin/nodejs-petstore-server.sh +++ b/bin/nodejs-petstore-server.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l nodejs -o samples/server/petstore/nodejs" java $JAVA_OPTS -Dservice -jar $executable $ags diff --git a/bin/objc-petstore.sh b/bin/objc-petstore.sh index 7d478719d19..feefc99a28c 100755 --- a/bin/objc-petstore.sh +++ b/bin/objc-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l objc -o samples/client/petstore/objc" java -DappName=PetstoreClient $JAVA_OPTS -jar $executable $ags diff --git a/bin/objc-wordnik-api.sh b/bin/objc-wordnik-api.sh index 68eb1b8226d..54807ca0512 100755 --- a/bin/objc-wordnik-api.sh +++ b/bin/objc-wordnik-api.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l objc -o samples/client/wordnik/objc" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l objc -o samples/client/wordnik/objc" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/php-petstore.sh b/bin/php-petstore.sh index fe210b2de24..f4efe06f51b 100755 --- a/bin/php-petstore.sh +++ b/bin/php-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l php -o samples/client/petstore/php" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l php -o samples/client/petstore/php" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/python-petstore.sh b/bin/python-petstore.sh index 2ef1f44ad7e..148733fdf14 100755 --- a/bin/python-petstore.sh +++ b/bin/python-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python -o samples/client/petstore/python" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l python -o samples/client/petstore/python" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/ruby-petstore.sh b/bin/ruby-petstore.sh index bd7c30496bf..2d17f6cb82c 100755 --- a/bin/ruby-petstore.sh +++ b/bin/ruby-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -o samples/client/petstore/ruby" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l ruby -o samples/client/petstore/ruby" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-async-petstore.sh b/bin/scala-async-petstore.sh index 108f40f82e1..4198e1ec3f8 100755 --- a/bin/scala-async-petstore.sh +++ b/bin/scala-async-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l async-scala -o samples/client/petstore/async-scala" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l async-scala -o samples/client/petstore/async-scala" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-petstore.sh b/bin/scala-petstore.sh index 55e54b6c74d..5ed773acf16 100755 --- a/bin/scala-petstore.sh +++ b/bin/scala-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scala -o samples/client/petstore/scala" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scala -o samples/client/petstore/scala" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scala-wordnik-api.sh b/bin/scala-wordnik-api.sh index 73c1f8e7dec..88692e34082 100755 --- a/bin/scala-wordnik-api.sh +++ b/bin/scala-wordnik-api.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l scala -o samples/client/wordnik/scala" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/wordnik.json -l scala -o samples/client/wordnik/scala" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/scalatra-petstore-server.sh b/bin/scalatra-petstore-server.sh index c84f0e2f4e0..2095ced8057 100755 --- a/bin/scalatra-petstore-server.sh +++ b/bin/scalatra-petstore-server.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scalatra -o samples/server/petstore/scalatra" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l scalatra -o samples/server/petstore/scalatra" java $JAVA_OPTS -jar $executable $ags diff --git a/bin/tizen-petstore.sh b/bin/tizen-petstore.sh index a0b1b4bdd96..42b531103d2 100755 --- a/bin/tizen-petstore.sh +++ b/bin/tizen-petstore.sh @@ -17,12 +17,7 @@ if [ ! -d "${APP_DIR}" ]; then APP_DIR=`cd "${APP_DIR}"; pwd` fi -root=./modules/swagger-codegen-distribution/pom.xml - -# gets version of swagger-codegen -version=$(sed '//,/<\/project>/d;//!d;s/ *<\/\?version> *//g' $root | sed -n '2p' | sed -e 's,.*\([^<]*\).*,\1,g') - -executable="./modules/swagger-codegen-distribution/target/swagger-codegen-distribution-$version.jar" +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" if [ ! -f "$executable" ] then @@ -31,6 +26,6 @@ fi # if you've executed sbt assembly previously it will use that instead. export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" -ags="$@ -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l tizen -o samples/client/petstore/tizen" +ags="$@ generate -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l tizen -o samples/client/petstore/tizen" java $JAVA_OPTS -jar $executable $ags From b7c2c3448ea6eac01c4a1698a77a6dc826c709cc Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 25 Mar 2015 12:12:04 -0700 Subject: [PATCH 19/21] renamed package --- .../pom.xml | 4 ++-- .../src/main/java/com/wordnik/swagger/codegen/Readme.java | 0 .../main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java | 0 .../main/java/com/wordnik/swagger/codegen/cmd/Generate.java | 0 .../src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java | 0 .../src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java | 0 .../src/main/resources/logback.xml | 0 pom.xml | 2 +- 8 files changed, 3 insertions(+), 3 deletions(-) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/pom.xml (97%) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/src/main/java/com/wordnik/swagger/codegen/Readme.java (100%) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java (100%) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java (100%) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java (100%) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java (100%) rename modules/{swagger-codegen-distribution => swagger-codegen-cli}/src/main/resources/logback.xml (100%) diff --git a/modules/swagger-codegen-distribution/pom.xml b/modules/swagger-codegen-cli/pom.xml similarity index 97% rename from modules/swagger-codegen-distribution/pom.xml rename to modules/swagger-codegen-cli/pom.xml index aea6ed3be63..f17c48deee7 100644 --- a/modules/swagger-codegen-distribution/pom.xml +++ b/modules/swagger-codegen-cli/pom.xml @@ -8,13 +8,13 @@ 4.0.0 - swagger-codegen-distribution + swagger-codegen-cli jar swagger-codegen (executable) - swagger-cli + swagger-codegen-cli org.apache.maven.plugins diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/Readme.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/Readme.java similarity index 100% rename from modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/Readme.java rename to modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/Readme.java diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java similarity index 100% rename from modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java rename to modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/SwaggerCodegen.java diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java similarity index 100% rename from modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java rename to modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Generate.java diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java similarity index 100% rename from modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java rename to modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Langs.java diff --git a/modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java b/modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java similarity index 100% rename from modules/swagger-codegen-distribution/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java rename to modules/swagger-codegen-cli/src/main/java/com/wordnik/swagger/codegen/cmd/Meta.java diff --git a/modules/swagger-codegen-distribution/src/main/resources/logback.xml b/modules/swagger-codegen-cli/src/main/resources/logback.xml similarity index 100% rename from modules/swagger-codegen-distribution/src/main/resources/logback.xml rename to modules/swagger-codegen-cli/src/main/resources/logback.xml diff --git a/pom.xml b/pom.xml index 24bd8f8a455..7e8e7b9ddcd 100644 --- a/pom.xml +++ b/pom.xml @@ -293,7 +293,7 @@ modules/swagger-codegen - modules/swagger-codegen-distribution + modules/swagger-codegen-cli modules/swagger-generator From 20add5b58e3435a185ab04dc36740d84a46274a6 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 25 Mar 2015 16:16:03 -0700 Subject: [PATCH 20/21] updated tests, jetty --- .../PetstoreClientTests/PetApiTest.m | 13 ++---- samples/client/petstore/objc/pom.xml | 42 +++++-------------- 2 files changed, 14 insertions(+), 41 deletions(-) diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m index 398010461e1..a4539c9255b 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClientTests/PetApiTest.m @@ -90,9 +90,7 @@ [photos addObject:url]; } [petToAdd setPhotoUrls:photos]; - dispatch_semaphore_t sema = dispatch_semaphore_create(0); - static bool hasResponse = false; [api addPetWithCompletionBlock:petToAdd completionHandler:^(NSError *error) { if(error) { XCTFail(@"got error %@", error); @@ -143,20 +141,15 @@ - (void)testGetPetByStatus { XCTestExpectation *expectation = [self expectationWithDescription:@"testGetPetByStatus"]; - static NSMutableArray* pets = nil; - static NSError * gError = nil; [api findPetsByStatusWithCompletionBlock:@"available" completionHandler:^(NSArray *output, NSError *error) { if(error) { - gError = error; + XCTFail(@"got error %@", error); } if(output == nil){ - NSLog(@"failed to fetch pets"); + XCTFail(@"failed to fetch pets"); } else { - pets = [[NSMutableArray alloc]init]; - for(SWGPet* pet in output) { - [pets addObject:[[SWGPet alloc] initWithValues:[pet asDictionary]]]; - } + [expectation fulfill]; } }]; [self waitForExpectationsWithTimeout:2.0 handler:nil]; diff --git a/samples/client/petstore/objc/pom.xml b/samples/client/petstore/objc/pom.xml index 02d38ca25aa..0a6e65e1d4f 100644 --- a/samples/client/petstore/objc/pom.xml +++ b/samples/client/petstore/objc/pom.xml @@ -22,47 +22,27 @@ - org.mortbay.jetty + org.eclipse.jetty jetty-maven-plugin ${jetty-version} - true - 15 ${project.build.directory}/swagger-java-jersey-sample-app-${webapp-version}.war - - / - - 8079 - stopit - - - 8002 - 60000 - 8443 - - + alpha + 9099 + + 8002 + start-jetty pre-integration-test - run-war - - - 0 - true - - - - stop-jetty - post-integration-test - - stop + deploy-war - - + + org.codehaus.mojo exec-maven-plugin @@ -110,8 +90,8 @@ swagger-java-jersey-sample-app ${webapp-version} war - test + sonatype-snapshots @@ -123,6 +103,6 @@ 1.5.4-M1-SNAPSHOT - 8.1.11.v20130520 + 9.2.9.v20150224 From a2dc7675595580070093a3d7fb98b03be9742f13 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 25 Mar 2015 20:57:48 -0700 Subject: [PATCH 21/21] Update .travis.yml --- .travis.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.travis.yml b/.travis.yml index 85a33a2d847..73c80821ba5 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,3 +1,4 @@ +sudo: false language: java script: mvn verify jdk: