From fe92889b1069ab090acfbd00d8fb513e5c5f1f07 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Mon, 23 Mar 2015 17:01:35 -0700 Subject: [PATCH 01/75] merge latest from develop_2.0 to to fork --- .../client/petstore/php/models/Category.php | 60 ------------- samples/client/petstore/php/models/Order.php | 79 ----------------- samples/client/petstore/php/models/Pet.php | 2 +- samples/client/petstore/php/models/Tag.php | 60 ------------- samples/client/petstore/php/models/pet.php | 79 ----------------- samples/client/petstore/php/models/user.php | 87 ------------------- 6 files changed, 1 insertion(+), 366 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/Tag.php delete mode 100644 samples/client/petstore/php/models/pet.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 98e7ba24800..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 2770e8bbbdf..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 index eee7fa3784c..e980d858a2f 100644 --- a/samples/client/petstore/php/models/Pet.php +++ b/samples/client/petstore/php/models/Pet.php @@ -22,7 +22,7 @@ * */ -class Pet implements ArrayAccess { +class pet implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'category' => 'Category', diff --git a/samples/client/petstore/php/models/Tag.php b/samples/client/petstore/php/models/Tag.php deleted file mode 100644 index f8efc998df6..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/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/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 970facaa8ae79e15cee4bd81020ff7ee1fc473c3 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Mon, 23 Mar 2015 17:01:49 -0700 Subject: [PATCH 02/75] merge latest from develop_2.0 to fork --- samples/client/petstore/php/models/User.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/php/models/User.php b/samples/client/petstore/php/models/User.php index d6b520eba51..1ae88e5e2aa 100644 --- a/samples/client/petstore/php/models/User.php +++ b/samples/client/petstore/php/models/User.php @@ -22,7 +22,7 @@ * */ -class User implements ArrayAccess { +class user implements ArrayAccess { static $swaggerTypes = array( 'id' => 'int', 'username' => 'string', From 0811e0bce35fe4da022b4a695d07ba1e56c6214d Mon Sep 17 00:00:00 2001 From: Camille Chafer Date: Thu, 2 Apr 2015 16:22:52 +0200 Subject: [PATCH 03/75] Add Akka-Scala client generator. This client uses Spray as Http Client. --- .../wordnik/swagger/codegen/CodegenModel.java | 2 +- .../swagger/codegen/CodegenResponse.java | 1 + .../swagger/codegen/CodegenSecurity.java | 11 +- .../swagger/codegen/DefaultCodegen.java | 31 +- .../languages/AkkaScalaClientCodegen.java | 365 ++++++++++++++++++ .../com.wordnik.swagger.codegen.CodegenConfig | 3 +- .../main/resources/akka-scala/api.mustache | 43 +++ .../resources/akka-scala/apiInvoker.mustache | 323 ++++++++++++++++ .../resources/akka-scala/apiRequest.mustache | 50 +++ .../resources/akka-scala/apiSettings.mustache | 32 ++ .../akka-scala/enumsSerializers.mustache | 42 ++ .../resources/akka-scala/javadoc.mustache | 21 + .../akka-scala/methodParameters.mustache | 1 + .../main/resources/akka-scala/model.mustache | 30 ++ .../akka-scala/operationReturnType.mustache | 1 + .../akka-scala/paramCreation.mustache | 1 + .../main/resources/akka-scala/pom.mustache | 227 +++++++++++ .../resources/akka-scala/reference.mustache | 24 ++ .../resources/akka-scala/requests.mustache | 166 ++++++++ .../akka-scala/responseState.mustache | 1 + .../src/test/resources/2_0/requiredTest.json | 93 +++++ .../src/test/scala/CodegenTest.scala | 38 +- 22 files changed, 1483 insertions(+), 23 deletions(-) create mode 100644 modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache create mode 100644 modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache create mode 100644 modules/swagger-codegen/src/test/resources/2_0/requiredTest.json diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 169886da22e..d1bfc90ba2a 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -11,6 +11,6 @@ public class CodegenModel { public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); - public Boolean hasVars, emptyVars, hasMoreModels; + public Boolean hasVars, emptyVars, hasMoreModels, hasEnums; public ExternalDocs externalDocs; } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java index 15931c9fd27..b23c5f72120 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java @@ -8,6 +8,7 @@ public class CodegenResponse { public List> examples; public final List headers = new ArrayList(); public String dataType, baseType, containerType; + public Boolean isDefault; public Boolean simpleType; public Boolean primitiveType; public Boolean isMapContainer; diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java index 889a9419c64..00d56ea213e 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenSecurity.java @@ -1,11 +1,10 @@ package com.wordnik.swagger.codegen; public class CodegenSecurity { - String name; - String type; - Boolean hasMore, isBasic, isOAuth, isApiKey; + public String name; + public String type; + public Boolean hasMore, isBasic, isOAuth, isApiKey; // ApiKey specific - String keyParamName; - Boolean isKeyInQuery, isKeyInHeader; - + public String keyParamName; + public Boolean isKeyInQuery, isKeyInHeader; } 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 0a6e955b955..0055c968edc 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 @@ -166,6 +166,9 @@ public class DefaultCodegen { return name; } + public String toEnumName(CodegenProperty property) { + return StringUtils.capitalize(property.name) + "Enum"; + } public String escapeReservedWord(String name) { throw new RuntimeException("reserved word " + name + " not allowed"); @@ -450,6 +453,7 @@ public class DefaultCodegen { } if(impl.getProperties() != null && impl.getProperties().size() > 0) { m.hasVars = true; + m.hasEnums = false; for(String key: impl.getProperties().keySet()) { Property prop = impl.getProperties().get(key); @@ -477,6 +481,8 @@ public class DefaultCodegen { } m.vars.add(cp); count += 1; + if (cp.isEnum) + m.hasEnums = true; if(count != impl.getProperties().keySet().size()) cp.hasMore = new Boolean(true); if(cp.isContainer != null) { @@ -569,7 +575,7 @@ public class DefaultCodegen { // this can cause issues for clients which don't support enums if(property.isEnum) - property.datatypeWithEnum = StringUtils.capitalize(property.name) + "Enum"; + property.datatypeWithEnum = toEnumName(property); else property.datatypeWithEnum = property.datatype; @@ -702,7 +708,6 @@ public class DefaultCodegen { if (operation.getResponses() != null && !operation.getResponses().isEmpty()) { Response methodResponse = findMethodResponse(operation.getResponses()); - CodegenResponse methodCodegenResponse = null; for (Map.Entry entry : operation.getResponses().entrySet()) { Response response = entry.getValue(); @@ -712,9 +717,7 @@ public class DefaultCodegen { !defaultIncludes.contains(r.baseType) && !languageSpecificPrimitives.contains(r.baseType)) imports.add(r.baseType); - - if (response == methodResponse) - methodCodegenResponse = r; + r.isDefault = response == methodResponse; op.responses.add(r); } op.responses.get(op.responses.size() - 1).hasMore = false; @@ -897,6 +900,19 @@ public class DefaultCodegen { collectionFormat = qp.getCollectionFormat(); CodegenProperty pr = fromProperty("inner", inner); p.baseType = pr.datatype; + p.isContainer = true; + imports.add(pr.baseType); + } + else if("object".equals(qp.getType())) { + Property inner = qp.getItems(); + if(inner == null) { + LOGGER.warn("warning! No inner type supplied for map parameter \"" + qp.getName() + "\", using String"); + inner = new StringProperty().description("//TODO automatically added by swagger-codegen"); + } + property = new MapProperty(inner); + collectionFormat = qp.getCollectionFormat(); + CodegenProperty pr = fromProperty("inner", inner); + p.baseType = pr.datatype; imports.add(pr.baseType); } else @@ -905,6 +921,7 @@ public class DefaultCodegen { LOGGER.warn("warning! Property type \"" + qp.getType() + "\" not found for parameter \"" + param.getName() + "\", using String"); property = new StringProperty().description("//TODO automatically added by swagger-codegen. Type was " + qp.getType() + " but not supported"); } + property.setRequired(param.getRequired()); CodegenProperty model = fromProperty(qp.getName(), property); p.collectionFormat = collectionFormat; p.dataType = model.datatype; @@ -928,6 +945,7 @@ public class DefaultCodegen { else { // TODO: missing format, so this will not always work Property prop = PropertyBuilder.build(impl.getType(), null, null); + prop.setRequired(bp.getRequired()); CodegenProperty cp = fromProperty("property", prop); if(cp != null) { p.dataType = cp.datatype; @@ -941,6 +959,7 @@ public class DefaultCodegen { CodegenModel cm = fromModel(bp.getName(), impl); // get the single property ArrayProperty ap = new ArrayProperty().items(impl.getItems()); + ap.setRequired(param.getRequired()); CodegenProperty cp = fromProperty("inner", ap); if(cp.complexType != null) { imports.add(cp.complexType); @@ -1148,4 +1167,4 @@ public class DefaultCodegen { } -} +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java new file mode 100644 index 00000000000..ee2da7aa921 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -0,0 +1,365 @@ +package com.wordnik.swagger.codegen.languages; + +import com.google.common.base.CaseFormat; +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import com.wordnik.swagger.codegen.*; +import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; +import com.wordnik.swagger.models.properties.*; +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.*; + +public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenConfig { + Logger LOGGER = LoggerFactory.getLogger(AkkaScalaClientCodegen.class); + + protected String mainPackage = "io.swagger.client"; + + protected String invokerPackage = mainPackage + ".core"; + protected String groupId = "com.wordnik"; + protected String artifactId = "swagger-client"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "src/main/scala"; + protected String resourcesFolder = "src/main/resources"; + protected String configKey = "apiRequest"; + protected int defaultTimeoutInMs = 5000; + protected String configKeyPath = mainPackage; + + protected boolean registerNonStandardStatusCodes = true; + protected boolean renderJavadoc = true; + protected boolean removeOAuthSecurities = true; + /** + * If set to true, only the default response (the one with le lowest 2XX code) will be considered as a success, and all + * others as ApiErrors. + * If set to false, all responses defined in the model will be considered as a success upon reception. Only http errors, + * unmarshalling problems and any other RuntimeException will be considered as ApiErrors. + */ + protected boolean onlyOneSuccess = true; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "akka-scala"; + } + + public String getHelp() { + return "Generates a Scala client library base on Akka/Spray."; + } + + public AkkaScalaClientCodegen() { + super(); + outputFolder = "generated-code/scala"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + templateDir = "akka-scala"; + apiPackage = mainPackage + ".api"; + modelPackage = mainPackage + ".model"; + + reservedWords = new HashSet( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + additionalProperties.put("invokerPackage", invokerPackage); + additionalProperties.put("groupId", groupId); + additionalProperties.put("artifactId", artifactId); + additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("configKey", configKey); + additionalProperties.put("configKeyPath", configKeyPath); + additionalProperties.put("defaultTimeout", defaultTimeoutInMs); + if (renderJavadoc) + additionalProperties.put("javadocRenderer", new JavadocLambda()); + additionalProperties.put("fnCapitalize", new CapitalizeLambda()); + additionalProperties.put("fnCamelize", new CamelizeLambda(false)); + additionalProperties.put("fnEnumEntry", new EnumEntryLambda()); + additionalProperties.put("onlyOneSuccess", onlyOneSuccess); + + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); + supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); + final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); + + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + + importMapping.put("DateTime", "org.joda.time.DateTime"); + + typeMapping = new HashMap(); + typeMapping.put("array", "Seq"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("long", "Long"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + typeMapping.put("number", "Double"); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "String", + "boolean", + "Boolean", + "Double", + "Int", + "Long", + "Float", + "Object", + "List", + "Seq", + "Map") + ); + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "Map"); + } + + @Override + public String escapeReservedWord(String name) { + return "`" + name + "`"; + } + + @Override + public String apiFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + apiPackage().replace('.', File.separatorChar); + } + + public String modelFileFolder() { + return outputFolder + "/" + sourceFolder + "/" + modelPackage().replace('.', File.separatorChar); + } + + @Override + public Map postProcessOperations(Map objs) { + if (registerNonStandardStatusCodes) { + try { + @SuppressWarnings("unchecked") + Map> opsMap = (Map>) objs.get("operations"); + HashSet unknownCodes = new HashSet(); + for (CodegenOperation operation : opsMap.get("operation")) { + for (CodegenResponse response : operation.responses) { + if ("default".equals(response.code)) + continue; + try { + int code = Integer.parseInt(response.code); + if (code >= 600) { + unknownCodes.add(code); + } + } catch (NumberFormatException e) { + LOGGER.error("Status code is not an integer : response.code", e); + } + } + } + if (!unknownCodes.isEmpty()) { + additionalProperties.put("unknownStatusCodes", unknownCodes); + } + } catch (Exception e) { + LOGGER.error("Unable to find operations List", e); + } + } + return super.postProcessOperations(objs); + } + + @Override + public String getTypeDeclaration(Property p) { + if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getSwaggerType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + + return getSwaggerType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public List fromSecurity(Map schemes) { + final List codegenSecurities = super.fromSecurity(schemes); + if (!removeOAuthSecurities) + return codegenSecurities; + + // Remove OAuth securities + Iterator it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + if (security.isOAuth) + it.remove(); + } + // Adapt 'hasMore' + it = codegenSecurities.iterator(); + while (it.hasNext()) { + final CodegenSecurity security = it.next(); + security.hasMore = it.hasNext(); + } + + if (codegenSecurities.isEmpty()) + return null; + return codegenSecurities; + } + + @Override + public String toOperationId(String operationId) { + return super.toOperationId(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, operationId)); + } + + private String formatIdentifier(String name, boolean capitalized) { + String identifier = camelize(name); + if (capitalized) + identifier = StringUtils.capitalize(identifier); + if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) + return identifier; + return escapeReservedWord(identifier); + } + + @Override + public String toParamName(String name) { return formatIdentifier(name, false); } + + @Override + public String toVarName(String name) { + return formatIdentifier(name, false); + } + + @Override + public String toEnumName(CodegenProperty property) + { + return formatIdentifier(property.baseName, true); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return toModelName(type); + } else + type = swaggerType; + return toModelName(type); + } + + @Override + public String toInstantiationType(Property p) { + if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return instantiationTypes.get("map") + "[String, " + inner + "]"; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return instantiationTypes.get("array") + "[" + inner + "]"; + } else + return null; + } + + public String toDefaultValue(Property p) { + if (!p.getRequired()) + return "None"; + if (p instanceof StringProperty) + return "null"; + else if (p instanceof BooleanProperty) + return "null"; + else if (p instanceof DateProperty) + return "null"; + else if (p instanceof DateTimeProperty) + return "null"; + else if (p instanceof DoubleProperty) + return "null"; + else if (p instanceof FloatProperty) + return "null"; + else if (p instanceof IntegerProperty) + return "null"; + else if (p instanceof LongProperty) + return "null"; + else if (p instanceof MapProperty) { + MapProperty ap = (MapProperty) p; + String inner = getSwaggerType(ap.getAdditionalProperties()); + return "Map[String, " + inner + "].empty "; + } else if (p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + String inner = getSwaggerType(ap.getItems()); + return "Seq[" + inner + "].empty "; + } else + return "null"; + } + + private static abstract class CustomLambda implements Mustache.Lambda { + @Override + public void execute(Template.Fragment frag, Writer out) throws IOException { + final StringWriter tempWriter = new StringWriter(); + frag.execute(tempWriter); + out.write(formatFragment(tempWriter.toString())); + } + public abstract String formatFragment(String fragment); + } + + + private static class JavadocLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + final String[] lines = fragment.split("\\r?\\n"); + final StringBuilder sb = new StringBuilder(); + sb.append(" /**\n"); + for (String line : lines) { + sb.append(" * ").append(line).append("\n"); + } + sb.append(" */\n"); + return sb.toString(); + } + } + + private static class CapitalizeLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return StringUtils.capitalize(fragment); + } + } + + private static class CamelizeLambda extends CustomLambda { + private final boolean capitalizeFirst; + + public CamelizeLambda(boolean capitalizeFirst) { + this.capitalizeFirst = capitalizeFirst; + } + + @Override + public String formatFragment(String fragment) { + return camelize(fragment, !capitalizeFirst); + } + } + + private class EnumEntryLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return formatIdentifier(fragment, true); + } + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig index 6535948ad88..3bd4df773cd 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/com.wordnik.swagger.codegen.CodegenConfig @@ -15,4 +15,5 @@ com.wordnik.swagger.codegen.languages.StaticDocCodegen com.wordnik.swagger.codegen.languages.StaticHtmlGenerator com.wordnik.swagger.codegen.languages.SwaggerGenerator com.wordnik.swagger.codegen.languages.SwaggerYamlGenerator -com.wordnik.swagger.codegen.languages.TizenClientCodegen \ No newline at end of file +com.wordnik.swagger.codegen.languages.TizenClientCodegen +com.wordnik.swagger.codegen.languages.AkkaScalaClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache new file mode 100644 index 00000000000..34523b80353 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache @@ -0,0 +1,43 @@ +package {{package}} + +{{#imports}} +import {{import}} +{{/imports}} +import {{invokerPackage}}._ +import {{invokerPackage}}.CollectionFormats._ +import {{invokerPackage}}.ApiKeyLocations._ + +{{#operations}} +object {{classname}} { + +{{#operation}} +{{#javadocRenderer}} +{{>javadoc}} +{{/javadocRenderer}} + def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] = + ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, "{{basePath}}", "{{path}}", {{#consumes.0}}"{{mediaType}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}) + {{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}}) + {{/isApiKey}}{{#isBasic}}.withCredentials(basicAuth) + {{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) + {{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}}) + {{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}}) + {{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}}) + {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) + {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) + {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) + {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}]() + {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit]() + {{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}} + object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}} + def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}} + } + {{/responseHeaders.isEmpty}} +{{/operation}} + +{{#unknownStatusCodes}} + ApiInvoker.addCustomStatusCode({{value}}, isSuccess = false) +{{/unknownStatusCodes}} + +} + +{{/operations}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache new file mode 100644 index 00000000000..0dde3673439 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiInvoker.mustache @@ -0,0 +1,323 @@ +package {{invokerPackage}} + +import java.io.File +import java.security.cert.X509Certificate +import javax.net.ssl._ + +import akka.actor.ActorSystem +import akka.io.IO +import akka.pattern.ask +import akka.util.Timeout +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.JsonAST.JString +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization +import spray.can.Http +import spray.can.Http.HostConnectorSetup +import spray.client.pipelining +import spray.client.pipelining._ +import spray.http.HttpEncodings._ +import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`} +import spray.http.Uri.Query +import spray.http._ +import spray.http.parser.HttpParser +import spray.httpx.encoding.{Deflate, Encoder, Gzip} +import spray.httpx.unmarshalling._ +import spray.io.ClientSSLEngineProvider + +import scala.concurrent.{ExecutionContext, Future} +import scala.reflect.ClassTag +import scala.util.control.NonFatal + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer) + def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer ++ serializers) + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) + + def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) + + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { + StatusCodes.getForKey(code) foreach { c => + StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) + } + } + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will failed with a ClassCastException + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + + case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { + case JString(s) => + ISODateTimeFormat.dateTimeParser().parseDateTime(s) + }, { + case d: DateTime => + JString(ISODateTimeFormat.dateTimeParser().print(d)) + })) +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { + + import io.swagger.client.core.ApiInvoker._ + import io.swagger.client.core.ParametersMap._ + + implicit val ec = system.dispatcher + implicit val jsonFormats = formats + + def settings = ApiSettings(system) + + import spray.http.MessagePredicate._ + + val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && + minEntitySize(settings.compressionSizeThreshold) + + settings.customCodes.foreach(addCustomStatusCode) + + private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = + request => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req ~> addCredentials(BasicHttpCredentials(login, password)) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req ~> addHeader(RawHeader(keyName, keyValue.value)) + case (req, _) => req + } + + private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => + + val rawHeaders = for { + (name, value) <- headers.asFormattedParams + header = RawHeader(name, String.valueOf(value)) + } yield header + + request.withHeaders(rawHeaders.toList) + } + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart(f, name) + case v: String => + BodyPart(HttpEntity(String.valueOf(v))) + case NumericValue(v) => + BodyPart(HttpEntity(String.valueOf(v))) + case m: ApiModel => + BodyPart(HttpEntity(Serialization.write(m))) + } + } + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.mapValues(String.valueOf)) + case m: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.mapValues(String.valueOf)) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = { + request.bodyParam.map(Extraction.decompose).map(compact) + } + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + + val builder = new RequestBuilder(request.method.toSprayMethod) + val httpRequest = request.method.toSprayMethod match { + case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) + case HttpMethods.POST | HttpMethods.PUT => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + builder.apply(uri, c) + case Some(c: MultipartFormData) => + builder.apply(uri, c) + case Some(c: String) => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) + case _ => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) + } + case _ => builder.apply(uri) + } + + httpRequest ~> + addHeaders(request.headerParams) ~> + addAuthentication(request.credentials) ~> + encode(Gzip(CompressionFilter)) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .mapValues(String.valueOf) + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .mapValues(String.valueOf) + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { + try { + implicit val timeout: Timeout = settings.connectionTimeout + + val uri = makeUri(r) + + val connector = HostConnectorSetup( + uri.authority.host.toString, + uri.effectivePort, + sslEncryption = "https".equals(uri.scheme), + defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) + + val request = createRequest(uri, r) + + for { + Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector + response <- hostConnector.ask(request).mapTo[HttpResponse] + } yield { + response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) + } + } + catch { + case NonFatal(x) => Future.failed(x) + } + } + + def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { + request.responseForCode(response.status.intValue) match { + case Some( (manifest: Manifest[T], state: ResponseState) ) => + entityUnmarshaller(manifest)(response.entity) match { + case Right(value) ⇒ + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw new ApiError(response.status.intValue, "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap) + } + + case Left(MalformedContent(error, Some(cause))) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + + case Left(MalformedContent(error, None)) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + + case Left(ContentExpected) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + } + + case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + } + } + + def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = + Unmarshaller[T](MediaTypes.`application/json`) { + case x: HttpEntity.NonEmpty ⇒ + parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) + .noNulls + .camelizeKeys + .extract[T] + } + +} + +sealed trait CustomContentTypes { + + def normalizedContentType(original: String): ContentType = + MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) + + def parseContentType(contentType: String): ContentType = { + val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) + val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) + (parsedContentTypeHeader: @unchecked) match { + case Right(ct: HttpHeaders.`Content-Type`) => + ct.contentType + case Left(error: ErrorInfo) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.summary}'") + } + } +} + +sealed trait UntrustedSslContext { + this: ApiInvoker => + + implicit lazy val trustfulSslContext: SSLContext = { + settings.alwaysTrustCertificates match { + case false => + SSLContext.getDefault + + case true => + class IgnoreX509TrustManager extends X509TrustManager { + def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def getAcceptedIssuers = null + } + + val context = SSLContext.getInstance("TLS") + context.init(null, Array(new IgnoreX509TrustManager), null) + context + } + } + + implicit val clientSSLEngineProvider = + ClientSSLEngineProvider { + _ => + val engine = trustfulSslContext.createSSLEngine() + engine.setUseClientMode(true) + engine + } +} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache new file mode 100644 index 00000000000..3016768f7ac --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiRequest.mustache @@ -0,0 +1,50 @@ +package {{invokerPackage}} + +sealed trait ResponseState +object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody() = copy[U](bodyParam = None) + + def withBody(body: Any) = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache new file mode 100644 index 00000000000..d3ffe3613ae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/apiSettings.mustache @@ -0,0 +1,32 @@ +package {{invokerPackage}} + +import java.util.concurrent.TimeUnit + +import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey} +import com.typesafe.config.Config +import io.swagger.client.core.ApiInvoker.CustomStatusCode +import spray.http.HttpHeaders.RawHeader + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("io.swagger.client.apiRequest") + + val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") + val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt + val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) + } + + +} + +object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache new file mode 100644 index 00000000000..52f1fd3e330 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/enumsSerializers.mustache @@ -0,0 +1,42 @@ +package {{apiPackage}} + +import {{modelPackage}}._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ + new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}} + + + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache new file mode 100644 index 00000000000..0d22fd62374 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/javadoc.mustache @@ -0,0 +1,21 @@ +{{^notes.isEmpty}} +{{notes}} +{{/notes.isEmpty}} + +Expected answers: +{{#responses}} + code {{code}} : {{dataType}} {{^message.isEmpty}}({{message}}){{/message.isEmpty}}{{^headers.isEmpty}} + Headers :{{#headers}} + {{baseName}} - {{description}}{{/headers}}{{/headers.isEmpty}} +{{/responses}} +{{#authMethods.0}} + +Available security schemes: +{{#authMethods}} + {{name}} ({{type}}) +{{/authMethods}} +{{/authMethods.0}} + +{{#allParams}} +@param {{paramName}} {{description}} +{{/allParams}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache new file mode 100644 index 00000000000..3e1ab33f665 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/methodParameters.mustache @@ -0,0 +1 @@ +{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{#defaultValue}} = {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{#hasMore}}, {{/hasMore}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}basicAuth: BasicCredentials{{/isBasic}}{{#hasMore}}, {{/hasMore}}{{/authMethods}}{{/authMethods.0}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache new file mode 100644 index 00000000000..a7395b5f03a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/model.mustache @@ -0,0 +1,30 @@ +package {{package}} + +import {{invokerPackage}}.ApiModel +import org.joda.time.DateTime + +{{#models}} +{{#model}} + +case class {{classname}} ( + {{#vars}}{{#description}}/* {{{description}}} */ + {{/description}}{{name}}: {{^required}}Option[{{/required}}{{^isEnum}}{{datatype}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}]{{/required}}{{#hasMore}},{{/hasMore}}{{^hasMore}}){{/hasMore}} + {{/vars}} extends ApiModel + +{{#hasEnums}} +object {{classname}}Enums { + + {{#vars}}{{#isEnum}}type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}}{{/vars}} + {{#vars}}{{#isEnum}}object {{datatypeWithEnum}} extends Enumeration { +{{#_enum}} + val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") +{{/_enum}} + } + + {{/isEnum}}{{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} + diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache new file mode 100644 index 00000000000..e9d2be53401 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache @@ -0,0 +1 @@ +{{#onlyOneSuccess}}{{^defaultResponse}}Unit{{/defaultResponse}}{{#responses}}{{#isDefault}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/isDefault}}{{/responses}}{{/onlyOneSuccess}}{{^onlyOneSuccess}}{{#responses}}{{#-first}}{{^hasMore}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/hasMore}}{{#hasMore}}Any{{/hasMore}}{{/-first}}{{/responses}}{{/onlyOneSuccess}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache new file mode 100644 index 00000000000..f93d3765038 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/paramCreation.mustache @@ -0,0 +1 @@ +"{{baseName}}", {{#isContainer}}ArrayValues({{paramName}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{paramName}}{{/isContainer}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache new file mode 100644 index 00000000000..0d65c135957 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/pom.mustache @@ -0,0 +1,227 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + org.scala-lang + scala-library + ${scala-version} + + + com.wordnik + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.10 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.10 + ${json4s-jackson-version} + + + + 2.10.4 + 3.2.11 + 3.2.11 + 1.3.1 + 2.3.9 + 1.2 + 2.2 + 1.5.0-M1 + 1.0.0 + + 4.8.1 + 3.1.5 + 2.1.3 + + diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache new file mode 100644 index 00000000000..1a28a8962ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/reference.mustache @@ -0,0 +1,24 @@ +{{configKeyPath}} { + + {{configKey}} { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: {{defaultTimeout}}ms + + default-headers { + "userAgent": "{{artifactId}}_{{artifactVersion}}" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache new file mode 100644 index 00000000000..145354203fb --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/requests.mustache @@ -0,0 +1,166 @@ +package {{invokerPackage}} + +import java.io.File +import java.net.URLEncoder +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) + def getStringHeader(name: String) = header(name) + def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) + def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) + def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) + def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) + def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList = m.toList.flatMap(formattedParams) + + def asFormattedParams = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => + formattedParams(name, opt) + case s: Seq[Any] => + formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + + } +} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache new file mode 100644 index 00000000000..c6d44b86d87 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/akka-scala/responseState.mustache @@ -0,0 +1 @@ +{{#onlyOneSuccess}}{{#isDefault}}Success{{/isDefault}}{{^isDefault}}Error{{/isDefault}}{{/onlyOneSuccess}}{{^onlyOneSuccess}}Success{{/onlyOneSuccess}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json new file mode 100644 index 00000000000..88106746d29 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/requiredTest.json @@ -0,0 +1,93 @@ +{ + "swagger": "2.0", + "info": { + "description": "This is a sample server Petstore server. You can find out more about Swagger at http://swagger.io or on irc.freenode.net, #swagger. For this sample, you can use the api key \"special-key\" to test the authorization filters", + "version": "1.0.0", + "title": "Swagger Petstore", + "termsOfService": "http://helloreverb.com/terms/", + "contact": { + "email": "apiteam@wordnik.com" + }, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" + } + }, + "host": "petstore.swagger.io", + "basePath": "/v2", + "schemes": [ + "http" + ], + "paths": { + "/tests/requiredParams": { + "get": { + "tags": [ + "tests" + ], + "summary": "Operation with required parameters", + "description": "", + "operationId": "requiredParams", + "produces": [ + "application/json" + ], + "parameters": [ + { + "name": "param1", + "in": "formData", + "description": "Some required parameter", + "required": true, + "type": "integer", + "format": "int64" + }, + { + "name": "param2", + "in": "formData", + "description": "Some optional parameter", + "required": false, + "type": "string" + } + ], + "responses": { + "200": { + "description": "successful operation. Retuning a simple int.", + "schema": { + "type": "integer", + "format": "int64" + } + } + } + } + } + }, + "securityDefinitions": { + "api_key": { + "type": "apiKey", + "name": "api_key", + "in": "header" + }, + "petstore_auth": { + "type": "oauth2", + "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", + "flow": "implicit", + "scopes": { + "write:pets": "modify pets in your account", + "read:pets": "read your pets" + } + } + }, + "definitions": { + "CustomModel": { + "required": ["id"], + "properties": { + "id": { + "type": "integer", + "format": "int64" + }, + "name": { + "type": "string", + "example": "doggie" + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/CodegenTest.scala b/modules/swagger-codegen/src/test/scala/CodegenTest.scala index 9e2a1d9fa9e..5ce35825159 100644 --- a/modules/swagger-codegen/src/test/scala/CodegenTest.scala +++ b/modules/swagger-codegen/src/test/scala/CodegenTest.scala @@ -1,15 +1,9 @@ -import com.wordnik.swagger.models._ -import com.wordnik.swagger.util.Json -import io.swagger.parser._ - import com.wordnik.swagger.codegen.DefaultCodegen - +import com.wordnik.swagger.models.properties.Property +import io.swagger.parser._ import org.junit.runner.RunWith import org.scalatest.junit.JUnitRunner -import org.scalatest.FlatSpec -import org.scalatest.Matchers - -import scala.collection.JavaConverters._ +import org.scalatest.{FlatSpec, Matchers} @RunWith(classOf[JUnitRunner]) class CodegenTest extends FlatSpec with Matchers { @@ -95,6 +89,32 @@ class CodegenTest extends FlatSpec with Matchers { statusParam.hasMore should be (null) } + it should "handle required parameters from a 2.0 spec as required when figuring out Swagger types" in { + val model = new SwaggerParser() + .read("src/test/resources/2_0/requiredTest.json") + + val codegen = new DefaultCodegen() { + override def getSwaggerType(p: Property) = Option(p) match { + case Some(property) if !property.getRequired => + "Optional<" + super.getSwaggerType(p) + ">" + case other => super.getSwaggerType(p) + } + } + val path = "/tests/requiredParams" + val p = model.getPaths().get(path).getGet() + val op = codegen.fromOperation(path, "get", p, model.getDefinitions) + + val formParams = op.formParams + formParams.size should be(2) + val requiredParam = formParams.get(0) + requiredParam.dataType should be("Long") + + val optionalParam = formParams.get(1) + optionalParam.dataType should be("Optional") + + op.returnType should be("Long") + } + it should "select main response from a 2.0 spec using the lowest 2XX code" in { val model = new SwaggerParser() .read("src/test/resources/2_0/responseSelectionTest.json") From 2ce55115a631d74b32e7fbb76168baebebd3a9d3 Mon Sep 17 00:00:00 2001 From: Camille Chafer Date: Thu, 2 Apr 2015 16:26:16 +0200 Subject: [PATCH 04/75] Add wordnik and petstore examples --- samples/client/petstore/akka-scala/pom.xml | 227 ++++++++++++ .../src/main/resources/reference.conf | 24 ++ .../swagger/client/api/EnumsSerializers.scala | 43 +++ .../scala/io/swagger/client/api/PetApi.scala | 139 ++++++++ .../io/swagger/client/api/StoreApi.scala | 73 ++++ .../scala/io/swagger/client/api/UserApi.scala | 123 +++++++ .../io/swagger/client/core/ApiInvoker.scala | 323 ++++++++++++++++++ .../io/swagger/client/core/ApiRequest.scala | 50 +++ .../io/swagger/client/core/ApiSettings.scala | 32 ++ .../io/swagger/client/core/requests.scala | 166 +++++++++ .../io/swagger/client/model/Category.scala | 12 + .../scala/io/swagger/client/model/Order.scala | 29 ++ .../scala/io/swagger/client/model/Pet.scala | 29 ++ .../scala/io/swagger/client/model/Tag.scala | 12 + .../scala/io/swagger/client/model/User.scala | 19 ++ samples/client/wordnik/akka-scala/pom.xml | 227 ++++++++++++ .../src/main/resources/reference.conf | 24 ++ .../io/swagger/client/api/AccountApi.scala | 109 ++++++ .../swagger/client/api/EnumsSerializers.scala | 41 +++ .../scala/io/swagger/client/api/WordApi.scala | 253 ++++++++++++++ .../io/swagger/client/api/WordListApi.scala | 154 +++++++++ .../io/swagger/client/api/WordListsApi.scala | 34 ++ .../io/swagger/client/api/WordsApi.scala | 181 ++++++++++ .../io/swagger/client/core/ApiInvoker.scala | 323 ++++++++++++++++++ .../io/swagger/client/core/ApiRequest.scala | 50 +++ .../io/swagger/client/core/ApiSettings.scala | 32 ++ .../io/swagger/client/core/requests.scala | 166 +++++++++ .../swagger/client/model/ApiTokenStatus.scala | 16 + .../io/swagger/client/model/AudioFile.scala | 24 ++ .../io/swagger/client/model/AudioType.scala | 12 + .../client/model/AuthenticationToken.scala | 13 + .../io/swagger/client/model/Bigram.scala | 15 + .../io/swagger/client/model/Category.scala | 12 + .../io/swagger/client/model/Citation.scala | 12 + .../client/model/ContentProvider.scala | 12 + .../io/swagger/client/model/Definition.scala | 26 ++ .../model/DefinitionSearchResults.scala | 12 + .../io/swagger/client/model/Example.scala | 22 ++ .../client/model/ExampleSearchResults.scala | 12 + .../swagger/client/model/ExampleUsage.scala | 11 + .../scala/io/swagger/client/model/Facet.scala | 12 + .../io/swagger/client/model/FacetValue.scala | 12 + .../io/swagger/client/model/Frequency.scala | 12 + .../client/model/FrequencySummary.scala | 15 + .../scala/io/swagger/client/model/Label.scala | 12 + .../scala/io/swagger/client/model/Note.scala | 14 + .../swagger/client/model/PartOfSpeech.scala | 13 + .../io/swagger/client/model/Related.scala | 17 + .../scala/io/swagger/client/model/Root.scala | 13 + .../io/swagger/client/model/ScoredWord.scala | 21 ++ .../io/swagger/client/model/Sentence.scala | 16 + .../client/model/SimpleDefinition.scala | 14 + .../swagger/client/model/SimpleExample.scala | 14 + .../io/swagger/client/model/StringValue.scala | 11 + .../io/swagger/client/model/Syllable.scala | 13 + .../io/swagger/client/model/TextPron.scala | 13 + .../scala/io/swagger/client/model/User.scala | 18 + .../io/swagger/client/model/WordList.scala | 21 ++ .../swagger/client/model/WordListWord.scala | 17 + .../io/swagger/client/model/WordObject.scala | 16 + .../swagger/client/model/WordOfTheDay.scala | 22 ++ .../client/model/WordSearchResult.scala | 13 + .../client/model/WordSearchResults.scala | 12 + 63 files changed, 3435 insertions(+) create mode 100644 samples/client/petstore/akka-scala/pom.xml create mode 100644 samples/client/petstore/akka-scala/src/main/resources/reference.conf create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala create mode 100644 samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala create mode 100644 samples/client/wordnik/akka-scala/pom.xml create mode 100644 samples/client/wordnik/akka-scala/src/main/resources/reference.conf create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala create mode 100644 samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala diff --git a/samples/client/petstore/akka-scala/pom.xml b/samples/client/petstore/akka-scala/pom.xml new file mode 100644 index 00000000000..f865a97c38b --- /dev/null +++ b/samples/client/petstore/akka-scala/pom.xml @@ -0,0 +1,227 @@ + + 4.0.0 + com.wordnik + swagger-client + jar + swagger-client + 1.0.0 + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + org.scala-lang + scala-library + ${scala-version} + + + com.wordnik + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.10 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.10 + ${json4s-jackson-version} + + + + 2.10.4 + 3.2.11 + 3.2.11 + 1.3.1 + 2.3.9 + 1.2 + 2.2 + 1.5.0-M1 + 1.0.0 + + 4.8.1 + 3.1.5 + 2.1.3 + + diff --git a/samples/client/petstore/akka-scala/src/main/resources/reference.conf b/samples/client/petstore/akka-scala/src/main/resources/reference.conf new file mode 100644 index 00000000000..f993f765edd --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/resources/reference.conf @@ -0,0 +1,24 @@ +io.swagger.client { + + apiRequest { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: 5000ms + + default-headers { + "userAgent": "swagger-client_1.0.0" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala new file mode 100644 index 00000000000..c8c0d2454e4 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala @@ -0,0 +1,43 @@ +package io.swagger.client.api + +import io.swagger.client.model._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all = Seq[Serializer[_]]() :+ + new EnumNameSerializer(PetEnums.Status) :+ + new EnumNameSerializer(OrderEnums.Status) + + + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} \ No newline at end of file diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala new file mode 100644 index 00000000000..d56d3f855a3 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -0,0 +1,139 @@ +package io.swagger.client.api + +import io.swagger.client.model.Pet +import java.io.File +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object PetApi { + + /** + * + * Expected answers: + * code 405 : (Validation exception) + * code 404 : (Pet not found) + * code 400 : (Invalid ID supplied) + * + * @param Body Pet object that needs to be added to the store + */ + def updatePet(Body: Option[Pet] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/pet", "application/json") + .withBody(Body) + .withErrorResponse[Unit](405) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 405 : (Invalid input) + * + * @param Body Pet object that needs to be added to the store + */ + def addPet(Body: Option[Pet] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet", "application/json") + .withBody(Body) + .withErrorResponse[Unit](405) + + /** + * Multiple status values can be provided with comma seperated strings + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid status value) + * + * @param Status Status values that need to be considered for filter + */ + def findPetsByStatus(Status: Seq[String]): ApiRequest[Seq[Pet]] = + ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByStatus", "application/json") + .withQueryParam("status", ArrayValues(Status, MULTI)) + .withSuccessResponse[Seq[Pet]](200) + .withErrorResponse[Unit](400) + + /** + * Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid tag value) + * + * @param Tags Tags to filter by + */ + def findPetsByTags(Tags: Seq[String]): ApiRequest[Seq[Pet]] = + ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByTags", "application/json") + .withQueryParam("tags", ArrayValues(Tags, MULTI)) + .withSuccessResponse[Seq[Pet]](200) + .withErrorResponse[Unit](400) + + /** + * Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + * + * Expected answers: + * code 404 : (Pet not found) + * code 200 : Pet (successful operation) + * code 400 : (Invalid ID supplied) + * + * Available security schemes: + * api_key (apiKey) + * + * @param PetId ID of pet that needs to be fetched + */ + def getPetById(PetId: Long)(implicit apiKey: ApiKeyValue): ApiRequest[Pet] = + ApiRequest[Pet](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") + .withApiKey(apiKey, "api_key", HEADER) + .withPathParam("petId", PetId) + .withErrorResponse[Unit](404) + .withSuccessResponse[Pet](200) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 405 : (Invalid input) + * + * @param PetId ID of pet that needs to be updated + * @param Name Updated name of the pet + * @param Status Updated status of the pet + */ + def updatePetWithForm(PetId: String, Name: Option[String] = None, Status: Option[String] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/x-www-form-urlencoded") + .withFormParam("name", Name) + .withFormParam("status", Status) + .withPathParam("petId", PetId) + .withErrorResponse[Unit](405) + + /** + * + * Expected answers: + * code 400 : (Invalid pet value) + * + * @param ApiKey + * @param PetId Pet id to delete + */ + def deletePet(ApiKey: Option[String] = None, PetId: Long): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") + .withPathParam("petId", PetId) + .withHeaderParam("api_key", ApiKey) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 0 : (successful operation) + * + * @param PetId ID of pet to update + * @param AdditionalMetadata Additional data to pass to server + * @param File file to upload + */ + def uploadFile(PetId: Long, AdditionalMetadata: Option[String] = None, File: Option[File] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}/uploadImage", "multipart/form-data") + .withFormParam("additionalMetadata", AdditionalMetadata) + .withFormParam("file", File) + .withPathParam("petId", PetId) + .withSuccessResponse[Unit](0) + + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala new file mode 100644 index 00000000000..a1391954a7d --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -0,0 +1,73 @@ +package io.swagger.client.api + +import io.swagger.client.model.Order +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object StoreApi { + + /** + * Returns a map of status codes to quantities + * + * Expected answers: + * code 200 : Map[String, Int] (successful operation) + * + * Available security schemes: + * api_key (apiKey) + */ + def getInventory()(implicit apiKey: ApiKeyValue): ApiRequest[Map[String, Int]] = + ApiRequest[Map[String, Int]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/inventory", "application/json") + .withApiKey(apiKey, "api_key", HEADER) + .withSuccessResponse[Map[String, Int]](200) + + /** + * + * Expected answers: + * code 200 : Order (successful operation) + * code 400 : (Invalid Order) + * + * @param Body order placed for purchasing the pet + */ + def placeOrder(Body: Option[Order] = None): ApiRequest[Order] = + ApiRequest[Order](ApiMethods.POST, "http://petstore.swagger.io/v2", "/store/order", "application/json") + .withBody(Body) + .withSuccessResponse[Order](200) + .withErrorResponse[Unit](400) + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + * + * Expected answers: + * code 404 : (Order not found) + * code 200 : Order (successful operation) + * code 400 : (Invalid ID supplied) + * + * @param OrderId ID of pet that needs to be fetched + */ + def getOrderById(OrderId: String): ApiRequest[Order] = + ApiRequest[Order](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") + .withPathParam("orderId", OrderId) + .withErrorResponse[Unit](404) + .withSuccessResponse[Order](200) + .withErrorResponse[Unit](400) + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * Expected answers: + * code 404 : (Order not found) + * code 400 : (Invalid ID supplied) + * + * @param OrderId ID of the order that needs to be deleted + */ + def deleteOrder(OrderId: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") + .withPathParam("orderId", OrderId) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala new file mode 100644 index 00000000000..77aade9a9e8 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -0,0 +1,123 @@ +package io.swagger.client.api + +import io.swagger.client.model.User +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object UserApi { + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 0 : (successful operation) + * + * @param Body Created user object + */ + def createUser(Body: Option[User] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user", "application/json") + .withBody(Body) + .withSuccessResponse[Unit](0) + + /** + * + * Expected answers: + * code 0 : (successful operation) + * + * @param Body List of user object + */ + def createUsersWithArrayInput(Body: Seq[User]): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithArray", "application/json") + .withBody(Body) + .withSuccessResponse[Unit](0) + + /** + * + * Expected answers: + * code 0 : (successful operation) + * + * @param Body List of user object + */ + def createUsersWithListInput(Body: Seq[User]): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithList", "application/json") + .withBody(Body) + .withSuccessResponse[Unit](0) + + /** + * + * Expected answers: + * code 200 : String (successful operation) + * code 400 : (Invalid username/password supplied) + * + * @param Username The user name for login + * @param Password The password for login in clear text + */ + def loginUser(Username: Option[String] = None, Password: Option[String] = None): ApiRequest[String] = + ApiRequest[String](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/login", "application/json") + .withQueryParam("username", Username) + .withQueryParam("password", Password) + .withSuccessResponse[String](200) + .withErrorResponse[Unit](400) + + /** + * + * Expected answers: + * code 0 : (successful operation) + */ + def logoutUser(): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/logout", "application/json") + .withSuccessResponse[Unit](0) + + /** + * + * Expected answers: + * code 404 : (User not found) + * code 200 : User (successful operation) + * code 400 : (Invalid username supplied) + * + * @param Username The name that needs to be fetched. Use user1 for testing. + */ + def getUserByName(Username: String): ApiRequest[User] = + ApiRequest[User](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") + .withPathParam("username", Username) + .withErrorResponse[Unit](404) + .withSuccessResponse[User](200) + .withErrorResponse[Unit](400) + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 404 : (User not found) + * code 400 : (Invalid user supplied) + * + * @param Username name that need to be deleted + * @param Body Updated user object + */ + def updateUser(Username: String, Body: Option[User] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") + .withBody(Body) + .withPathParam("username", Username) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 404 : (User not found) + * code 400 : (Invalid username supplied) + * + * @param Username The name that needs to be deleted + */ + def deleteUser(Username: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") + .withPathParam("username", Username) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](400) + + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala new file mode 100644 index 00000000000..3b11d866017 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala @@ -0,0 +1,323 @@ +package io.swagger.client.core + +import java.io.File +import java.security.cert.X509Certificate +import javax.net.ssl._ + +import akka.actor.ActorSystem +import akka.io.IO +import akka.pattern.ask +import akka.util.Timeout +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.JsonAST.JString +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization +import spray.can.Http +import spray.can.Http.HostConnectorSetup +import spray.client.pipelining +import spray.client.pipelining._ +import spray.http.HttpEncodings._ +import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`} +import spray.http.Uri.Query +import spray.http._ +import spray.http.parser.HttpParser +import spray.httpx.encoding.{Deflate, Encoder, Gzip} +import spray.httpx.unmarshalling._ +import spray.io.ClientSSLEngineProvider + +import scala.concurrent.{ExecutionContext, Future} +import scala.reflect.ClassTag +import scala.util.control.NonFatal + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer) + def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer ++ serializers) + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) + + def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) + + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { + StatusCodes.getForKey(code) foreach { c => + StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) + } + } + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will failed with a ClassCastException + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + + case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { + case JString(s) => + ISODateTimeFormat.dateTimeParser().parseDateTime(s) + }, { + case d: DateTime => + JString(ISODateTimeFormat.dateTimeParser().print(d)) + })) +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { + + import io.swagger.client.core.ApiInvoker._ + import io.swagger.client.core.ParametersMap._ + + implicit val ec = system.dispatcher + implicit val jsonFormats = formats + + def settings = ApiSettings(system) + + import spray.http.MessagePredicate._ + + val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && + minEntitySize(settings.compressionSizeThreshold) + + settings.customCodes.foreach(addCustomStatusCode) + + private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = + request => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req ~> addCredentials(BasicHttpCredentials(login, password)) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req ~> addHeader(RawHeader(keyName, keyValue.value)) + case (req, _) => req + } + + private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => + + val rawHeaders = for { + (name, value) <- headers.asFormattedParams + header = RawHeader(name, String.valueOf(value)) + } yield header + + request.withHeaders(rawHeaders.toList) + } + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart(f, name) + case v: String => + BodyPart(HttpEntity(String.valueOf(v))) + case NumericValue(v) => + BodyPart(HttpEntity(String.valueOf(v))) + case m: ApiModel => + BodyPart(HttpEntity(Serialization.write(m))) + } + } + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.mapValues(String.valueOf)) + case m: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.mapValues(String.valueOf)) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = { + request.bodyParam.map(Extraction.decompose).map(compact) + } + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + + val builder = new RequestBuilder(request.method.toSprayMethod) + val httpRequest = request.method.toSprayMethod match { + case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) + case HttpMethods.POST | HttpMethods.PUT => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + builder.apply(uri, c) + case Some(c: MultipartFormData) => + builder.apply(uri, c) + case Some(c: String) => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) + case _ => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) + } + case _ => builder.apply(uri) + } + + httpRequest ~> + addHeaders(request.headerParams) ~> + addAuthentication(request.credentials) ~> + encode(Gzip(CompressionFilter)) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .mapValues(String.valueOf) + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .mapValues(String.valueOf) + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { + try { + implicit val timeout: Timeout = settings.connectionTimeout + + val uri = makeUri(r) + + val connector = HostConnectorSetup( + uri.authority.host.toString, + uri.effectivePort, + sslEncryption = "https".equals(uri.scheme), + defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) + + val request = createRequest(uri, r) + + for { + Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector + response <- hostConnector.ask(request).mapTo[HttpResponse] + } yield { + response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) + } + } + catch { + case NonFatal(x) => Future.failed(x) + } + } + + def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { + request.responseForCode(response.status.intValue) match { + case Some( (manifest: Manifest[T], state: ResponseState) ) => + entityUnmarshaller(manifest)(response.entity) match { + case Right(value) ⇒ + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw new ApiError(response.status.intValue, "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap) + } + + case Left(MalformedContent(error, Some(cause))) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + + case Left(MalformedContent(error, None)) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + + case Left(ContentExpected) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + } + + case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + } + } + + def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = + Unmarshaller[T](MediaTypes.`application/json`) { + case x: HttpEntity.NonEmpty ⇒ + parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) + .noNulls + .camelizeKeys + .extract[T] + } + +} + +sealed trait CustomContentTypes { + + def normalizedContentType(original: String): ContentType = + MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) + + def parseContentType(contentType: String): ContentType = { + val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) + val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) + (parsedContentTypeHeader: @unchecked) match { + case Right(ct: HttpHeaders.`Content-Type`) => + ct.contentType + case Left(error: ErrorInfo) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.summary}'") + } + } +} + +sealed trait UntrustedSslContext { + this: ApiInvoker => + + implicit lazy val trustfulSslContext: SSLContext = { + settings.alwaysTrustCertificates match { + case false => + SSLContext.getDefault + + case true => + class IgnoreX509TrustManager extends X509TrustManager { + def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def getAcceptedIssuers = null + } + + val context = SSLContext.getInstance("TLS") + context.init(null, Array(new IgnoreX509TrustManager), null) + context + } + } + + implicit val clientSSLEngineProvider = + ClientSSLEngineProvider { + _ => + val engine = trustfulSslContext.createSSLEngine() + engine.setUseClientMode(true) + engine + } +} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala new file mode 100644 index 00000000000..0588193cfbe --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala @@ -0,0 +1,50 @@ +package io.swagger.client.core + +sealed trait ResponseState +object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody() = copy[U](bodyParam = None) + + def withBody(body: Any) = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala new file mode 100644 index 00000000000..3162fb9f6be --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala @@ -0,0 +1,32 @@ +package io.swagger.client.core + +import java.util.concurrent.TimeUnit + +import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey} +import com.typesafe.config.Config +import io.swagger.client.core.ApiInvoker.CustomStatusCode +import spray.http.HttpHeaders.RawHeader + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("io.swagger.client.apiRequest") + + val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") + val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt + val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) + } + + +} + +object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala new file mode 100644 index 00000000000..a096a994ea3 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/core/requests.scala @@ -0,0 +1,166 @@ +package io.swagger.client.core + +import java.io.File +import java.net.URLEncoder +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) + def getStringHeader(name: String) = header(name) + def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) + def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) + def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) + def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) + def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList = m.toList.flatMap(formattedParams) + + def asFormattedParams = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => + formattedParams(name, opt) + case s: Seq[Any] => + formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + + } +} diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 00000000000..5eec9d159de --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Category ( + Id: Option[Long], + Name: Option[String]) + extends ApiModel + + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala new file mode 100644 index 00000000000..5fe2c3d0a67 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -0,0 +1,29 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Order ( + Id: Option[Long], + PetId: Option[Long], + Quantity: Option[Int], + ShipDate: Option[DateTime], + /* Order Status */ + Status: Option[OrderEnums.Status], + Complete: Option[Boolean]) + extends ApiModel + +object OrderEnums { + + type Status = Status.Value + + object Status extends Enumeration { + val Placed = Value("placed") + val Approved = Value("approved") + val Delivered = Value("delivered") + } + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala new file mode 100644 index 00000000000..5007c7d9585 --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -0,0 +1,29 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Pet ( + Id: Option[Long], + Category: Option[Category], + Name: String, + PhotoUrls: Seq[String], + Tags: Option[Seq[Tag]], + /* pet status in the store */ + Status: Option[PetEnums.Status]) + extends ApiModel + +object PetEnums { + + type Status = Status.Value + + object Status extends Enumeration { + val Available = Value("available") + val Pending = Value("pending") + val Sold = Value("sold") + } + + +} + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala new file mode 100644 index 00000000000..8f7c3f2aa4a --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Tag ( + Id: Option[Long], + Name: Option[String]) + extends ApiModel + + diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 00000000000..c9772f5361e --- /dev/null +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,19 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class User ( + Id: Option[Long], + Username: Option[String], + FirstName: Option[String], + LastName: Option[String], + Email: Option[String], + Password: Option[String], + Phone: Option[String], + /* User Status */ + UserStatus: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/pom.xml b/samples/client/wordnik/akka-scala/pom.xml new file mode 100644 index 00000000000..f865a97c38b --- /dev/null +++ b/samples/client/wordnik/akka-scala/pom.xml @@ -0,0 +1,227 @@ + + 4.0.0 + com.wordnik + swagger-client + jar + swagger-client + 1.0.0 + + 2.2.0 + + + + + maven-mongodb-plugin-repo + maven mongodb plugin repository + http://maven-mongodb-plugin.googlecode.com/svn/maven/repo + default + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.2 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.3.2 + + + 1.6 + 1.6 + + + + net.alchim31.maven + scala-maven-plugin + ${scala-maven-plugin-version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + + + + org.scala-tools + maven-scala-plugin + + ${scala-version} + + + + + + + org.scala-lang + scala-library + ${scala-version} + + + com.wordnik + swagger-core + ${swagger-core-version} + + + org.scalatest + scalatest_2.10 + ${scala-test-version} + test + + + junit + junit + ${junit-version} + test + + + joda-time + joda-time + ${joda-time-version} + + + org.joda + joda-convert + ${joda-version} + + + com.typesafe + config + 1.2.1 + + + com.typesafe.akka + akka-actor_2.10 + ${akka-version} + + + io.spray + spray-client + ${spray-version} + + + org.json4s + json4s-jackson_2.10 + ${json4s-jackson-version} + + + + 2.10.4 + 3.2.11 + 3.2.11 + 1.3.1 + 2.3.9 + 1.2 + 2.2 + 1.5.0-M1 + 1.0.0 + + 4.8.1 + 3.1.5 + 2.1.3 + + diff --git a/samples/client/wordnik/akka-scala/src/main/resources/reference.conf b/samples/client/wordnik/akka-scala/src/main/resources/reference.conf new file mode 100644 index 00000000000..f993f765edd --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/resources/reference.conf @@ -0,0 +1,24 @@ +io.swagger.client { + + apiRequest { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: 5000ms + + default-headers { + "userAgent": "swagger-client_1.0.0" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala new file mode 100644 index 00000000000..920159a629f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala @@ -0,0 +1,109 @@ +package io.swagger.client.api + +import io.swagger.client.model.ApiTokenStatus +import io.swagger.client.model.AuthenticationToken +import io.swagger.client.model.User +import io.swagger.client.model.WordList +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object AccountApi { + + /** + * + * + * Expected answers: + * code 200 : ApiTokenStatus (Usage statistics for the supplied API key) + * code 400 : (No token supplied.) + * code 404 : (No API account with supplied token.) + * + * @param ApiKey Wordnik authentication token + */ + def getApiTokenStatus(ApiKey: Option[String] = None): ApiRequest[ApiTokenStatus] = + ApiRequest[ApiTokenStatus](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/apiTokenStatus", "application/json") + .withHeaderParam("api_key", ApiKey) + .withSuccessResponse[ApiTokenStatus](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : AuthenticationToken (A valid authentication token) + * code 403 : (Account not available.) + * code 404 : (User not found.) + * + * @param Username A confirmed Wordnik username + * @param Password The user's password + */ + def authenticate(Username: String, Password: String): ApiRequest[AuthenticationToken] = + ApiRequest[AuthenticationToken](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json") + .withQueryParam("password", Password) + .withPathParam("username", Username) + .withSuccessResponse[AuthenticationToken](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : AuthenticationToken (A valid authentication token) + * code 403 : (Account not available.) + * code 404 : (User not found.) + * + * @param Username A confirmed Wordnik username + * @param Body The user's password + */ + def authenticatePost(Username: String, Body: String): ApiRequest[AuthenticationToken] = + ApiRequest[AuthenticationToken](ApiMethods.POST, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json") + .withBody(Body) + .withPathParam("username", Username) + .withSuccessResponse[AuthenticationToken](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * Requires a valid auth_token to be set. + * + * Expected answers: + * code 200 : User (The logged-in user) + * code 403 : (Not logged in.) + * code 404 : (User not found.) + * + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def getLoggedInUser(AuthToken: String): ApiRequest[User] = + ApiRequest[User](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/user", "application/json") + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[User](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : Seq[WordList] (success) + * code 403 : (Not authenticated.) + * code 404 : (User account not found.) + * + * @param AuthToken auth_token of logged-in user + * @param Skip Results to skip + * @param Limit Maximum number of results to return + */ + def getWordListsForLoggedInUser(AuthToken: String, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[Seq[WordList]] = + ApiRequest[Seq[WordList]](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/wordLists", "application/json") + .withQueryParam("skip", Skip) + .withQueryParam("limit", Limit) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[Seq[WordList]](200) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala new file mode 100644 index 00000000000..c95a49ad0b2 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/EnumsSerializers.scala @@ -0,0 +1,41 @@ +package io.swagger.client.api + +import io.swagger.client.model._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all = Seq[Serializer[_]]() + + + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => { + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} \ No newline at end of file diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala new file mode 100644 index 00000000000..bbcf2dd357c --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala @@ -0,0 +1,253 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.AudioFile +import io.swagger.client.model.Definition +import io.swagger.client.model.FrequencySummary +import io.swagger.client.model.Bigram +import io.swagger.client.model.Example +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordApi { + + /** + * + * + * Expected answers: + * code 200 : WordObject (success) + * code 400 : (Invalid word supplied.) + * + * @param Word String value of WordObject to return + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param IncludeSuggestions Return suggestions (for correct spelling, case variants, etc.) + */ + def getWord(Word: String, UseCanonical: Option[String] = None, IncludeSuggestions: Option[String] = None): ApiRequest[WordObject] = + ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("includeSuggestions", IncludeSuggestions) + .withPathParam("word", Word) + .withSuccessResponse[WordObject](200) + .withErrorResponse[Unit](400) + + /** + * The metadata includes a time-expiring fileUrl which allows reading the audio file directly from the API. Currently only audio pronunciations from the American Heritage Dictionary in mp3 format are supported. + * + * Expected answers: + * code 200 : Seq[AudioFile] (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to get audio for. + * @param UseCanonical Use the canonical form of the word + * @param Limit Maximum number of results to return + */ + def getAudio(Word: String, UseCanonical: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Seq[AudioFile]] = + ApiRequest[Seq[AudioFile]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/audio", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("limit", Limit) + .withPathParam("word", Word) + .withSuccessResponse[Seq[AudioFile]](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : Seq[Definition] (success) + * code 400 : (Invalid word supplied.) + * code 404 : (No definitions found.) + * + * @param Word Word to return definitions for + * @param Limit Maximum number of results to return + * @param PartOfSpeech CSV list of part-of-speech types + * @param IncludeRelated Return related words with definitions + * @param SourceDictionaries Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param IncludeTags Return a closed set of XML tags in response + */ + def getDefinitions(Word: String, Limit: Option[Int] = None, PartOfSpeech: Option[String] = None, IncludeRelated: Option[String] = None, SourceDictionaries: Seq[String], UseCanonical: Option[String] = None, IncludeTags: Option[String] = None): ApiRequest[Seq[Definition]] = + ApiRequest[Seq[Definition]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/definitions", "application/json") + .withQueryParam("limit", Limit) + .withQueryParam("partOfSpeech", PartOfSpeech) + .withQueryParam("includeRelated", IncludeRelated) + .withQueryParam("sourceDictionaries", ArrayValues(SourceDictionaries, CSV)) + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("includeTags", IncludeTags) + .withPathParam("word", Word) + .withSuccessResponse[Seq[Definition]](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : Seq[String] (success) + * code 400 : (Invalid word supplied.) + * code 404 : (No definitions found.) + * + * @param Word Word to return + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + */ + def getEtymologies(Word: String, UseCanonical: Option[String] = None): ApiRequest[Seq[String]] = + ApiRequest[Seq[String]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/etymologies", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withPathParam("word", Word) + .withSuccessResponse[Seq[String]](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to return examples for + * @param IncludeDuplicates Show duplicate examples from different sources + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param Skip Results to skip + * @param Limit Maximum number of results to return + */ + def getExamples(Word: String, IncludeDuplicates: Option[String] = None, UseCanonical: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/examples", "application/json") + .withQueryParam("includeDuplicates", IncludeDuplicates) + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("skip", Skip) + .withQueryParam("limit", Limit) + .withPathParam("word", Word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : FrequencySummary (success) + * code 400 : (Invalid word supplied.) + * code 404 : (No results.) + * + * @param Word Word to return + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param StartYear Starting Year + * @param EndYear Ending Year + */ + def getWordFrequency(Word: String, UseCanonical: Option[String] = None, StartYear: Option[Int] = None, EndYear: Option[Int] = None): ApiRequest[FrequencySummary] = + ApiRequest[FrequencySummary](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/frequency", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("startYear", StartYear) + .withQueryParam("endYear", EndYear) + .withPathParam("word", Word) + .withSuccessResponse[FrequencySummary](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to get syllables for + * @param UseCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param SourceDictionary Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. + * @param Limit Maximum number of results to return + */ + def getHyphenation(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/hyphenation", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("sourceDictionary", SourceDictionary) + .withQueryParam("limit", Limit) + .withPathParam("word", Word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : Seq[Bigram] (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to fetch phrases for + * @param Limit Maximum number of results to return + * @param Wlmi Minimum WLMI for the phrase + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + */ + def getPhrases(Word: String, Limit: Option[Int] = None, Wlmi: Option[Int] = None, UseCanonical: Option[String] = None): ApiRequest[Seq[Bigram]] = + ApiRequest[Seq[Bigram]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/phrases", "application/json") + .withQueryParam("limit", Limit) + .withQueryParam("wlmi", Wlmi) + .withQueryParam("useCanonical", UseCanonical) + .withPathParam("word", Word) + .withSuccessResponse[Seq[Bigram]](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to get pronunciations for + * @param UseCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param SourceDictionary Get from a single dictionary + * @param TypeFormat Text pronunciation type + * @param Limit Maximum number of results to return + */ + def getTextPronunciations(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, TypeFormat: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/pronunciations", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("sourceDictionary", SourceDictionary) + .withQueryParam("typeFormat", TypeFormat) + .withQueryParam("limit", Limit) + .withPathParam("word", Word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to fetch relationships for + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param RelationshipTypes Limits the total results per type of relationship type + * @param LimitPerRelationshipType Restrict to the supplied relationship types + */ + def getRelatedWords(Word: String, UseCanonical: Option[String] = None, RelationshipTypes: Option[String] = None, LimitPerRelationshipType: Option[Int] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/relatedWords", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withQueryParam("relationshipTypes", RelationshipTypes) + .withQueryParam("limitPerRelationshipType", LimitPerRelationshipType) + .withPathParam("word", Word) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : Example (success) + * code 400 : (Invalid word supplied.) + * + * @param Word Word to fetch examples for + * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + */ + def getTopExample(Word: String, UseCanonical: Option[String] = None): ApiRequest[Example] = + ApiRequest[Example](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/topExample", "application/json") + .withQueryParam("useCanonical", UseCanonical) + .withPathParam("word", Word) + .withSuccessResponse[Example](200) + .withErrorResponse[Unit](400) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala new file mode 100644 index 00000000000..8d34cfd3f3f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala @@ -0,0 +1,154 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.model.StringValue +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordListApi { + + /** + * + * + * Expected answers: + * code 200 : WordList (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to access WordList) + * code 404 : (WordList not found) + * + * @param Permalink permalink of WordList to fetch + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def getWordListByPermalink(Permalink: String, AuthToken: String): ApiRequest[WordList] = + ApiRequest[WordList](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + .withPathParam("permalink", Permalink) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[WordList](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to update WordList) + * code 404 : (WordList not found) + * + * @param Permalink permalink of WordList to update + * @param Body Updated WordList + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def updateWordList(Permalink: String, Body: Option[WordList] = None, AuthToken: String): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.PUT, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + .withBody(Body) + .withPathParam("permalink", Permalink) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to delete WordList) + * code 404 : (WordList not found) + * + * @param Permalink ID of WordList to delete + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def deleteWordList(Permalink: String, AuthToken: String): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.DELETE, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + .withPathParam("permalink", Permalink) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid permalink supplied) + * code 403 : (Not Authorized to modify WordList) + * code 404 : (WordList not found) + * + * @param Permalink permalink of WordList to use + * @param Body Words to remove from WordList + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def deleteWordsFromWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/deleteWords", "application/json") + .withBody(Body) + .withPathParam("permalink", Permalink) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid ID supplied) + * code 403 : (Not Authorized to access WordList) + * code 404 : (WordList not found) + * + * @param Permalink ID of WordList to use + * @param SortBy Field to sort by + * @param SortOrder Direction to sort + * @param Skip Results to skip + * @param Limit Maximum number of results to return + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def getWordListWords(Permalink: String, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None, AuthToken: String): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") + .withQueryParam("sortBy", SortBy) + .withQueryParam("sortOrder", SortOrder) + .withQueryParam("skip", Skip) + .withQueryParam("limit", Limit) + .withPathParam("permalink", Permalink) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid permalink supplied) + * code 403 : (Not Authorized to access WordList) + * code 404 : (WordList not found) + * + * @param Permalink permalink of WordList to user + * @param Body Array of words to add to WordList + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def addWordsToWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") + .withBody(Body) + .withPathParam("permalink", Permalink) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala new file mode 100644 index 00000000000..a2540c383a0 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala @@ -0,0 +1,34 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordListsApi { + + /** + * + * + * Expected answers: + * code 200 : WordList (success) + * code 400 : (Invalid WordList supplied or mandatory fields are missing) + * code 403 : (Not authenticated) + * code 404 : (WordList owner not found) + * + * @param Body WordList to create + * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + */ + def createWordList(Body: Option[WordList] = None, AuthToken: String): ApiRequest[WordList] = + ApiRequest[WordList](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordLists.json", "application/json") + .withBody(Body) + .withHeaderParam("auth_token", AuthToken) + .withSuccessResponse[WordList](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](403) + .withErrorResponse[Unit](404) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala new file mode 100644 index 00000000000..4ca9ab1310b --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala @@ -0,0 +1,181 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.DefinitionSearchResults +import io.swagger.client.model.WordSearchResults +import io.swagger.client.model.WordOfTheDay +import io.swagger.client.core._ +import io.swagger.client.core.CollectionFormats._ +import io.swagger.client.core.ApiKeyLocations._ + +object WordsApi { + + /** + * + * + * Expected answers: + * code 200 : WordObject (success) + * code 404 : (No word found.) + * + * @param HasDictionaryDef Only return words with dictionary definitions + * @param IncludePartOfSpeech CSV part-of-speech values to include + * @param ExcludePartOfSpeech CSV part-of-speech values to exclude + * @param MinCorpusCount Minimum corpus frequency for terms + * @param MaxCorpusCount Maximum corpus frequency for terms + * @param MinDictionaryCount Minimum dictionary count + * @param MaxDictionaryCount Maximum dictionary count + * @param MinLength Minimum word length + * @param MaxLength Maximum word length + */ + def getRandomWord(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None): ApiRequest[WordObject] = + ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWord", "application/json") + .withQueryParam("hasDictionaryDef", HasDictionaryDef) + .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) + .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) + .withQueryParam("minCorpusCount", MinCorpusCount) + .withQueryParam("maxCorpusCount", MaxCorpusCount) + .withQueryParam("minDictionaryCount", MinDictionaryCount) + .withQueryParam("maxDictionaryCount", MaxDictionaryCount) + .withQueryParam("minLength", MinLength) + .withQueryParam("maxLength", MaxLength) + .withSuccessResponse[WordObject](200) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : (success) + * code 400 : (Invalid term supplied.) + * code 404 : (No results.) + * + * @param HasDictionaryDef Only return words with dictionary definitions + * @param IncludePartOfSpeech CSV part-of-speech values to include + * @param ExcludePartOfSpeech CSV part-of-speech values to exclude + * @param MinCorpusCount Minimum corpus frequency for terms + * @param MaxCorpusCount Maximum corpus frequency for terms + * @param MinDictionaryCount Minimum dictionary count + * @param MaxDictionaryCount Maximum dictionary count + * @param MinLength Minimum word length + * @param MaxLength Maximum word length + * @param SortBy Attribute to sort by + * @param SortOrder Sort direction + * @param Limit Maximum number of results to return + */ + def getRandomWords(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = + ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWords", "application/json") + .withQueryParam("hasDictionaryDef", HasDictionaryDef) + .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) + .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) + .withQueryParam("minCorpusCount", MinCorpusCount) + .withQueryParam("maxCorpusCount", MaxCorpusCount) + .withQueryParam("minDictionaryCount", MinDictionaryCount) + .withQueryParam("maxDictionaryCount", MaxDictionaryCount) + .withQueryParam("minLength", MinLength) + .withQueryParam("maxLength", MaxLength) + .withQueryParam("sortBy", SortBy) + .withQueryParam("sortOrder", SortOrder) + .withQueryParam("limit", Limit) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + /** + * + * + * Expected answers: + * code 200 : DefinitionSearchResults (success) + * code 400 : (Invalid term supplied.) + * + * @param Query Search term + * @param FindSenseForWord Restricts words and finds closest sense + * @param IncludeSourceDictionaries Only include these comma-delimited source dictionaries + * @param ExcludeSourceDictionaries Exclude these comma-delimited source dictionaries + * @param IncludePartOfSpeech Only include these comma-delimited parts of speech + * @param ExcludePartOfSpeech Exclude these comma-delimited parts of speech + * @param MinCorpusCount Minimum corpus frequency for terms + * @param MaxCorpusCount Maximum corpus frequency for terms + * @param MinLength Minimum word length + * @param MaxLength Maximum word length + * @param ExpandTerms Expand terms + * @param IncludeTags Return a closed set of XML tags in response + * @param SortBy Attribute to sort by + * @param SortOrder Sort direction + * @param Skip Results to skip + * @param Limit Maximum number of results to return + */ + def reverseDictionary(Query: String, FindSenseForWord: Option[String] = None, IncludeSourceDictionaries: Option[String] = None, ExcludeSourceDictionaries: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, ExpandTerms: Option[String] = None, IncludeTags: Option[String] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[String] = None, Limit: Option[Int] = None): ApiRequest[DefinitionSearchResults] = + ApiRequest[DefinitionSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/reverseDictionary", "application/json") + .withQueryParam("query", Query) + .withQueryParam("findSenseForWord", FindSenseForWord) + .withQueryParam("includeSourceDictionaries", IncludeSourceDictionaries) + .withQueryParam("excludeSourceDictionaries", ExcludeSourceDictionaries) + .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) + .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) + .withQueryParam("minCorpusCount", MinCorpusCount) + .withQueryParam("maxCorpusCount", MaxCorpusCount) + .withQueryParam("minLength", MinLength) + .withQueryParam("maxLength", MaxLength) + .withQueryParam("expandTerms", ExpandTerms) + .withQueryParam("includeTags", IncludeTags) + .withQueryParam("sortBy", SortBy) + .withQueryParam("sortOrder", SortOrder) + .withQueryParam("skip", Skip) + .withQueryParam("limit", Limit) + .withSuccessResponse[DefinitionSearchResults](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 200 : WordSearchResults (success) + * code 400 : (Invalid query supplied.) + * + * @param Query Search query + * @param CaseSensitive Search case sensitive + * @param IncludePartOfSpeech Only include these comma-delimited parts of speech + * @param ExcludePartOfSpeech Exclude these comma-delimited parts of speech + * @param MinCorpusCount Minimum corpus frequency for terms + * @param MaxCorpusCount Maximum corpus frequency for terms + * @param MinDictionaryCount Minimum number of dictionary entries for words returned + * @param MaxDictionaryCount Maximum dictionary definition count + * @param MinLength Minimum word length + * @param MaxLength Maximum word length + * @param Skip Results to skip + * @param Limit Maximum number of results to return + */ + def searchWords(Query: String, CaseSensitive: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[WordSearchResults] = + ApiRequest[WordSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/search/{query}", "application/json") + .withQueryParam("caseSensitive", CaseSensitive) + .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) + .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) + .withQueryParam("minCorpusCount", MinCorpusCount) + .withQueryParam("maxCorpusCount", MaxCorpusCount) + .withQueryParam("minDictionaryCount", MinDictionaryCount) + .withQueryParam("maxDictionaryCount", MaxDictionaryCount) + .withQueryParam("minLength", MinLength) + .withQueryParam("maxLength", MaxLength) + .withQueryParam("skip", Skip) + .withQueryParam("limit", Limit) + .withPathParam("query", Query) + .withSuccessResponse[WordSearchResults](200) + .withErrorResponse[Unit](400) + + /** + * + * + * Expected answers: + * code 0 : WordOfTheDay (success) + * + * @param Date Fetches by date in yyyy-MM-dd + */ + def getWordOfTheDay(Date: Option[String] = None): ApiRequest[WordOfTheDay] = + ApiRequest[WordOfTheDay](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/wordOfTheDay", "application/json") + .withQueryParam("date", Date) + .withSuccessResponse[WordOfTheDay](0) + + + +} + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala new file mode 100644 index 00000000000..3b11d866017 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiInvoker.scala @@ -0,0 +1,323 @@ +package io.swagger.client.core + +import java.io.File +import java.security.cert.X509Certificate +import javax.net.ssl._ + +import akka.actor.ActorSystem +import akka.io.IO +import akka.pattern.ask +import akka.util.Timeout +import org.joda.time.DateTime +import org.joda.time.format.ISODateTimeFormat +import org.json4s.JsonAST.JString +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization +import spray.can.Http +import spray.can.Http.HostConnectorSetup +import spray.client.pipelining +import spray.client.pipelining._ +import spray.http.HttpEncodings._ +import spray.http.HttpHeaders.{RawHeader, `Accept-Encoding`} +import spray.http.Uri.Query +import spray.http._ +import spray.http.parser.HttpParser +import spray.httpx.encoding.{Deflate, Encoder, Gzip} +import spray.httpx.unmarshalling._ +import spray.io.ClientSSLEngineProvider + +import scala.concurrent.{ExecutionContext, Future} +import scala.reflect.ClassTag +import scala.util.control.NonFatal + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer) + def apply(serializers: Traversable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats + DateTimeSerializer ++ serializers) + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + case class CustomStatusCode(value: Int, reason: String = "Application-defined status code", isSuccess: Boolean = true) + + def addCustomStatusCode(code: CustomStatusCode): Unit = addCustomStatusCode(code.value, code.reason, code.isSuccess) + + def addCustomStatusCode(code: Int, reason: String = "Application defined code", isSuccess: Boolean = true) = { + StatusCodes.getForKey(code) foreach { c => + StatusCodes.registerCustom(code, reason, reason, isSuccess, allowsEntity = true) + } + } + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will failed with a ClassCastException + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toSprayMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + + case object DateTimeSerializer extends CustomSerializer[DateTime](format => ( { + case JString(s) => + ISODateTimeFormat.dateTimeParser().parseDateTime(s) + }, { + case d: DateTime => + JString(ISODateTimeFormat.dateTimeParser().print(d)) + })) +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends UntrustedSslContext with CustomContentTypes { + + import io.swagger.client.core.ApiInvoker._ + import io.swagger.client.core.ParametersMap._ + + implicit val ec = system.dispatcher + implicit val jsonFormats = formats + + def settings = ApiSettings(system) + + import spray.http.MessagePredicate._ + + val CompressionFilter = MessagePredicate({ _ => settings.compressionEnabled}) && + Encoder.DefaultFilter && + minEntitySize(settings.compressionSizeThreshold) + + settings.customCodes.foreach(addCustomStatusCode) + + private def addAuthentication(credentialsSeq: Seq[Credentials]): pipelining.RequestTransformer = + request => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req ~> addCredentials(BasicHttpCredentials(login, password)) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req ~> addHeader(RawHeader(keyName, keyValue.value)) + case (req, _) => req + } + + private def addHeaders(headers: Map[String, Any]): pipelining.RequestTransformer = { request => + + val rawHeaders = for { + (name, value) <- headers.asFormattedParams + header = RawHeader(name, String.valueOf(value)) + } yield header + + request.withHeaders(rawHeaders.toList) + } + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart(f, name) + case v: String => + BodyPart(HttpEntity(String.valueOf(v))) + case NumericValue(v) => + BodyPart(HttpEntity(String.valueOf(v))) + case m: ApiModel => + BodyPart(HttpEntity(Serialization.write(m))) + } + } + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + MultipartFormData(params.map { case (name, value) => (name, bodyPart(name, value))}) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.mapValues(String.valueOf)) + case m: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.mapValues(String.valueOf)) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = { + request.bodyParam.map(Extraction.decompose).map(compact) + } + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + + val builder = new RequestBuilder(request.method.toSprayMethod) + val httpRequest = request.method.toSprayMethod match { + case HttpMethods.GET | HttpMethods.DELETE => builder.apply(uri) + case HttpMethods.POST | HttpMethods.PUT => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + builder.apply(uri, c) + case Some(c: MultipartFormData) => + builder.apply(uri, c) + case Some(c: String) => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), c)) + case _ => + builder.apply(uri, HttpEntity(normalizedContentType(request.contentType), " ")) + } + case _ => builder.apply(uri) + } + + httpRequest ~> + addHeaders(request.headerParams) ~> + addAuthentication(request.credentials) ~> + encode(Gzip(CompressionFilter)) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .mapValues(String.valueOf) + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .mapValues(String.valueOf) + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T](r: ApiRequest[T]): Future[ApiResponse[T]] = { + try { + implicit val timeout: Timeout = settings.connectionTimeout + + val uri = makeUri(r) + + val connector = HostConnectorSetup( + uri.authority.host.toString, + uri.effectivePort, + sslEncryption = "https".equals(uri.scheme), + defaultHeaders = settings.defaultHeaders ++ List(`Accept-Encoding`(gzip, deflate))) + + val request = createRequest(uri, r) + + for { + Http.HostConnectorInfo(hostConnector, _) <- IO(Http) ? connector + response <- hostConnector.ask(request).mapTo[HttpResponse] + } yield { + response ~> decode(Deflate) ~> decode(Gzip) ~> unmarshallApiResponse(r) + } + } + catch { + case NonFatal(x) => Future.failed(x) + } + } + + def unmarshallApiResponse[T](request: ApiRequest[T])(response: HttpResponse): ApiResponse[T] = { + request.responseForCode(response.status.intValue) match { + case Some( (manifest: Manifest[T], state: ResponseState) ) => + entityUnmarshaller(manifest)(response.entity) match { + case Right(value) ⇒ + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw new ApiError(response.status.intValue, "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap) + } + + case Left(MalformedContent(error, Some(cause))) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), cause) + + case Left(MalformedContent(error, None)) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString)) + + case Left(ContentExpected) ⇒ + throw new ApiError(response.status.intValue, s"Unable to unmarshall empty response to [$manifest]", Some(response.entity.toString)) + } + + case _ => throw new ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString)) + } + } + + def entityUnmarshaller[T](implicit mf: Manifest[T]): Unmarshaller[T] = + Unmarshaller[T](MediaTypes.`application/json`) { + case x: HttpEntity.NonEmpty ⇒ + parse(x.asString(defaultCharset = HttpCharsets.`UTF-8`)) + .noNulls + .camelizeKeys + .extract[T] + } + +} + +sealed trait CustomContentTypes { + + def normalizedContentType(original: String): ContentType = + MediaTypes.forExtension(original) map (ContentType(_)) getOrElse parseContentType(original) + + def parseContentType(contentType: String): ContentType = { + val contentTypeAsRawHeader = HttpHeaders.RawHeader("Content-Type", contentType) + val parsedContentTypeHeader = HttpParser.parseHeader(contentTypeAsRawHeader) + (parsedContentTypeHeader: @unchecked) match { + case Right(ct: HttpHeaders.`Content-Type`) => + ct.contentType + case Left(error: ErrorInfo) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.summary}'") + } + } +} + +sealed trait UntrustedSslContext { + this: ApiInvoker => + + implicit lazy val trustfulSslContext: SSLContext = { + settings.alwaysTrustCertificates match { + case false => + SSLContext.getDefault + + case true => + class IgnoreX509TrustManager extends X509TrustManager { + def checkClientTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def checkServerTrusted(chain: Array[X509Certificate], authType: String): Unit = {} + + def getAcceptedIssuers = null + } + + val context = SSLContext.getInstance("TLS") + context.init(null, Array(new IgnoreX509TrustManager), null) + context + } + } + + implicit val clientSSLEngineProvider = + ClientSSLEngineProvider { + _ => + val engine = trustfulSslContext.createSSLEngine() + engine.setUseClientMode(true) + engine + } +} diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala new file mode 100644 index 00000000000..0588193cfbe --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiRequest.scala @@ -0,0 +1,50 @@ +package io.swagger.client.core + +sealed trait ResponseState +object ResponseState { + case object Success extends ResponseState + case object Error extends ResponseState +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials) = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]) = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]) = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]) = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody() = copy[U](bodyParam = None) + + def withBody(body: Any) = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any) = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any) = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(name: String, value: Any) = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any) = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala new file mode 100644 index 00000000000..3162fb9f6be --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/ApiSettings.scala @@ -0,0 +1,32 @@ +package io.swagger.client.core + +import java.util.concurrent.TimeUnit + +import akka.actor.{ExtendedActorSystem, Extension, ExtensionKey} +import com.typesafe.config.Config +import io.swagger.client.core.ApiInvoker.CustomStatusCode +import spray.http.HttpHeaders.RawHeader + +import scala.collection.JavaConversions._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("io.swagger.client.apiRequest") + + val alwaysTrustCertificates = cfg.getBoolean("trust-certificates") + val defaultHeaders = cfg.getConfig("default-headers").entrySet.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold = cfg.getBytes("compression.size-threshold").toInt + val customCodes = cfg.getConfigList("custom-codes").toList.map { c => CustomStatusCode( + c.getInt("code"), + c.getString("reason"), + c.getBoolean("success")) + } + + +} + +object ApiSettings extends ExtensionKey[ApiSettings] diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala new file mode 100644 index 00000000000..a096a994ea3 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/core/requests.scala @@ -0,0 +1,166 @@ +package io.swagger.client.core + +import java.io.File +import java.net.URLEncoder +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + def header(name: String): Option[String] = headers.get(name) + def getStringHeader(name: String) = header(name) + def getIntHeader(name: String) = castedHeader(name, java.lang.Integer.parseInt) + def getLongHeader(name: String) = castedHeader(name, java.lang.Long.parseLong) + def getFloatHeader(name: String) = castedHeader(name, java.lang.Float.parseFloat) + def getDoubleHeader(name: String) = castedHeader(name, java.lang.Double.parseDouble) + def getBooleanHeader(name: String) = castedHeader(name, java.lang.Boolean.parseBoolean) + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { Try { header(name).map( conversion ) }.get } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tupple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tupples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList = m.toList.flatMap(formattedParams) + + def asFormattedParams = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => + formattedParams(name, opt) + case s: Seq[Any] => + formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + + } +} diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala new file mode 100644 index 00000000000..41a0615c0e4 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ApiTokenStatus ( + Valid: Option[Boolean], + Token: Option[String], + ResetsInMillis: Option[Long], + RemainingCalls: Option[Long], + ExpiresInMillis: Option[Long], + TotalRequests: Option[Long]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala new file mode 100644 index 00000000000..6f3b759a2cb --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala @@ -0,0 +1,24 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class AudioFile ( + AttributionUrl: Option[String], + CommentCount: Option[Int], + VoteCount: Option[Int], + FileUrl: Option[String], + AudioType: Option[String], + Id: Option[Long], + Duration: Option[Double], + AttributionText: Option[String], + CreatedBy: Option[String], + Description: Option[String], + CreatedAt: Option[DateTime], + VoteWeightedAverage: Option[Float], + VoteAverage: Option[Float], + Word: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala new file mode 100644 index 00000000000..deda697e9e3 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class AudioType ( + Id: Option[Int], + Name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala new file mode 100644 index 00000000000..169571959e3 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class AuthenticationToken ( + Token: Option[String], + UserId: Option[Long], + UserSignature: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala new file mode 100644 index 00000000000..0559c35f7fa --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Bigram ( + Count: Option[Long], + Gram2: Option[String], + Gram1: Option[String], + Wlmi: Option[Double], + Mi: Option[Double]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 00000000000..5eec9d159de --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Category ( + Id: Option[Long], + Name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala new file mode 100644 index 00000000000..af025124060 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Citation ( + Cite: Option[String], + Source: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala new file mode 100644 index 00000000000..be35406b63e --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ContentProvider ( + Id: Option[Int], + Name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala new file mode 100644 index 00000000000..00b58932167 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala @@ -0,0 +1,26 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Definition ( + ExtendedText: Option[String], + Text: Option[String], + SourceDictionary: Option[String], + Citations: Option[Seq[Citation]], + Labels: Option[Seq[Label]], + Score: Option[Float], + ExampleUses: Option[Seq[ExampleUsage]], + AttributionUrl: Option[String], + SeqString: Option[String], + AttributionText: Option[String], + RelatedWords: Option[Seq[Related]], + Sequence: Option[String], + Word: Option[String], + Notes: Option[Seq[Note]], + TextProns: Option[Seq[TextPron]], + PartOfSpeech: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala new file mode 100644 index 00000000000..a757637d42f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class DefinitionSearchResults ( + Results: Option[Seq[Definition]], + TotalResults: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala new file mode 100644 index 00000000000..9604f2aa625 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Example ( + Id: Option[Long], + ExampleId: Option[Long], + Title: Option[String], + Text: Option[String], + Score: Option[ScoredWord], + Sentence: Option[Sentence], + Word: Option[String], + Provider: Option[ContentProvider], + Year: Option[Int], + Rating: Option[Float], + DocumentId: Option[Long], + Url: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala new file mode 100644 index 00000000000..8ef6be3f172 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ExampleSearchResults ( + Facets: Option[Seq[Facet]], + Examples: Option[Seq[Example]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala new file mode 100644 index 00000000000..2e6fff5f975 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ExampleUsage ( + Text: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala new file mode 100644 index 00000000000..4e113440c52 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Facet ( + FacetValues: Option[Seq[FacetValue]], + Name: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala new file mode 100644 index 00000000000..4d4d7294851 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class FacetValue ( + Count: Option[Long], + Value: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala new file mode 100644 index 00000000000..595e001c6a7 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Frequency ( + Count: Option[Long], + Year: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala new file mode 100644 index 00000000000..3f0ac1c0c53 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class FrequencySummary ( + UnknownYearCount: Option[Int], + TotalCount: Option[Long], + FrequencyString: Option[String], + Word: Option[String], + Frequency: Option[Seq[Frequency]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala new file mode 100644 index 00000000000..52b386526c2 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Label ( + Text: Option[String], + Type: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala new file mode 100644 index 00000000000..6975837dcb5 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Note ( + NoteType: Option[String], + AppliesTo: Option[Seq[String]], + Value: Option[String], + Pos: Option[Int]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala new file mode 100644 index 00000000000..8a659ce4872 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class PartOfSpeech ( + Roots: Option[Seq[Root]], + StorageAbbr: Option[Seq[String]], + AllCategories: Option[Seq[Category]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala new file mode 100644 index 00000000000..d5147838373 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala @@ -0,0 +1,17 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Related ( + Label1: Option[String], + RelationshipType: Option[String], + Label2: Option[String], + Label3: Option[String], + Words: Option[Seq[String]], + Gram: Option[String], + Label4: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala new file mode 100644 index 00000000000..b8580e33ef3 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Root ( + Id: Option[Long], + Name: Option[String], + Categories: Option[Seq[Category]]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala new file mode 100644 index 00000000000..79401c1e1b6 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala @@ -0,0 +1,21 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class ScoredWord ( + Position: Option[Int], + Id: Option[Long], + DocTermCount: Option[Int], + Lemma: Option[String], + WordType: Option[String], + Score: Option[Float], + SentenceId: Option[Long], + Word: Option[String], + Stopword: Option[Boolean], + BaseWordScore: Option[Double], + PartOfSpeech: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala new file mode 100644 index 00000000000..eb9944b10b7 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Sentence ( + HasScoredWords: Option[Boolean], + Id: Option[Long], + ScoredWords: Option[Seq[ScoredWord]], + Display: Option[String], + Rating: Option[Int], + DocumentMetadataId: Option[Long]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala new file mode 100644 index 00000000000..49ee8301c9f --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class SimpleDefinition ( + Text: Option[String], + Source: Option[String], + Note: Option[String], + PartOfSpeech: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala new file mode 100644 index 00000000000..1eea4ee4588 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class SimpleExample ( + Id: Option[Long], + Title: Option[String], + Text: Option[String], + Url: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala new file mode 100644 index 00000000000..71538e2425c --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class StringValue ( + Word: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala new file mode 100644 index 00000000000..99ed72f3502 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class Syllable ( + Text: Option[String], + Seq: Option[Int], + Type: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala new file mode 100644 index 00000000000..7d3d59dd726 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class TextPron ( + Raw: Option[String], + Seq: Option[Int], + RawType: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 00000000000..6b1db4b0c81 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,18 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class User ( + Id: Option[Long], + Username: Option[String], + Email: Option[String], + Status: Option[Int], + FaceBookId: Option[String], + UserName: Option[String], + DisplayName: Option[String], + Password: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala new file mode 100644 index 00000000000..9022b32efbe --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala @@ -0,0 +1,21 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordList ( + Id: Option[Long], + Permalink: Option[String], + Name: Option[String], + CreatedAt: Option[DateTime], + UpdatedAt: Option[DateTime], + LastActivityAt: Option[DateTime], + Username: Option[String], + UserId: Option[Long], + Description: Option[String], + NumberWordsInList: Option[Long], + Type: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala new file mode 100644 index 00000000000..c15ddd7c58d --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala @@ -0,0 +1,17 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordListWord ( + Id: Option[Long], + Word: Option[String], + Username: Option[String], + UserId: Option[Long], + CreatedAt: Option[DateTime], + NumberCommentsOnWord: Option[Long], + NumberLists: Option[Long]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala new file mode 100644 index 00000000000..a00491ba046 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala @@ -0,0 +1,16 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordObject ( + Id: Option[Long], + Word: Option[String], + OriginalWord: Option[String], + Suggestions: Option[Seq[String]], + CanonicalForm: Option[String], + Vulgar: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala new file mode 100644 index 00000000000..8cfbf432438 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordOfTheDay ( + Id: Option[Long], + ParentId: Option[String], + Category: Option[String], + CreatedBy: Option[String], + CreatedAt: Option[DateTime], + ContentProvider: Option[ContentProvider], + HtmlExtra: Option[String], + Word: Option[String], + Definitions: Option[Seq[SimpleDefinition]], + Examples: Option[Seq[SimpleExample]], + Note: Option[String], + PublishDate: Option[DateTime]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala new file mode 100644 index 00000000000..ca2cb8182ae --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordSearchResult ( + Count: Option[Long], + Lexicality: Option[Double], + Word: Option[String]) + extends ApiModel + + diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala new file mode 100644 index 00000000000..a4715f16612 --- /dev/null +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.core.ApiModel +import org.joda.time.DateTime + + +case class WordSearchResults ( + SearchResults: Option[Seq[WordSearchResult]], + TotalResults: Option[Int]) + extends ApiModel + + From ef3811390fd950fd9a0afe841a69fd363b707120 Mon Sep 17 00:00:00 2001 From: Camille Chafer Date: Thu, 2 Apr 2015 17:46:26 +0200 Subject: [PATCH 05/75] Some fixes for Wordnik & Petstore examples --- .../swagger/codegen/CodegenResponse.java | 1 + .../main/resources/akka-scala/api.mustache | 4 ++-- .../akka-scala/operationReturnType.mustache | 2 +- .../scala/io/swagger/client/api/PetApi.scala | 6 ++--- .../scala/io/swagger/client/api/UserApi.scala | 24 +++++++++---------- .../scala/io/swagger/client/api/WordApi.scala | 16 ++++++------- .../io/swagger/client/api/WordListApi.scala | 20 ++++++++-------- .../io/swagger/client/api/WordsApi.scala | 6 ++--- 8 files changed, 40 insertions(+), 39 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java index b23c5f72120..c4d9d2c6ed7 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java @@ -15,4 +15,5 @@ public class CodegenResponse { public Boolean isListContainer; public Object schema; public String jsonSchema; + public boolean isWildcard() { return "0".equals(code) || "default".equals(code); } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache index 34523b80353..fecf2827f04 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/api.mustache @@ -25,8 +25,8 @@ object {{classname}} { {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) - {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}]() - {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit]() + {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}] + {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit] {{/dataType}}{{/isWildcard}}{{/responses}}{{^responseHeaders.isEmpty}} object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { {{#responseHeaders}} def {{name}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}"){{/responseHeaders}} diff --git a/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache b/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache index e9d2be53401..ba0924313fb 100644 --- a/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache +++ b/modules/swagger-codegen/src/main/resources/akka-scala/operationReturnType.mustache @@ -1 +1 @@ -{{#onlyOneSuccess}}{{^defaultResponse}}Unit{{/defaultResponse}}{{#responses}}{{#isDefault}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/isDefault}}{{/responses}}{{/onlyOneSuccess}}{{^onlyOneSuccess}}{{#responses}}{{#-first}}{{^hasMore}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/hasMore}}{{#hasMore}}Any{{/hasMore}}{{/-first}}{{/responses}}{{/onlyOneSuccess}} \ No newline at end of file +{{#onlyOneSuccess}}{{^defaultResponse}}Unit{{/defaultResponse}}{{#defaultResponse}}{{#responses}}{{#isDefault}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/isDefault}}{{/responses}}{{/defaultResponse}}{{/onlyOneSuccess}}{{^onlyOneSuccess}}{{#responses}}{{#-first}}{{^hasMore}}{{#dataType}}{{dataType}}{{/dataType}}{{^dataType}}Unit{{/dataType}}{{/hasMore}}{{#hasMore}}Any{{/hasMore}}{{/-first}}{{/responses}}{{/onlyOneSuccess}} \ No newline at end of file diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala index d56d3f855a3..abb8054e753 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -126,12 +126,12 @@ object PetApi { * @param AdditionalMetadata Additional data to pass to server * @param File file to upload */ - def uploadFile(PetId: Long, AdditionalMetadata: Option[String] = None, File: Option[File] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}/uploadImage", "multipart/form-data") + def uploadFile(PetId: Long, AdditionalMetadata: Option[String] = None, File: Option[File] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}/uploadImage", "multipart/form-data") .withFormParam("additionalMetadata", AdditionalMetadata) .withFormParam("file", File) .withPathParam("petId", PetId) - .withSuccessResponse[Unit](0) + .withDefaultSuccessResponse[Unit] diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala index 77aade9a9e8..9fb026d950d 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -15,10 +15,10 @@ object UserApi { * * @param Body Created user object */ - def createUser(Body: Option[User] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user", "application/json") + def createUser(Body: Option[User] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user", "application/json") .withBody(Body) - .withSuccessResponse[Unit](0) + .withDefaultSuccessResponse[Unit] /** * @@ -27,10 +27,10 @@ object UserApi { * * @param Body List of user object */ - def createUsersWithArrayInput(Body: Seq[User]): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithArray", "application/json") + def createUsersWithArrayInput(Body: Seq[User]): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithArray", "application/json") .withBody(Body) - .withSuccessResponse[Unit](0) + .withDefaultSuccessResponse[Unit] /** * @@ -39,10 +39,10 @@ object UserApi { * * @param Body List of user object */ - def createUsersWithListInput(Body: Seq[User]): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithList", "application/json") + def createUsersWithListInput(Body: Seq[User]): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithList", "application/json") .withBody(Body) - .withSuccessResponse[Unit](0) + .withDefaultSuccessResponse[Unit] /** * @@ -65,9 +65,9 @@ object UserApi { * Expected answers: * code 0 : (successful operation) */ - def logoutUser(): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/logout", "application/json") - .withSuccessResponse[Unit](0) + def logoutUser(): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/logout", "application/json") + .withDefaultSuccessResponse[Unit] /** * diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala index bbcf2dd357c..36d706c4f40 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala @@ -111,8 +111,8 @@ object WordApi { * @param Skip Results to skip * @param Limit Maximum number of results to return */ - def getExamples(Word: String, IncludeDuplicates: Option[String] = None, UseCanonical: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/examples", "application/json") + def getExamples(Word: String, IncludeDuplicates: Option[String] = None, UseCanonical: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/examples", "application/json") .withQueryParam("includeDuplicates", IncludeDuplicates) .withQueryParam("useCanonical", UseCanonical) .withQueryParam("skip", Skip) @@ -156,8 +156,8 @@ object WordApi { * @param SourceDictionary Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. * @param Limit Maximum number of results to return */ - def getHyphenation(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/hyphenation", "application/json") + def getHyphenation(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/hyphenation", "application/json") .withQueryParam("useCanonical", UseCanonical) .withQueryParam("sourceDictionary", SourceDictionary) .withQueryParam("limit", Limit) @@ -199,8 +199,8 @@ object WordApi { * @param TypeFormat Text pronunciation type * @param Limit Maximum number of results to return */ - def getTextPronunciations(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, TypeFormat: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/pronunciations", "application/json") + def getTextPronunciations(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, TypeFormat: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/pronunciations", "application/json") .withQueryParam("useCanonical", UseCanonical) .withQueryParam("sourceDictionary", SourceDictionary) .withQueryParam("typeFormat", TypeFormat) @@ -221,8 +221,8 @@ object WordApi { * @param RelationshipTypes Limits the total results per type of relationship type * @param LimitPerRelationshipType Restrict to the supplied relationship types */ - def getRelatedWords(Word: String, UseCanonical: Option[String] = None, RelationshipTypes: Option[String] = None, LimitPerRelationshipType: Option[Int] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/relatedWords", "application/json") + def getRelatedWords(Word: String, UseCanonical: Option[String] = None, RelationshipTypes: Option[String] = None, LimitPerRelationshipType: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/relatedWords", "application/json") .withQueryParam("useCanonical", UseCanonical) .withQueryParam("relationshipTypes", RelationshipTypes) .withQueryParam("limitPerRelationshipType", LimitPerRelationshipType) diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala index 8d34cfd3f3f..54883fa07bd 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala @@ -42,8 +42,8 @@ object WordListApi { * @param Body Updated WordList * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def updateWordList(Permalink: String, Body: Option[WordList] = None, AuthToken: String): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.PUT, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + def updateWordList(Permalink: String, Body: Option[WordList] = None, AuthToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") .withBody(Body) .withPathParam("permalink", Permalink) .withHeaderParam("auth_token", AuthToken) @@ -64,8 +64,8 @@ object WordListApi { * @param Permalink ID of WordList to delete * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def deleteWordList(Permalink: String, AuthToken: String): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.DELETE, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") + def deleteWordList(Permalink: String, AuthToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") .withPathParam("permalink", Permalink) .withHeaderParam("auth_token", AuthToken) .withSuccessResponse[Unit](200) @@ -86,8 +86,8 @@ object WordListApi { * @param Body Words to remove from WordList * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def deleteWordsFromWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/deleteWords", "application/json") + def deleteWordsFromWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/deleteWords", "application/json") .withBody(Body) .withPathParam("permalink", Permalink) .withHeaderParam("auth_token", AuthToken) @@ -112,8 +112,8 @@ object WordListApi { * @param Limit Maximum number of results to return * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def getWordListWords(Permalink: String, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None, AuthToken: String): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") + def getWordListWords(Permalink: String, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None, AuthToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") .withQueryParam("sortBy", SortBy) .withQueryParam("sortOrder", SortOrder) .withQueryParam("skip", Skip) @@ -138,8 +138,8 @@ object WordListApi { * @param Body Array of words to add to WordList * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def addWordsToWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") + def addWordsToWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") .withBody(Body) .withPathParam("permalink", Permalink) .withHeaderParam("auth_token", AuthToken) diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala index 4ca9ab1310b..1a58a2f4139 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala @@ -62,8 +62,8 @@ object WordsApi { * @param SortOrder Sort direction * @param Limit Maximum number of results to return */ - def getRandomWords(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Limit: Option[Int] = None): ApiRequest[UnitUnit] = - ApiRequest[UnitUnit](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWords", "application/json") + def getRandomWords(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWords", "application/json") .withQueryParam("hasDictionaryDef", HasDictionaryDef) .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) @@ -173,7 +173,7 @@ object WordsApi { def getWordOfTheDay(Date: Option[String] = None): ApiRequest[WordOfTheDay] = ApiRequest[WordOfTheDay](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/wordOfTheDay", "application/json") .withQueryParam("date", Date) - .withSuccessResponse[WordOfTheDay](0) + .withDefaultSuccessResponse[WordOfTheDay] From 6c4765fd00322dbd25b764b20152cc965a473c98 Mon Sep 17 00:00:00 2001 From: Camille Chafer Date: Thu, 2 Apr 2015 18:00:25 +0200 Subject: [PATCH 06/75] Parameters names where camelized with first letter not lower --- .../swagger/codegen/languages/AkkaScalaClientCodegen.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java index ee2da7aa921..fff8deb99f4 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AkkaScalaClientCodegen.java @@ -230,7 +230,7 @@ public class AkkaScalaClientCodegen extends DefaultCodegen implements CodegenCon } private String formatIdentifier(String name, boolean capitalized) { - String identifier = camelize(name); + String identifier = camelize(name, true); if (capitalized) identifier = StringUtils.capitalize(identifier); if (identifier.matches("[a-zA-Z_$][\\w_$]+") && !reservedWords.contains(identifier)) From 65b6d210bc81a1e0a68a63bd2f6415580c400f73 Mon Sep 17 00:00:00 2001 From: Camille Chafer Date: Thu, 2 Apr 2015 18:02:21 +0200 Subject: [PATCH 07/75] Examples updated with names lower-camelized --- .../scala/io/swagger/client/api/PetApi.scala | 68 +++--- .../io/swagger/client/api/StoreApi.scala | 18 +- .../scala/io/swagger/client/api/UserApi.scala | 50 ++--- .../io/swagger/client/model/Category.scala | 4 +- .../scala/io/swagger/client/model/Order.scala | 12 +- .../scala/io/swagger/client/model/Pet.scala | 12 +- .../scala/io/swagger/client/model/Tag.scala | 4 +- .../scala/io/swagger/client/model/User.scala | 16 +- .../io/swagger/client/api/AccountApi.scala | 46 ++-- .../scala/io/swagger/client/api/WordApi.scala | 194 ++++++++-------- .../io/swagger/client/api/WordListApi.scala | 88 ++++---- .../io/swagger/client/api/WordListsApi.scala | 10 +- .../io/swagger/client/api/WordsApi.scala | 210 +++++++++--------- .../swagger/client/model/ApiTokenStatus.scala | 12 +- .../io/swagger/client/model/AudioFile.scala | 28 +-- .../io/swagger/client/model/AudioType.scala | 4 +- .../client/model/AuthenticationToken.scala | 6 +- .../io/swagger/client/model/Bigram.scala | 10 +- .../io/swagger/client/model/Category.scala | 4 +- .../io/swagger/client/model/Citation.scala | 4 +- .../client/model/ContentProvider.scala | 4 +- .../io/swagger/client/model/Definition.scala | 32 +-- .../model/DefinitionSearchResults.scala | 4 +- .../io/swagger/client/model/Example.scala | 24 +- .../client/model/ExampleSearchResults.scala | 4 +- .../swagger/client/model/ExampleUsage.scala | 2 +- .../scala/io/swagger/client/model/Facet.scala | 4 +- .../io/swagger/client/model/FacetValue.scala | 4 +- .../io/swagger/client/model/Frequency.scala | 4 +- .../client/model/FrequencySummary.scala | 10 +- .../scala/io/swagger/client/model/Label.scala | 4 +- .../scala/io/swagger/client/model/Note.scala | 8 +- .../swagger/client/model/PartOfSpeech.scala | 6 +- .../io/swagger/client/model/Related.scala | 14 +- .../scala/io/swagger/client/model/Root.scala | 6 +- .../io/swagger/client/model/ScoredWord.scala | 22 +- .../io/swagger/client/model/Sentence.scala | 12 +- .../client/model/SimpleDefinition.scala | 8 +- .../swagger/client/model/SimpleExample.scala | 8 +- .../io/swagger/client/model/StringValue.scala | 2 +- .../io/swagger/client/model/Syllable.scala | 6 +- .../io/swagger/client/model/TextPron.scala | 6 +- .../scala/io/swagger/client/model/User.scala | 16 +- .../io/swagger/client/model/WordList.scala | 22 +- .../swagger/client/model/WordListWord.scala | 14 +- .../io/swagger/client/model/WordObject.scala | 12 +- .../swagger/client/model/WordOfTheDay.scala | 24 +- .../client/model/WordSearchResult.scala | 6 +- .../client/model/WordSearchResults.scala | 4 +- 49 files changed, 546 insertions(+), 546 deletions(-) diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala index abb8054e753..d5ae6fd65f0 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -15,11 +15,11 @@ object PetApi { * code 404 : (Pet not found) * code 400 : (Invalid ID supplied) * - * @param Body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store */ - def updatePet(Body: Option[Pet] = None): ApiRequest[Unit] = + def updatePet(body: Option[Pet] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/pet", "application/json") - .withBody(Body) + .withBody(body) .withErrorResponse[Unit](405) .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) @@ -29,11 +29,11 @@ object PetApi { * Expected answers: * code 405 : (Invalid input) * - * @param Body Pet object that needs to be added to the store + * @param body Pet object that needs to be added to the store */ - def addPet(Body: Option[Pet] = None): ApiRequest[Unit] = + def addPet(body: Option[Pet] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet", "application/json") - .withBody(Body) + .withBody(body) .withErrorResponse[Unit](405) /** @@ -43,11 +43,11 @@ object PetApi { * code 200 : Seq[Pet] (successful operation) * code 400 : (Invalid status value) * - * @param Status Status values that need to be considered for filter + * @param status Status values that need to be considered for filter */ - def findPetsByStatus(Status: Seq[String]): ApiRequest[Seq[Pet]] = + def findPetsByStatus(status: Seq[String]): ApiRequest[Seq[Pet]] = ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByStatus", "application/json") - .withQueryParam("status", ArrayValues(Status, MULTI)) + .withQueryParam("status", ArrayValues(status, MULTI)) .withSuccessResponse[Seq[Pet]](200) .withErrorResponse[Unit](400) @@ -58,11 +58,11 @@ object PetApi { * code 200 : Seq[Pet] (successful operation) * code 400 : (Invalid tag value) * - * @param Tags Tags to filter by + * @param tags Tags to filter by */ - def findPetsByTags(Tags: Seq[String]): ApiRequest[Seq[Pet]] = + def findPetsByTags(tags: Seq[String]): ApiRequest[Seq[Pet]] = ApiRequest[Seq[Pet]](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/findByTags", "application/json") - .withQueryParam("tags", ArrayValues(Tags, MULTI)) + .withQueryParam("tags", ArrayValues(tags, MULTI)) .withSuccessResponse[Seq[Pet]](200) .withErrorResponse[Unit](400) @@ -77,12 +77,12 @@ object PetApi { * Available security schemes: * api_key (apiKey) * - * @param PetId ID of pet that needs to be fetched + * @param petId ID of pet that needs to be fetched */ - def getPetById(PetId: Long)(implicit apiKey: ApiKeyValue): ApiRequest[Pet] = + def getPetById(petId: Long)(implicit apiKey: ApiKeyValue): ApiRequest[Pet] = ApiRequest[Pet](ApiMethods.GET, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") .withApiKey(apiKey, "api_key", HEADER) - .withPathParam("petId", PetId) + .withPathParam("petId", petId) .withErrorResponse[Unit](404) .withSuccessResponse[Pet](200) .withErrorResponse[Unit](400) @@ -92,15 +92,15 @@ object PetApi { * Expected answers: * code 405 : (Invalid input) * - * @param PetId ID of pet that needs to be updated - * @param Name Updated name of the pet - * @param Status Updated status of the pet + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet */ - def updatePetWithForm(PetId: String, Name: Option[String] = None, Status: Option[String] = None): ApiRequest[Unit] = + def updatePetWithForm(petId: String, name: Option[String] = None, status: Option[String] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/x-www-form-urlencoded") - .withFormParam("name", Name) - .withFormParam("status", Status) - .withPathParam("petId", PetId) + .withFormParam("name", name) + .withFormParam("status", status) + .withPathParam("petId", petId) .withErrorResponse[Unit](405) /** @@ -108,13 +108,13 @@ object PetApi { * Expected answers: * code 400 : (Invalid pet value) * - * @param ApiKey - * @param PetId Pet id to delete + * @param apiKey + * @param petId Pet id to delete */ - def deletePet(ApiKey: Option[String] = None, PetId: Long): ApiRequest[Unit] = + def deletePet(apiKey: Option[String] = None, petId: Long): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/pet/{petId}", "application/json") - .withPathParam("petId", PetId) - .withHeaderParam("api_key", ApiKey) + .withPathParam("petId", petId) + .withHeaderParam("api_key", apiKey) .withErrorResponse[Unit](400) /** @@ -122,15 +122,15 @@ object PetApi { * Expected answers: * code 0 : (successful operation) * - * @param PetId ID of pet to update - * @param AdditionalMetadata Additional data to pass to server - * @param File file to upload + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload */ - def uploadFile(PetId: Long, AdditionalMetadata: Option[String] = None, File: Option[File] = None): ApiRequest[Unit] = + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/pet/{petId}/uploadImage", "multipart/form-data") - .withFormParam("additionalMetadata", AdditionalMetadata) - .withFormParam("file", File) - .withPathParam("petId", PetId) + .withFormParam("additionalMetadata", additionalMetadata) + .withFormParam("file", file) + .withPathParam("petId", petId) .withDefaultSuccessResponse[Unit] diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala index a1391954a7d..686e85e105d 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/StoreApi.scala @@ -27,11 +27,11 @@ object StoreApi { * code 200 : Order (successful operation) * code 400 : (Invalid Order) * - * @param Body order placed for purchasing the pet + * @param body order placed for purchasing the pet */ - def placeOrder(Body: Option[Order] = None): ApiRequest[Order] = + def placeOrder(body: Option[Order] = None): ApiRequest[Order] = ApiRequest[Order](ApiMethods.POST, "http://petstore.swagger.io/v2", "/store/order", "application/json") - .withBody(Body) + .withBody(body) .withSuccessResponse[Order](200) .withErrorResponse[Unit](400) @@ -43,11 +43,11 @@ object StoreApi { * code 200 : Order (successful operation) * code 400 : (Invalid ID supplied) * - * @param OrderId ID of pet that needs to be fetched + * @param orderId ID of pet that needs to be fetched */ - def getOrderById(OrderId: String): ApiRequest[Order] = + def getOrderById(orderId: String): ApiRequest[Order] = ApiRequest[Order](ApiMethods.GET, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") - .withPathParam("orderId", OrderId) + .withPathParam("orderId", orderId) .withErrorResponse[Unit](404) .withSuccessResponse[Order](200) .withErrorResponse[Unit](400) @@ -59,11 +59,11 @@ object StoreApi { * code 404 : (Order not found) * code 400 : (Invalid ID supplied) * - * @param OrderId ID of the order that needs to be deleted + * @param orderId ID of the order that needs to be deleted */ - def deleteOrder(OrderId: String): ApiRequest[Unit] = + def deleteOrder(orderId: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/store/order/{orderId}", "application/json") - .withPathParam("orderId", OrderId) + .withPathParam("orderId", orderId) .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala index 9fb026d950d..4c2ab10e9e7 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/api/UserApi.scala @@ -13,11 +13,11 @@ object UserApi { * Expected answers: * code 0 : (successful operation) * - * @param Body Created user object + * @param body Created user object */ - def createUser(Body: Option[User] = None): ApiRequest[Unit] = + def createUser(body: Option[User] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user", "application/json") - .withBody(Body) + .withBody(body) .withDefaultSuccessResponse[Unit] /** @@ -25,11 +25,11 @@ object UserApi { * Expected answers: * code 0 : (successful operation) * - * @param Body List of user object + * @param body List of user object */ - def createUsersWithArrayInput(Body: Seq[User]): ApiRequest[Unit] = + def createUsersWithArrayInput(body: Seq[User]): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithArray", "application/json") - .withBody(Body) + .withBody(body) .withDefaultSuccessResponse[Unit] /** @@ -37,11 +37,11 @@ object UserApi { * Expected answers: * code 0 : (successful operation) * - * @param Body List of user object + * @param body List of user object */ - def createUsersWithListInput(Body: Seq[User]): ApiRequest[Unit] = + def createUsersWithListInput(body: Seq[User]): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "http://petstore.swagger.io/v2", "/user/createWithList", "application/json") - .withBody(Body) + .withBody(body) .withDefaultSuccessResponse[Unit] /** @@ -50,13 +50,13 @@ object UserApi { * code 200 : String (successful operation) * code 400 : (Invalid username/password supplied) * - * @param Username The user name for login - * @param Password The password for login in clear text + * @param username The user name for login + * @param password The password for login in clear text */ - def loginUser(Username: Option[String] = None, Password: Option[String] = None): ApiRequest[String] = + def loginUser(username: Option[String] = None, password: Option[String] = None): ApiRequest[String] = ApiRequest[String](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/login", "application/json") - .withQueryParam("username", Username) - .withQueryParam("password", Password) + .withQueryParam("username", username) + .withQueryParam("password", password) .withSuccessResponse[String](200) .withErrorResponse[Unit](400) @@ -76,11 +76,11 @@ object UserApi { * code 200 : User (successful operation) * code 400 : (Invalid username supplied) * - * @param Username The name that needs to be fetched. Use user1 for testing. + * @param username The name that needs to be fetched. Use user1 for testing. */ - def getUserByName(Username: String): ApiRequest[User] = + def getUserByName(username: String): ApiRequest[User] = ApiRequest[User](ApiMethods.GET, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") - .withPathParam("username", Username) + .withPathParam("username", username) .withErrorResponse[Unit](404) .withSuccessResponse[User](200) .withErrorResponse[Unit](400) @@ -92,13 +92,13 @@ object UserApi { * code 404 : (User not found) * code 400 : (Invalid user supplied) * - * @param Username name that need to be deleted - * @param Body Updated user object + * @param username name that need to be deleted + * @param body Updated user object */ - def updateUser(Username: String, Body: Option[User] = None): ApiRequest[Unit] = + def updateUser(username: String, body: Option[User] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.PUT, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") - .withBody(Body) - .withPathParam("username", Username) + .withBody(body) + .withPathParam("username", username) .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) @@ -109,11 +109,11 @@ object UserApi { * code 404 : (User not found) * code 400 : (Invalid username supplied) * - * @param Username The name that needs to be deleted + * @param username The name that needs to be deleted */ - def deleteUser(Username: String): ApiRequest[Unit] = + def deleteUser(username: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "http://petstore.swagger.io/v2", "/user/{username}", "application/json") - .withPathParam("username", Username) + .withPathParam("username", username) .withErrorResponse[Unit](404) .withErrorResponse[Unit](400) diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala index 5eec9d159de..af66bc14753 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Category ( - Id: Option[Long], - Name: Option[String]) + id: Option[Long], + name: Option[String]) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala index 5fe2c3d0a67..83a40fb55d3 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Order.scala @@ -5,13 +5,13 @@ import org.joda.time.DateTime case class Order ( - Id: Option[Long], - PetId: Option[Long], - Quantity: Option[Int], - ShipDate: Option[DateTime], + id: Option[Long], + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[DateTime], /* Order Status */ - Status: Option[OrderEnums.Status], - Complete: Option[Boolean]) + status: Option[OrderEnums.Status], + complete: Option[Boolean]) extends ApiModel object OrderEnums { diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala index 5007c7d9585..8cd3c61cb60 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Pet.scala @@ -5,13 +5,13 @@ import org.joda.time.DateTime case class Pet ( - Id: Option[Long], - Category: Option[Category], - Name: String, - PhotoUrls: Seq[String], - Tags: Option[Seq[Tag]], + id: Option[Long], + category: Option[Category], + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]], /* pet status in the store */ - Status: Option[PetEnums.Status]) + status: Option[PetEnums.Status]) extends ApiModel object PetEnums { diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala index 8f7c3f2aa4a..58aabadabe0 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/Tag.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Tag ( - Id: Option[Long], - Name: Option[String]) + id: Option[Long], + name: Option[String]) extends ApiModel diff --git a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala index c9772f5361e..dd0bce1d8a7 100644 --- a/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/petstore/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -5,15 +5,15 @@ import org.joda.time.DateTime case class User ( - Id: Option[Long], - Username: Option[String], - FirstName: Option[String], - LastName: Option[String], - Email: Option[String], - Password: Option[String], - Phone: Option[String], + id: Option[Long], + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], /* User Status */ - UserStatus: Option[Int]) + userStatus: Option[Int]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala index 920159a629f..8168c1c0f4f 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/AccountApi.scala @@ -18,11 +18,11 @@ object AccountApi { * code 400 : (No token supplied.) * code 404 : (No API account with supplied token.) * - * @param ApiKey Wordnik authentication token + * @param apiKey Wordnik authentication token */ - def getApiTokenStatus(ApiKey: Option[String] = None): ApiRequest[ApiTokenStatus] = + def getApiTokenStatus(apiKey: Option[String] = None): ApiRequest[ApiTokenStatus] = ApiRequest[ApiTokenStatus](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/apiTokenStatus", "application/json") - .withHeaderParam("api_key", ApiKey) + .withHeaderParam("api_key", apiKey) .withSuccessResponse[ApiTokenStatus](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](404) @@ -35,13 +35,13 @@ object AccountApi { * code 403 : (Account not available.) * code 404 : (User not found.) * - * @param Username A confirmed Wordnik username - * @param Password The user's password + * @param username A confirmed Wordnik username + * @param password The user's password */ - def authenticate(Username: String, Password: String): ApiRequest[AuthenticationToken] = + def authenticate(username: String, password: String): ApiRequest[AuthenticationToken] = ApiRequest[AuthenticationToken](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json") - .withQueryParam("password", Password) - .withPathParam("username", Username) + .withQueryParam("password", password) + .withPathParam("username", username) .withSuccessResponse[AuthenticationToken](200) .withErrorResponse[Unit](403) .withErrorResponse[Unit](404) @@ -54,13 +54,13 @@ object AccountApi { * code 403 : (Account not available.) * code 404 : (User not found.) * - * @param Username A confirmed Wordnik username - * @param Body The user's password + * @param username A confirmed Wordnik username + * @param body The user's password */ - def authenticatePost(Username: String, Body: String): ApiRequest[AuthenticationToken] = + def authenticatePost(username: String, body: String): ApiRequest[AuthenticationToken] = ApiRequest[AuthenticationToken](ApiMethods.POST, "https://api.wordnik.com/v4", "/account.json/authenticate/{username}", "application/json") - .withBody(Body) - .withPathParam("username", Username) + .withBody(body) + .withPathParam("username", username) .withSuccessResponse[AuthenticationToken](200) .withErrorResponse[Unit](403) .withErrorResponse[Unit](404) @@ -73,11 +73,11 @@ object AccountApi { * code 403 : (Not logged in.) * code 404 : (User not found.) * - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def getLoggedInUser(AuthToken: String): ApiRequest[User] = + def getLoggedInUser(authToken: String): ApiRequest[User] = ApiRequest[User](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/user", "application/json") - .withHeaderParam("auth_token", AuthToken) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[User](200) .withErrorResponse[Unit](403) .withErrorResponse[Unit](404) @@ -90,15 +90,15 @@ object AccountApi { * code 403 : (Not authenticated.) * code 404 : (User account not found.) * - * @param AuthToken auth_token of logged-in user - * @param Skip Results to skip - * @param Limit Maximum number of results to return + * @param authToken auth_token of logged-in user + * @param skip Results to skip + * @param limit Maximum number of results to return */ - def getWordListsForLoggedInUser(AuthToken: String, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[Seq[WordList]] = + def getWordListsForLoggedInUser(authToken: String, skip: Option[Int] = None, limit: Option[Int] = None): ApiRequest[Seq[WordList]] = ApiRequest[Seq[WordList]](ApiMethods.GET, "https://api.wordnik.com/v4", "/account.json/wordLists", "application/json") - .withQueryParam("skip", Skip) - .withQueryParam("limit", Limit) - .withHeaderParam("auth_token", AuthToken) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[Seq[WordList]](200) .withErrorResponse[Unit](403) .withErrorResponse[Unit](404) diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala index 36d706c4f40..3c85b1a857f 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordApi.scala @@ -19,15 +19,15 @@ object WordApi { * code 200 : WordObject (success) * code 400 : (Invalid word supplied.) * - * @param Word String value of WordObject to return - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param IncludeSuggestions Return suggestions (for correct spelling, case variants, etc.) + * @param word String value of WordObject to return + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param includeSuggestions Return suggestions (for correct spelling, case variants, etc.) */ - def getWord(Word: String, UseCanonical: Option[String] = None, IncludeSuggestions: Option[String] = None): ApiRequest[WordObject] = + def getWord(word: String, useCanonical: Option[String] = None, includeSuggestions: Option[String] = None): ApiRequest[WordObject] = ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("includeSuggestions", IncludeSuggestions) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("includeSuggestions", includeSuggestions) + .withPathParam("word", word) .withSuccessResponse[WordObject](200) .withErrorResponse[Unit](400) @@ -38,15 +38,15 @@ object WordApi { * code 200 : Seq[AudioFile] (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to get audio for. - * @param UseCanonical Use the canonical form of the word - * @param Limit Maximum number of results to return + * @param word Word to get audio for. + * @param useCanonical Use the canonical form of the word + * @param limit Maximum number of results to return */ - def getAudio(Word: String, UseCanonical: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Seq[AudioFile]] = + def getAudio(word: String, useCanonical: Option[String] = None, limit: Option[Int] = None): ApiRequest[Seq[AudioFile]] = ApiRequest[Seq[AudioFile]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/audio", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("limit", Limit) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("limit", limit) + .withPathParam("word", word) .withSuccessResponse[Seq[AudioFile]](200) .withErrorResponse[Unit](400) @@ -58,23 +58,23 @@ object WordApi { * code 400 : (Invalid word supplied.) * code 404 : (No definitions found.) * - * @param Word Word to return definitions for - * @param Limit Maximum number of results to return - * @param PartOfSpeech CSV list of part-of-speech types - * @param IncludeRelated Return related words with definitions - * @param SourceDictionaries Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param IncludeTags Return a closed set of XML tags in response + * @param word Word to return definitions for + * @param limit Maximum number of results to return + * @param partOfSpeech CSV list of part-of-speech types + * @param includeRelated Return related words with definitions + * @param sourceDictionaries Source dictionary to return definitions from. If 'all' is received, results are returned from all sources. If multiple values are received (e.g. 'century,wiktionary'), results are returned from the first specified dictionary that has definitions. If left blank, results are returned from the first dictionary that has definitions. By default, dictionaries are searched in this order: ahd, wiktionary, webster, century, wordnet + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param includeTags Return a closed set of XML tags in response */ - def getDefinitions(Word: String, Limit: Option[Int] = None, PartOfSpeech: Option[String] = None, IncludeRelated: Option[String] = None, SourceDictionaries: Seq[String], UseCanonical: Option[String] = None, IncludeTags: Option[String] = None): ApiRequest[Seq[Definition]] = + def getDefinitions(word: String, limit: Option[Int] = None, partOfSpeech: Option[String] = None, includeRelated: Option[String] = None, sourceDictionaries: Seq[String], useCanonical: Option[String] = None, includeTags: Option[String] = None): ApiRequest[Seq[Definition]] = ApiRequest[Seq[Definition]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/definitions", "application/json") - .withQueryParam("limit", Limit) - .withQueryParam("partOfSpeech", PartOfSpeech) - .withQueryParam("includeRelated", IncludeRelated) - .withQueryParam("sourceDictionaries", ArrayValues(SourceDictionaries, CSV)) - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("includeTags", IncludeTags) - .withPathParam("word", Word) + .withQueryParam("limit", limit) + .withQueryParam("partOfSpeech", partOfSpeech) + .withQueryParam("includeRelated", includeRelated) + .withQueryParam("sourceDictionaries", ArrayValues(sourceDictionaries, CSV)) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("includeTags", includeTags) + .withPathParam("word", word) .withSuccessResponse[Seq[Definition]](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](404) @@ -87,13 +87,13 @@ object WordApi { * code 400 : (Invalid word supplied.) * code 404 : (No definitions found.) * - * @param Word Word to return - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param word Word to return + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. */ - def getEtymologies(Word: String, UseCanonical: Option[String] = None): ApiRequest[Seq[String]] = + def getEtymologies(word: String, useCanonical: Option[String] = None): ApiRequest[Seq[String]] = ApiRequest[Seq[String]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/etymologies", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withPathParam("word", word) .withSuccessResponse[Seq[String]](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](404) @@ -105,19 +105,19 @@ object WordApi { * code 200 : (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to return examples for - * @param IncludeDuplicates Show duplicate examples from different sources - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param Skip Results to skip - * @param Limit Maximum number of results to return + * @param word Word to return examples for + * @param includeDuplicates Show duplicate examples from different sources + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param skip Results to skip + * @param limit Maximum number of results to return */ - def getExamples(Word: String, IncludeDuplicates: Option[String] = None, UseCanonical: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + def getExamples(word: String, includeDuplicates: Option[String] = None, useCanonical: Option[String] = None, skip: Option[Int] = None, limit: Option[Int] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/examples", "application/json") - .withQueryParam("includeDuplicates", IncludeDuplicates) - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("skip", Skip) - .withQueryParam("limit", Limit) - .withPathParam("word", Word) + .withQueryParam("includeDuplicates", includeDuplicates) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withPathParam("word", word) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) @@ -129,17 +129,17 @@ object WordApi { * code 400 : (Invalid word supplied.) * code 404 : (No results.) * - * @param Word Word to return - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param StartYear Starting Year - * @param EndYear Ending Year + * @param word Word to return + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param startYear Starting Year + * @param endYear Ending Year */ - def getWordFrequency(Word: String, UseCanonical: Option[String] = None, StartYear: Option[Int] = None, EndYear: Option[Int] = None): ApiRequest[FrequencySummary] = + def getWordFrequency(word: String, useCanonical: Option[String] = None, startYear: Option[Int] = None, endYear: Option[Int] = None): ApiRequest[FrequencySummary] = ApiRequest[FrequencySummary](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/frequency", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("startYear", StartYear) - .withQueryParam("endYear", EndYear) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("startYear", startYear) + .withQueryParam("endYear", endYear) + .withPathParam("word", word) .withSuccessResponse[FrequencySummary](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](404) @@ -151,17 +151,17 @@ object WordApi { * code 200 : (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to get syllables for - * @param UseCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param SourceDictionary Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. - * @param Limit Maximum number of results to return + * @param word Word to get syllables for + * @param useCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param sourceDictionary Get from a single dictionary. Valid options: ahd, century, wiktionary, webster, and wordnet. + * @param limit Maximum number of results to return */ - def getHyphenation(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + def getHyphenation(word: String, useCanonical: Option[String] = None, sourceDictionary: Option[String] = None, limit: Option[Int] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/hyphenation", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("sourceDictionary", SourceDictionary) - .withQueryParam("limit", Limit) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("sourceDictionary", sourceDictionary) + .withQueryParam("limit", limit) + .withPathParam("word", word) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) @@ -172,17 +172,17 @@ object WordApi { * code 200 : Seq[Bigram] (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to fetch phrases for - * @param Limit Maximum number of results to return - * @param Wlmi Minimum WLMI for the phrase - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param word Word to fetch phrases for + * @param limit Maximum number of results to return + * @param wlmi Minimum WLMI for the phrase + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. */ - def getPhrases(Word: String, Limit: Option[Int] = None, Wlmi: Option[Int] = None, UseCanonical: Option[String] = None): ApiRequest[Seq[Bigram]] = + def getPhrases(word: String, limit: Option[Int] = None, wlmi: Option[Int] = None, useCanonical: Option[String] = None): ApiRequest[Seq[Bigram]] = ApiRequest[Seq[Bigram]](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/phrases", "application/json") - .withQueryParam("limit", Limit) - .withQueryParam("wlmi", Wlmi) - .withQueryParam("useCanonical", UseCanonical) - .withPathParam("word", Word) + .withQueryParam("limit", limit) + .withQueryParam("wlmi", wlmi) + .withQueryParam("useCanonical", useCanonical) + .withPathParam("word", word) .withSuccessResponse[Seq[Bigram]](200) .withErrorResponse[Unit](400) @@ -193,19 +193,19 @@ object WordApi { * code 200 : (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to get pronunciations for - * @param UseCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param SourceDictionary Get from a single dictionary - * @param TypeFormat Text pronunciation type - * @param Limit Maximum number of results to return + * @param word Word to get pronunciations for + * @param useCanonical If true will try to return a correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param sourceDictionary Get from a single dictionary + * @param typeFormat Text pronunciation type + * @param limit Maximum number of results to return */ - def getTextPronunciations(Word: String, UseCanonical: Option[String] = None, SourceDictionary: Option[String] = None, TypeFormat: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + def getTextPronunciations(word: String, useCanonical: Option[String] = None, sourceDictionary: Option[String] = None, typeFormat: Option[String] = None, limit: Option[Int] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/pronunciations", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("sourceDictionary", SourceDictionary) - .withQueryParam("typeFormat", TypeFormat) - .withQueryParam("limit", Limit) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("sourceDictionary", sourceDictionary) + .withQueryParam("typeFormat", typeFormat) + .withQueryParam("limit", limit) + .withPathParam("word", word) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) @@ -216,17 +216,17 @@ object WordApi { * code 200 : (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to fetch relationships for - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. - * @param RelationshipTypes Limits the total results per type of relationship type - * @param LimitPerRelationshipType Restrict to the supplied relationship types + * @param word Word to fetch relationships for + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param relationshipTypes Limits the total results per type of relationship type + * @param limitPerRelationshipType Restrict to the supplied relationship types */ - def getRelatedWords(Word: String, UseCanonical: Option[String] = None, RelationshipTypes: Option[String] = None, LimitPerRelationshipType: Option[Int] = None): ApiRequest[Unit] = + def getRelatedWords(word: String, useCanonical: Option[String] = None, relationshipTypes: Option[String] = None, limitPerRelationshipType: Option[Int] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/relatedWords", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withQueryParam("relationshipTypes", RelationshipTypes) - .withQueryParam("limitPerRelationshipType", LimitPerRelationshipType) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withQueryParam("relationshipTypes", relationshipTypes) + .withQueryParam("limitPerRelationshipType", limitPerRelationshipType) + .withPathParam("word", word) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) @@ -237,13 +237,13 @@ object WordApi { * code 200 : Example (success) * code 400 : (Invalid word supplied.) * - * @param Word Word to fetch examples for - * @param UseCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. + * @param word Word to fetch examples for + * @param useCanonical If true will try to return the correct word root ('cats' -> 'cat'). If false returns exactly what was requested. */ - def getTopExample(Word: String, UseCanonical: Option[String] = None): ApiRequest[Example] = + def getTopExample(word: String, useCanonical: Option[String] = None): ApiRequest[Example] = ApiRequest[Example](ApiMethods.GET, "https://api.wordnik.com/v4", "/word.json/{word}/topExample", "application/json") - .withQueryParam("useCanonical", UseCanonical) - .withPathParam("word", Word) + .withQueryParam("useCanonical", useCanonical) + .withPathParam("word", word) .withSuccessResponse[Example](200) .withErrorResponse[Unit](400) diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala index 54883fa07bd..6ff76587e1a 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListApi.scala @@ -17,13 +17,13 @@ object WordListApi { * code 403 : (Not Authorized to access WordList) * code 404 : (WordList not found) * - * @param Permalink permalink of WordList to fetch - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param permalink permalink of WordList to fetch + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def getWordListByPermalink(Permalink: String, AuthToken: String): ApiRequest[WordList] = + def getWordListByPermalink(permalink: String, authToken: String): ApiRequest[WordList] = ApiRequest[WordList](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") - .withPathParam("permalink", Permalink) - .withHeaderParam("auth_token", AuthToken) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[WordList](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) @@ -38,15 +38,15 @@ object WordListApi { * code 403 : (Not Authorized to update WordList) * code 404 : (WordList not found) * - * @param Permalink permalink of WordList to update - * @param Body Updated WordList - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param permalink permalink of WordList to update + * @param body Updated WordList + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def updateWordList(Permalink: String, Body: Option[WordList] = None, AuthToken: String): ApiRequest[Unit] = + def updateWordList(permalink: String, body: Option[WordList] = None, authToken: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.PUT, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") - .withBody(Body) - .withPathParam("permalink", Permalink) - .withHeaderParam("auth_token", AuthToken) + .withBody(body) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) @@ -61,13 +61,13 @@ object WordListApi { * code 403 : (Not Authorized to delete WordList) * code 404 : (WordList not found) * - * @param Permalink ID of WordList to delete - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param permalink ID of WordList to delete + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def deleteWordList(Permalink: String, AuthToken: String): ApiRequest[Unit] = + def deleteWordList(permalink: String, authToken: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.DELETE, "https://api.wordnik.com/v4", "/wordList.json/{permalink}", "application/json") - .withPathParam("permalink", Permalink) - .withHeaderParam("auth_token", AuthToken) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) @@ -82,15 +82,15 @@ object WordListApi { * code 403 : (Not Authorized to modify WordList) * code 404 : (WordList not found) * - * @param Permalink permalink of WordList to use - * @param Body Words to remove from WordList - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param permalink permalink of WordList to use + * @param body Words to remove from WordList + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def deleteWordsFromWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[Unit] = + def deleteWordsFromWordList(permalink: String, body: Seq[StringValue], authToken: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/deleteWords", "application/json") - .withBody(Body) - .withPathParam("permalink", Permalink) - .withHeaderParam("auth_token", AuthToken) + .withBody(body) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) @@ -105,21 +105,21 @@ object WordListApi { * code 403 : (Not Authorized to access WordList) * code 404 : (WordList not found) * - * @param Permalink ID of WordList to use - * @param SortBy Field to sort by - * @param SortOrder Direction to sort - * @param Skip Results to skip - * @param Limit Maximum number of results to return - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param permalink ID of WordList to use + * @param sortBy Field to sort by + * @param sortOrder Direction to sort + * @param skip Results to skip + * @param limit Maximum number of results to return + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def getWordListWords(Permalink: String, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[Int] = None, Limit: Option[Int] = None, AuthToken: String): ApiRequest[Unit] = + def getWordListWords(permalink: String, sortBy: Option[String] = None, sortOrder: Option[String] = None, skip: Option[Int] = None, limit: Option[Int] = None, authToken: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") - .withQueryParam("sortBy", SortBy) - .withQueryParam("sortOrder", SortOrder) - .withQueryParam("skip", Skip) - .withQueryParam("limit", Limit) - .withPathParam("permalink", Permalink) - .withHeaderParam("auth_token", AuthToken) + .withQueryParam("sortBy", sortBy) + .withQueryParam("sortOrder", sortOrder) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) @@ -134,15 +134,15 @@ object WordListApi { * code 403 : (Not Authorized to access WordList) * code 404 : (WordList not found) * - * @param Permalink permalink of WordList to user - * @param Body Array of words to add to WordList - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param permalink permalink of WordList to user + * @param body Array of words to add to WordList + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def addWordsToWordList(Permalink: String, Body: Seq[StringValue], AuthToken: String): ApiRequest[Unit] = + def addWordsToWordList(permalink: String, body: Seq[StringValue], authToken: String): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordList.json/{permalink}/words", "application/json") - .withBody(Body) - .withPathParam("permalink", Permalink) - .withHeaderParam("auth_token", AuthToken) + .withBody(body) + .withPathParam("permalink", permalink) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala index a2540c383a0..cad9a37ba87 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordListsApi.scala @@ -16,13 +16,13 @@ object WordListsApi { * code 403 : (Not authenticated) * code 404 : (WordList owner not found) * - * @param Body WordList to create - * @param AuthToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) + * @param body WordList to create + * @param authToken The auth token of the logged-in user, obtained by calling /account.json/authenticate/{username} (described above) */ - def createWordList(Body: Option[WordList] = None, AuthToken: String): ApiRequest[WordList] = + def createWordList(body: Option[WordList] = None, authToken: String): ApiRequest[WordList] = ApiRequest[WordList](ApiMethods.POST, "https://api.wordnik.com/v4", "/wordLists.json", "application/json") - .withBody(Body) - .withHeaderParam("auth_token", AuthToken) + .withBody(body) + .withHeaderParam("auth_token", authToken) .withSuccessResponse[WordList](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](403) diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala index 1a58a2f4139..b3b33679252 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/api/WordsApi.scala @@ -17,27 +17,27 @@ object WordsApi { * code 200 : WordObject (success) * code 404 : (No word found.) * - * @param HasDictionaryDef Only return words with dictionary definitions - * @param IncludePartOfSpeech CSV part-of-speech values to include - * @param ExcludePartOfSpeech CSV part-of-speech values to exclude - * @param MinCorpusCount Minimum corpus frequency for terms - * @param MaxCorpusCount Maximum corpus frequency for terms - * @param MinDictionaryCount Minimum dictionary count - * @param MaxDictionaryCount Maximum dictionary count - * @param MinLength Minimum word length - * @param MaxLength Maximum word length + * @param hasDictionaryDef Only return words with dictionary definitions + * @param includePartOfSpeech CSV part-of-speech values to include + * @param excludePartOfSpeech CSV part-of-speech values to exclude + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minDictionaryCount Minimum dictionary count + * @param maxDictionaryCount Maximum dictionary count + * @param minLength Minimum word length + * @param maxLength Maximum word length */ - def getRandomWord(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None): ApiRequest[WordObject] = + def getRandomWord(hasDictionaryDef: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minDictionaryCount: Option[Int] = None, maxDictionaryCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None): ApiRequest[WordObject] = ApiRequest[WordObject](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWord", "application/json") - .withQueryParam("hasDictionaryDef", HasDictionaryDef) - .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) - .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) - .withQueryParam("minCorpusCount", MinCorpusCount) - .withQueryParam("maxCorpusCount", MaxCorpusCount) - .withQueryParam("minDictionaryCount", MinDictionaryCount) - .withQueryParam("maxDictionaryCount", MaxDictionaryCount) - .withQueryParam("minLength", MinLength) - .withQueryParam("maxLength", MaxLength) + .withQueryParam("hasDictionaryDef", hasDictionaryDef) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minDictionaryCount", minDictionaryCount) + .withQueryParam("maxDictionaryCount", maxDictionaryCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) .withSuccessResponse[WordObject](200) .withErrorResponse[Unit](404) @@ -49,33 +49,33 @@ object WordsApi { * code 400 : (Invalid term supplied.) * code 404 : (No results.) * - * @param HasDictionaryDef Only return words with dictionary definitions - * @param IncludePartOfSpeech CSV part-of-speech values to include - * @param ExcludePartOfSpeech CSV part-of-speech values to exclude - * @param MinCorpusCount Minimum corpus frequency for terms - * @param MaxCorpusCount Maximum corpus frequency for terms - * @param MinDictionaryCount Minimum dictionary count - * @param MaxDictionaryCount Maximum dictionary count - * @param MinLength Minimum word length - * @param MaxLength Maximum word length - * @param SortBy Attribute to sort by - * @param SortOrder Sort direction - * @param Limit Maximum number of results to return + * @param hasDictionaryDef Only return words with dictionary definitions + * @param includePartOfSpeech CSV part-of-speech values to include + * @param excludePartOfSpeech CSV part-of-speech values to exclude + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minDictionaryCount Minimum dictionary count + * @param maxDictionaryCount Maximum dictionary count + * @param minLength Minimum word length + * @param maxLength Maximum word length + * @param sortBy Attribute to sort by + * @param sortOrder Sort direction + * @param limit Maximum number of results to return */ - def getRandomWords(HasDictionaryDef: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Limit: Option[Int] = None): ApiRequest[Unit] = + def getRandomWords(hasDictionaryDef: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minDictionaryCount: Option[Int] = None, maxDictionaryCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, sortBy: Option[String] = None, sortOrder: Option[String] = None, limit: Option[Int] = None): ApiRequest[Unit] = ApiRequest[Unit](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/randomWords", "application/json") - .withQueryParam("hasDictionaryDef", HasDictionaryDef) - .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) - .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) - .withQueryParam("minCorpusCount", MinCorpusCount) - .withQueryParam("maxCorpusCount", MaxCorpusCount) - .withQueryParam("minDictionaryCount", MinDictionaryCount) - .withQueryParam("maxDictionaryCount", MaxDictionaryCount) - .withQueryParam("minLength", MinLength) - .withQueryParam("maxLength", MaxLength) - .withQueryParam("sortBy", SortBy) - .withQueryParam("sortOrder", SortOrder) - .withQueryParam("limit", Limit) + .withQueryParam("hasDictionaryDef", hasDictionaryDef) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minDictionaryCount", minDictionaryCount) + .withQueryParam("maxDictionaryCount", maxDictionaryCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withQueryParam("sortBy", sortBy) + .withQueryParam("sortOrder", sortOrder) + .withQueryParam("limit", limit) .withSuccessResponse[Unit](200) .withErrorResponse[Unit](400) .withErrorResponse[Unit](404) @@ -87,41 +87,41 @@ object WordsApi { * code 200 : DefinitionSearchResults (success) * code 400 : (Invalid term supplied.) * - * @param Query Search term - * @param FindSenseForWord Restricts words and finds closest sense - * @param IncludeSourceDictionaries Only include these comma-delimited source dictionaries - * @param ExcludeSourceDictionaries Exclude these comma-delimited source dictionaries - * @param IncludePartOfSpeech Only include these comma-delimited parts of speech - * @param ExcludePartOfSpeech Exclude these comma-delimited parts of speech - * @param MinCorpusCount Minimum corpus frequency for terms - * @param MaxCorpusCount Maximum corpus frequency for terms - * @param MinLength Minimum word length - * @param MaxLength Maximum word length - * @param ExpandTerms Expand terms - * @param IncludeTags Return a closed set of XML tags in response - * @param SortBy Attribute to sort by - * @param SortOrder Sort direction - * @param Skip Results to skip - * @param Limit Maximum number of results to return + * @param query Search term + * @param findSenseForWord Restricts words and finds closest sense + * @param includeSourceDictionaries Only include these comma-delimited source dictionaries + * @param excludeSourceDictionaries Exclude these comma-delimited source dictionaries + * @param includePartOfSpeech Only include these comma-delimited parts of speech + * @param excludePartOfSpeech Exclude these comma-delimited parts of speech + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minLength Minimum word length + * @param maxLength Maximum word length + * @param expandTerms Expand terms + * @param includeTags Return a closed set of XML tags in response + * @param sortBy Attribute to sort by + * @param sortOrder Sort direction + * @param skip Results to skip + * @param limit Maximum number of results to return */ - def reverseDictionary(Query: String, FindSenseForWord: Option[String] = None, IncludeSourceDictionaries: Option[String] = None, ExcludeSourceDictionaries: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, ExpandTerms: Option[String] = None, IncludeTags: Option[String] = None, SortBy: Option[String] = None, SortOrder: Option[String] = None, Skip: Option[String] = None, Limit: Option[Int] = None): ApiRequest[DefinitionSearchResults] = + def reverseDictionary(query: String, findSenseForWord: Option[String] = None, includeSourceDictionaries: Option[String] = None, excludeSourceDictionaries: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, expandTerms: Option[String] = None, includeTags: Option[String] = None, sortBy: Option[String] = None, sortOrder: Option[String] = None, skip: Option[String] = None, limit: Option[Int] = None): ApiRequest[DefinitionSearchResults] = ApiRequest[DefinitionSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/reverseDictionary", "application/json") - .withQueryParam("query", Query) - .withQueryParam("findSenseForWord", FindSenseForWord) - .withQueryParam("includeSourceDictionaries", IncludeSourceDictionaries) - .withQueryParam("excludeSourceDictionaries", ExcludeSourceDictionaries) - .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) - .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) - .withQueryParam("minCorpusCount", MinCorpusCount) - .withQueryParam("maxCorpusCount", MaxCorpusCount) - .withQueryParam("minLength", MinLength) - .withQueryParam("maxLength", MaxLength) - .withQueryParam("expandTerms", ExpandTerms) - .withQueryParam("includeTags", IncludeTags) - .withQueryParam("sortBy", SortBy) - .withQueryParam("sortOrder", SortOrder) - .withQueryParam("skip", Skip) - .withQueryParam("limit", Limit) + .withQueryParam("query", query) + .withQueryParam("findSenseForWord", findSenseForWord) + .withQueryParam("includeSourceDictionaries", includeSourceDictionaries) + .withQueryParam("excludeSourceDictionaries", excludeSourceDictionaries) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withQueryParam("expandTerms", expandTerms) + .withQueryParam("includeTags", includeTags) + .withQueryParam("sortBy", sortBy) + .withQueryParam("sortOrder", sortOrder) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) .withSuccessResponse[DefinitionSearchResults](200) .withErrorResponse[Unit](400) @@ -132,33 +132,33 @@ object WordsApi { * code 200 : WordSearchResults (success) * code 400 : (Invalid query supplied.) * - * @param Query Search query - * @param CaseSensitive Search case sensitive - * @param IncludePartOfSpeech Only include these comma-delimited parts of speech - * @param ExcludePartOfSpeech Exclude these comma-delimited parts of speech - * @param MinCorpusCount Minimum corpus frequency for terms - * @param MaxCorpusCount Maximum corpus frequency for terms - * @param MinDictionaryCount Minimum number of dictionary entries for words returned - * @param MaxDictionaryCount Maximum dictionary definition count - * @param MinLength Minimum word length - * @param MaxLength Maximum word length - * @param Skip Results to skip - * @param Limit Maximum number of results to return + * @param query Search query + * @param caseSensitive Search case sensitive + * @param includePartOfSpeech Only include these comma-delimited parts of speech + * @param excludePartOfSpeech Exclude these comma-delimited parts of speech + * @param minCorpusCount Minimum corpus frequency for terms + * @param maxCorpusCount Maximum corpus frequency for terms + * @param minDictionaryCount Minimum number of dictionary entries for words returned + * @param maxDictionaryCount Maximum dictionary definition count + * @param minLength Minimum word length + * @param maxLength Maximum word length + * @param skip Results to skip + * @param limit Maximum number of results to return */ - def searchWords(Query: String, CaseSensitive: Option[String] = None, IncludePartOfSpeech: Option[String] = None, ExcludePartOfSpeech: Option[String] = None, MinCorpusCount: Option[Int] = None, MaxCorpusCount: Option[Int] = None, MinDictionaryCount: Option[Int] = None, MaxDictionaryCount: Option[Int] = None, MinLength: Option[Int] = None, MaxLength: Option[Int] = None, Skip: Option[Int] = None, Limit: Option[Int] = None): ApiRequest[WordSearchResults] = + def searchWords(query: String, caseSensitive: Option[String] = None, includePartOfSpeech: Option[String] = None, excludePartOfSpeech: Option[String] = None, minCorpusCount: Option[Int] = None, maxCorpusCount: Option[Int] = None, minDictionaryCount: Option[Int] = None, maxDictionaryCount: Option[Int] = None, minLength: Option[Int] = None, maxLength: Option[Int] = None, skip: Option[Int] = None, limit: Option[Int] = None): ApiRequest[WordSearchResults] = ApiRequest[WordSearchResults](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/search/{query}", "application/json") - .withQueryParam("caseSensitive", CaseSensitive) - .withQueryParam("includePartOfSpeech", IncludePartOfSpeech) - .withQueryParam("excludePartOfSpeech", ExcludePartOfSpeech) - .withQueryParam("minCorpusCount", MinCorpusCount) - .withQueryParam("maxCorpusCount", MaxCorpusCount) - .withQueryParam("minDictionaryCount", MinDictionaryCount) - .withQueryParam("maxDictionaryCount", MaxDictionaryCount) - .withQueryParam("minLength", MinLength) - .withQueryParam("maxLength", MaxLength) - .withQueryParam("skip", Skip) - .withQueryParam("limit", Limit) - .withPathParam("query", Query) + .withQueryParam("caseSensitive", caseSensitive) + .withQueryParam("includePartOfSpeech", includePartOfSpeech) + .withQueryParam("excludePartOfSpeech", excludePartOfSpeech) + .withQueryParam("minCorpusCount", minCorpusCount) + .withQueryParam("maxCorpusCount", maxCorpusCount) + .withQueryParam("minDictionaryCount", minDictionaryCount) + .withQueryParam("maxDictionaryCount", maxDictionaryCount) + .withQueryParam("minLength", minLength) + .withQueryParam("maxLength", maxLength) + .withQueryParam("skip", skip) + .withQueryParam("limit", limit) + .withPathParam("query", query) .withSuccessResponse[WordSearchResults](200) .withErrorResponse[Unit](400) @@ -168,11 +168,11 @@ object WordsApi { * Expected answers: * code 0 : WordOfTheDay (success) * - * @param Date Fetches by date in yyyy-MM-dd + * @param date Fetches by date in yyyy-MM-dd */ - def getWordOfTheDay(Date: Option[String] = None): ApiRequest[WordOfTheDay] = + def getWordOfTheDay(date: Option[String] = None): ApiRequest[WordOfTheDay] = ApiRequest[WordOfTheDay](ApiMethods.GET, "https://api.wordnik.com/v4", "/words.json/wordOfTheDay", "application/json") - .withQueryParam("date", Date) + .withQueryParam("date", date) .withDefaultSuccessResponse[WordOfTheDay] diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala index 41a0615c0e4..0887fb0ba76 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala @@ -5,12 +5,12 @@ import org.joda.time.DateTime case class ApiTokenStatus ( - Valid: Option[Boolean], - Token: Option[String], - ResetsInMillis: Option[Long], - RemainingCalls: Option[Long], - ExpiresInMillis: Option[Long], - TotalRequests: Option[Long]) + valid: Option[Boolean], + token: Option[String], + resetsInMillis: Option[Long], + remainingCalls: Option[Long], + expiresInMillis: Option[Long], + totalRequests: Option[Long]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala index 6f3b759a2cb..3b3e9186b69 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioFile.scala @@ -5,20 +5,20 @@ import org.joda.time.DateTime case class AudioFile ( - AttributionUrl: Option[String], - CommentCount: Option[Int], - VoteCount: Option[Int], - FileUrl: Option[String], - AudioType: Option[String], - Id: Option[Long], - Duration: Option[Double], - AttributionText: Option[String], - CreatedBy: Option[String], - Description: Option[String], - CreatedAt: Option[DateTime], - VoteWeightedAverage: Option[Float], - VoteAverage: Option[Float], - Word: Option[String]) + attributionUrl: Option[String], + commentCount: Option[Int], + voteCount: Option[Int], + fileUrl: Option[String], + audioType: Option[String], + id: Option[Long], + duration: Option[Double], + attributionText: Option[String], + createdBy: Option[String], + description: Option[String], + createdAt: Option[DateTime], + voteWeightedAverage: Option[Float], + voteAverage: Option[Float], + word: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala index deda697e9e3..be7d0a1d5ef 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AudioType.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class AudioType ( - Id: Option[Int], - Name: Option[String]) + id: Option[Int], + name: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala index 169571959e3..981c7340d8e 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala @@ -5,9 +5,9 @@ import org.joda.time.DateTime case class AuthenticationToken ( - Token: Option[String], - UserId: Option[Long], - UserSignature: Option[String]) + token: Option[String], + userId: Option[Long], + userSignature: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala index 0559c35f7fa..c0a567c4ff9 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Bigram.scala @@ -5,11 +5,11 @@ import org.joda.time.DateTime case class Bigram ( - Count: Option[Long], - Gram2: Option[String], - Gram1: Option[String], - Wlmi: Option[Double], - Mi: Option[Double]) + count: Option[Long], + gram2: Option[String], + gram1: Option[String], + wlmi: Option[Double], + mi: Option[Double]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala index 5eec9d159de..af66bc14753 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Category.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Category ( - Id: Option[Long], - Name: Option[String]) + id: Option[Long], + name: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala index af025124060..16f75961500 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Citation.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Citation ( - Cite: Option[String], - Source: Option[String]) + cite: Option[String], + source: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala index be35406b63e..c7832871f7e 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ContentProvider.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class ContentProvider ( - Id: Option[Int], - Name: Option[String]) + id: Option[Int], + name: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala index 00b58932167..6274df1aa61 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Definition.scala @@ -5,22 +5,22 @@ import org.joda.time.DateTime case class Definition ( - ExtendedText: Option[String], - Text: Option[String], - SourceDictionary: Option[String], - Citations: Option[Seq[Citation]], - Labels: Option[Seq[Label]], - Score: Option[Float], - ExampleUses: Option[Seq[ExampleUsage]], - AttributionUrl: Option[String], - SeqString: Option[String], - AttributionText: Option[String], - RelatedWords: Option[Seq[Related]], - Sequence: Option[String], - Word: Option[String], - Notes: Option[Seq[Note]], - TextProns: Option[Seq[TextPron]], - PartOfSpeech: Option[String]) + extendedText: Option[String], + text: Option[String], + sourceDictionary: Option[String], + citations: Option[Seq[Citation]], + labels: Option[Seq[Label]], + score: Option[Float], + exampleUses: Option[Seq[ExampleUsage]], + attributionUrl: Option[String], + seqString: Option[String], + attributionText: Option[String], + relatedWords: Option[Seq[Related]], + sequence: Option[String], + word: Option[String], + notes: Option[Seq[Note]], + textProns: Option[Seq[TextPron]], + partOfSpeech: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala index a757637d42f..28d7d4e239b 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class DefinitionSearchResults ( - Results: Option[Seq[Definition]], - TotalResults: Option[Int]) + results: Option[Seq[Definition]], + totalResults: Option[Int]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala index 9604f2aa625..0d4d52aec98 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Example.scala @@ -5,18 +5,18 @@ import org.joda.time.DateTime case class Example ( - Id: Option[Long], - ExampleId: Option[Long], - Title: Option[String], - Text: Option[String], - Score: Option[ScoredWord], - Sentence: Option[Sentence], - Word: Option[String], - Provider: Option[ContentProvider], - Year: Option[Int], - Rating: Option[Float], - DocumentId: Option[Long], - Url: Option[String]) + id: Option[Long], + exampleId: Option[Long], + title: Option[String], + text: Option[String], + score: Option[ScoredWord], + sentence: Option[Sentence], + word: Option[String], + provider: Option[ContentProvider], + year: Option[Int], + rating: Option[Float], + documentId: Option[Long], + url: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala index 8ef6be3f172..bd4494666da 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class ExampleSearchResults ( - Facets: Option[Seq[Facet]], - Examples: Option[Seq[Example]]) + facets: Option[Seq[Facet]], + examples: Option[Seq[Example]]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala index 2e6fff5f975..377ee69f27a 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala @@ -5,7 +5,7 @@ import org.joda.time.DateTime case class ExampleUsage ( - Text: Option[String]) + text: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala index 4e113440c52..80d28578b78 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Facet.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Facet ( - FacetValues: Option[Seq[FacetValue]], - Name: Option[String]) + facetValues: Option[Seq[FacetValue]], + name: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala index 4d4d7294851..8a6f5d78cbb 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FacetValue.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class FacetValue ( - Count: Option[Long], - Value: Option[String]) + count: Option[Long], + value: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala index 595e001c6a7..58c29eb0b12 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Frequency.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Frequency ( - Count: Option[Long], - Year: Option[Int]) + count: Option[Long], + year: Option[Int]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala index 3f0ac1c0c53..3eacadbde71 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala @@ -5,11 +5,11 @@ import org.joda.time.DateTime case class FrequencySummary ( - UnknownYearCount: Option[Int], - TotalCount: Option[Long], - FrequencyString: Option[String], - Word: Option[String], - Frequency: Option[Seq[Frequency]]) + unknownYearCount: Option[Int], + totalCount: Option[Long], + frequencyString: Option[String], + word: Option[String], + frequency: Option[Seq[Frequency]]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala index 52b386526c2..5adba8e3276 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Label.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class Label ( - Text: Option[String], - Type: Option[String]) + text: Option[String], + `type`: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala index 6975837dcb5..ff0d72524ed 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Note.scala @@ -5,10 +5,10 @@ import org.joda.time.DateTime case class Note ( - NoteType: Option[String], - AppliesTo: Option[Seq[String]], - Value: Option[String], - Pos: Option[Int]) + noteType: Option[String], + appliesTo: Option[Seq[String]], + value: Option[String], + pos: Option[Int]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala index 8a659ce4872..182a8974ff6 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala @@ -5,9 +5,9 @@ import org.joda.time.DateTime case class PartOfSpeech ( - Roots: Option[Seq[Root]], - StorageAbbr: Option[Seq[String]], - AllCategories: Option[Seq[Category]]) + roots: Option[Seq[Root]], + storageAbbr: Option[Seq[String]], + allCategories: Option[Seq[Category]]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala index d5147838373..5fdd347cb33 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Related.scala @@ -5,13 +5,13 @@ import org.joda.time.DateTime case class Related ( - Label1: Option[String], - RelationshipType: Option[String], - Label2: Option[String], - Label3: Option[String], - Words: Option[Seq[String]], - Gram: Option[String], - Label4: Option[String]) + label1: Option[String], + relationshipType: Option[String], + label2: Option[String], + label3: Option[String], + words: Option[Seq[String]], + gram: Option[String], + label4: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala index b8580e33ef3..ee134f80340 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Root.scala @@ -5,9 +5,9 @@ import org.joda.time.DateTime case class Root ( - Id: Option[Long], - Name: Option[String], - Categories: Option[Seq[Category]]) + id: Option[Long], + name: Option[String], + categories: Option[Seq[Category]]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala index 79401c1e1b6..7c7b7e9b5ab 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/ScoredWord.scala @@ -5,17 +5,17 @@ import org.joda.time.DateTime case class ScoredWord ( - Position: Option[Int], - Id: Option[Long], - DocTermCount: Option[Int], - Lemma: Option[String], - WordType: Option[String], - Score: Option[Float], - SentenceId: Option[Long], - Word: Option[String], - Stopword: Option[Boolean], - BaseWordScore: Option[Double], - PartOfSpeech: Option[String]) + position: Option[Int], + id: Option[Long], + docTermCount: Option[Int], + lemma: Option[String], + wordType: Option[String], + score: Option[Float], + sentenceId: Option[Long], + word: Option[String], + stopword: Option[Boolean], + baseWordScore: Option[Double], + partOfSpeech: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala index eb9944b10b7..99f7f0400af 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Sentence.scala @@ -5,12 +5,12 @@ import org.joda.time.DateTime case class Sentence ( - HasScoredWords: Option[Boolean], - Id: Option[Long], - ScoredWords: Option[Seq[ScoredWord]], - Display: Option[String], - Rating: Option[Int], - DocumentMetadataId: Option[Long]) + hasScoredWords: Option[Boolean], + id: Option[Long], + scoredWords: Option[Seq[ScoredWord]], + display: Option[String], + rating: Option[Int], + documentMetadataId: Option[Long]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala index 49ee8301c9f..1807123222c 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala @@ -5,10 +5,10 @@ import org.joda.time.DateTime case class SimpleDefinition ( - Text: Option[String], - Source: Option[String], - Note: Option[String], - PartOfSpeech: Option[String]) + text: Option[String], + source: Option[String], + note: Option[String], + partOfSpeech: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala index 1eea4ee4588..4548c2ece38 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/SimpleExample.scala @@ -5,10 +5,10 @@ import org.joda.time.DateTime case class SimpleExample ( - Id: Option[Long], - Title: Option[String], - Text: Option[String], - Url: Option[String]) + id: Option[Long], + title: Option[String], + text: Option[String], + url: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala index 71538e2425c..bb36fabef8e 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/StringValue.scala @@ -5,7 +5,7 @@ import org.joda.time.DateTime case class StringValue ( - Word: Option[String]) + word: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala index 99ed72f3502..0db80cb840f 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/Syllable.scala @@ -5,9 +5,9 @@ import org.joda.time.DateTime case class Syllable ( - Text: Option[String], - Seq: Option[Int], - Type: Option[String]) + text: Option[String], + seq: Option[Int], + `type`: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala index 7d3d59dd726..95d17c14fcf 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/TextPron.scala @@ -5,9 +5,9 @@ import org.joda.time.DateTime case class TextPron ( - Raw: Option[String], - Seq: Option[Int], - RawType: Option[String]) + raw: Option[String], + seq: Option[Int], + rawType: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala index 6b1db4b0c81..421c8f3210b 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/User.scala @@ -5,14 +5,14 @@ import org.joda.time.DateTime case class User ( - Id: Option[Long], - Username: Option[String], - Email: Option[String], - Status: Option[Int], - FaceBookId: Option[String], - UserName: Option[String], - DisplayName: Option[String], - Password: Option[String]) + id: Option[Long], + username: Option[String], + email: Option[String], + status: Option[Int], + faceBookId: Option[String], + userName: Option[String], + displayName: Option[String], + password: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala index 9022b32efbe..c46484d5978 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordList.scala @@ -5,17 +5,17 @@ import org.joda.time.DateTime case class WordList ( - Id: Option[Long], - Permalink: Option[String], - Name: Option[String], - CreatedAt: Option[DateTime], - UpdatedAt: Option[DateTime], - LastActivityAt: Option[DateTime], - Username: Option[String], - UserId: Option[Long], - Description: Option[String], - NumberWordsInList: Option[Long], - Type: Option[String]) + id: Option[Long], + permalink: Option[String], + name: Option[String], + createdAt: Option[DateTime], + updatedAt: Option[DateTime], + lastActivityAt: Option[DateTime], + username: Option[String], + userId: Option[Long], + description: Option[String], + numberWordsInList: Option[Long], + `type`: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala index c15ddd7c58d..062f1fe6a6b 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordListWord.scala @@ -5,13 +5,13 @@ import org.joda.time.DateTime case class WordListWord ( - Id: Option[Long], - Word: Option[String], - Username: Option[String], - UserId: Option[Long], - CreatedAt: Option[DateTime], - NumberCommentsOnWord: Option[Long], - NumberLists: Option[Long]) + id: Option[Long], + word: Option[String], + username: Option[String], + userId: Option[Long], + createdAt: Option[DateTime], + numberCommentsOnWord: Option[Long], + numberLists: Option[Long]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala index a00491ba046..5f5c1c6a426 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordObject.scala @@ -5,12 +5,12 @@ import org.joda.time.DateTime case class WordObject ( - Id: Option[Long], - Word: Option[String], - OriginalWord: Option[String], - Suggestions: Option[Seq[String]], - CanonicalForm: Option[String], - Vulgar: Option[String]) + id: Option[Long], + word: Option[String], + originalWord: Option[String], + suggestions: Option[Seq[String]], + canonicalForm: Option[String], + vulgar: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala index 8cfbf432438..6b94e34d211 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala @@ -5,18 +5,18 @@ import org.joda.time.DateTime case class WordOfTheDay ( - Id: Option[Long], - ParentId: Option[String], - Category: Option[String], - CreatedBy: Option[String], - CreatedAt: Option[DateTime], - ContentProvider: Option[ContentProvider], - HtmlExtra: Option[String], - Word: Option[String], - Definitions: Option[Seq[SimpleDefinition]], - Examples: Option[Seq[SimpleExample]], - Note: Option[String], - PublishDate: Option[DateTime]) + id: Option[Long], + parentId: Option[String], + category: Option[String], + createdBy: Option[String], + createdAt: Option[DateTime], + contentProvider: Option[ContentProvider], + htmlExtra: Option[String], + word: Option[String], + definitions: Option[Seq[SimpleDefinition]], + examples: Option[Seq[SimpleExample]], + note: Option[String], + publishDate: Option[DateTime]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala index ca2cb8182ae..771fd35b2e8 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala @@ -5,9 +5,9 @@ import org.joda.time.DateTime case class WordSearchResult ( - Count: Option[Long], - Lexicality: Option[Double], - Word: Option[String]) + count: Option[Long], + lexicality: Option[Double], + word: Option[String]) extends ApiModel diff --git a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala index a4715f16612..bc2af2a8448 100644 --- a/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala +++ b/samples/client/wordnik/akka-scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala @@ -5,8 +5,8 @@ import org.joda.time.DateTime case class WordSearchResults ( - SearchResults: Option[Seq[WordSearchResult]], - TotalResults: Option[Int]) + searchResults: Option[Seq[WordSearchResult]], + totalResults: Option[Int]) extends ApiModel From 699973dcfe3bfb9624c75006a9ea6f70ad31edeb Mon Sep 17 00:00:00 2001 From: Alexey Nechaev Date: Wed, 22 Apr 2015 16:11:16 +0300 Subject: [PATCH 08/75] Group and version are avaiable from parent pom. --- modules/swagger-codegen/pom.xml | 2 -- modules/swagger-generator/pom.xml | 2 -- 2 files changed, 4 deletions(-) diff --git a/modules/swagger-codegen/pom.xml b/modules/swagger-codegen/pom.xml index 6fc2ca0e016..e5329fce1dc 100644 --- a/modules/swagger-codegen/pom.xml +++ b/modules/swagger-codegen/pom.xml @@ -6,11 +6,9 @@ ../.. 4.0.0 - com.wordnik swagger-codegen jar swagger-codegen (core library) - 2.1.1-M2-SNAPSHOT src/main/java install diff --git a/modules/swagger-generator/pom.xml b/modules/swagger-generator/pom.xml index 143f7e32605..082384dd148 100644 --- a/modules/swagger-generator/pom.xml +++ b/modules/swagger-generator/pom.xml @@ -6,11 +6,9 @@ 2.1.1-M2-SNAPSHOT ../.. - com.wordnik swagger-generator war swagger-generator - 2.1.1-M2-SNAPSHOT src/main/java From fc0be6d5035f53d30b5add3dfd027d52d923fb7c Mon Sep 17 00:00:00 2001 From: Alexey Nechaev Date: Wed, 22 Apr 2015 16:17:28 +0300 Subject: [PATCH 09/75] Fixes #646: Example field handling has been fixed. --- .../swagger/codegen/CodegenResponse.java | 8 +- .../swagger/codegen/DefaultCodegen.java | 81 +++++++++++++------ .../codegen/examples/ExampleGenerator.java | 54 ++++++++----- .../main/resources/htmlDocs/index.mustache | 2 +- .../src/test/resources/2_0/petstore.json | 12 +++ pom.xml | 2 +- 6 files changed, 107 insertions(+), 52 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java index 15931c9fd27..6c3ce5030f0 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenResponse.java @@ -1,11 +1,13 @@ package com.wordnik.swagger.codegen; -import java.util.*; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; public class CodegenResponse { public String code, message; public Boolean hasMore; - public List> examples; + public List> examples; public final List headers = new ArrayList(); public String dataType, baseType, containerType; public Boolean simpleType; @@ -14,4 +16,4 @@ public class CodegenResponse { public Boolean isListContainer; public Object schema; public String jsonSchema; -} \ No newline at end of file +} 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 6f51374c536..ba67219014a 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 @@ -1,26 +1,58 @@ package com.wordnik.swagger.codegen; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.lang.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import com.wordnik.swagger.codegen.examples.ExampleGenerator; -import com.wordnik.swagger.models.*; +import com.wordnik.swagger.models.ArrayModel; +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.ModelImpl; +import com.wordnik.swagger.models.Operation; +import com.wordnik.swagger.models.RefModel; +import com.wordnik.swagger.models.Response; +import com.wordnik.swagger.models.Swagger; import com.wordnik.swagger.models.auth.ApiKeyAuthDefinition; import com.wordnik.swagger.models.auth.BasicAuthDefinition; import com.wordnik.swagger.models.auth.In; import com.wordnik.swagger.models.auth.SecuritySchemeDefinition; -import com.wordnik.swagger.models.parameters.*; -import com.wordnik.swagger.models.properties.*; +import com.wordnik.swagger.models.parameters.BodyParameter; +import com.wordnik.swagger.models.parameters.CookieParameter; +import com.wordnik.swagger.models.parameters.FormParameter; +import com.wordnik.swagger.models.parameters.HeaderParameter; +import com.wordnik.swagger.models.parameters.Parameter; +import com.wordnik.swagger.models.parameters.PathParameter; +import com.wordnik.swagger.models.parameters.QueryParameter; +import com.wordnik.swagger.models.parameters.SerializableParameter; +import com.wordnik.swagger.models.properties.AbstractNumericProperty; +import com.wordnik.swagger.models.properties.ArrayProperty; +import com.wordnik.swagger.models.properties.BooleanProperty; +import com.wordnik.swagger.models.properties.DateProperty; +import com.wordnik.swagger.models.properties.DateTimeProperty; +import com.wordnik.swagger.models.properties.DecimalProperty; +import com.wordnik.swagger.models.properties.DoubleProperty; +import com.wordnik.swagger.models.properties.FloatProperty; +import com.wordnik.swagger.models.properties.IntegerProperty; +import com.wordnik.swagger.models.properties.LongProperty; +import com.wordnik.swagger.models.properties.MapProperty; +import com.wordnik.swagger.models.properties.Property; +import com.wordnik.swagger.models.properties.PropertyBuilder; +import com.wordnik.swagger.models.properties.RefProperty; +import com.wordnik.swagger.models.properties.StringProperty; import com.wordnik.swagger.util.Json; -import org.apache.commons.lang.StringUtils; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.io.File; -import java.util.*; - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - public class DefaultCodegen { Logger LOGGER = LoggerFactory.getLogger(DefaultCodegen.class); @@ -996,9 +1028,9 @@ public class DefaultCodegen { if(schemes == null) return null; - List secs = new ArrayList(); - for(Iterator entries = schemes.entrySet().iterator(); entries.hasNext(); ) { - Map.Entry entry = (Map.Entry) entries.next(); + List secs = new ArrayList(schemes.size()); + for (Iterator> it = schemes.entrySet().iterator(); it.hasNext();) { + final Map.Entry entry = it.next(); final SecuritySchemeDefinition schemeDefinition = entry.getValue(); CodegenSecurity sec = CodegenModelFactory.newInstance(CodegenModelType.SECURITY); @@ -1018,23 +1050,22 @@ public class DefaultCodegen { sec.isOAuth = !sec.isBasic; } - sec.hasMore = entries.hasNext(); + sec.hasMore = it.hasNext(); secs.add(sec); } return secs; } - protected List> toExamples(Map examples) { + protected List> toExamples(Map examples) { if(examples == null) return null; - List> output = new ArrayList>(); - for(String key: examples.keySet()) { - String value = examples.get(key); + final List> output = new ArrayList>(examples.size()); + for(Map.Entry entry : examples.entrySet()) { - Map kv = new HashMap(); - kv.put("contentType", key); - kv.put("example", value); + final Map kv = new HashMap(); + kv.put("contentType", entry.getKey()); + kv.put("example", entry.getValue()); output.add(kv); } return output; 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 80063625440..51d10f7e8a6 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 @@ -1,19 +1,33 @@ package com.wordnik.swagger.codegen.examples; -import com.wordnik.swagger.models.*; -import com.wordnik.swagger.models.properties.*; -import com.wordnik.swagger.util.Json; - -import java.text.SimpleDateFormat; - - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - - import java.math.BigDecimal; -import java.util.*; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.wordnik.swagger.models.Model; +import com.wordnik.swagger.models.ModelImpl; +import com.wordnik.swagger.models.properties.ArrayProperty; +import com.wordnik.swagger.models.properties.BooleanProperty; +import com.wordnik.swagger.models.properties.DateProperty; +import com.wordnik.swagger.models.properties.DateTimeProperty; +import com.wordnik.swagger.models.properties.DecimalProperty; +import com.wordnik.swagger.models.properties.DoubleProperty; +import com.wordnik.swagger.models.properties.FileProperty; +import com.wordnik.swagger.models.properties.FloatProperty; +import com.wordnik.swagger.models.properties.IntegerProperty; +import com.wordnik.swagger.models.properties.LongProperty; +import com.wordnik.swagger.models.properties.MapProperty; +import com.wordnik.swagger.models.properties.ObjectProperty; +import com.wordnik.swagger.models.properties.Property; +import com.wordnik.swagger.models.properties.RefProperty; +import com.wordnik.swagger.models.properties.StringProperty; +import com.wordnik.swagger.models.properties.UUIDProperty; +import com.wordnik.swagger.util.Json; public class ExampleGenerator { protected Map examples; @@ -22,7 +36,7 @@ public class ExampleGenerator { this.examples = examples; } - public List> generate(Map examples, List mediaTypes, Property property) { + public List> generate(Map examples, List mediaTypes, Property property) { List> output = new ArrayList>(); Set processedModels = new HashSet(); if(examples == null ) { @@ -37,7 +51,6 @@ public class ExampleGenerator { String example = Json.pretty(resolvePropertyToExample(mediaType, property, processedModels)); if(example != null) { - example = example.replaceAll("\n", "\\\\n"); kv.put("example", example); output.add(kv); } @@ -45,7 +58,6 @@ public class ExampleGenerator { else if(property != null && mediaType.startsWith("application/xml")) { String example = new XmlExampleGenerator(this.examples).toXml(property); if(example != null) { - example = example.replaceAll("\n", "\\\\n"); kv.put("example", example); output.add(kv); } @@ -53,12 +65,10 @@ public class ExampleGenerator { } } else { - for(String key: examples.keySet()) { - String value = examples.get(key); - - Map kv = new HashMap(); - kv.put("contentType", key); - kv.put("example", value); + for(Map.Entry entry: examples.entrySet()) { + final Map kv = new HashMap(); + kv.put("contentType", entry.getKey()); + kv.put("example", Json.pretty(entry.getValue())); output.add(kv); } } diff --git a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache index 8e228257951..88bf8f42bfe 100644 --- a/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache +++ b/modules/swagger-codegen/src/main/resources/htmlDocs/index.mustache @@ -35,7 +35,7 @@ {{#examples}}

Example data

Content-Type: {{{contentType}}}
-
{{{example}}}
+
{{example}}
{{/examples}}
diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index b4678fc3ab9..30c53134633 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -720,6 +720,18 @@ "description": "successful operation", "schema": { "$ref": "#/definitions/User" + }, + "examples": { + "application/json": { + "id": 1, + "username": "johnp", + "firstName": "John", + "lastName": "Public", + "email": "johnp@swagger.io", + "password": "-secret-", + "phone": "0123456789", + "userStatus": 0 + } } }, "400": { diff --git a/pom.xml b/pom.xml index fd7d05b546a..a578b45741b 100644 --- a/pom.xml +++ b/pom.xml @@ -440,7 +440,7 @@ 1.0.6-SNAPSHOT 2.10.4 2.3.4 - 1.5.1-M2 + 1.5.2-M2-SNAPSHOT 2.1.4 2.3 1.2 From 9a361746854dc1c177e48433c4a6248b896b682a Mon Sep 17 00:00:00 2001 From: Alexey Nechaev Date: Thu, 23 Apr 2015 11:50:07 +0300 Subject: [PATCH 10/75] Clean up of '\n' escaping. --- .../languages/NodeJSServerCodegen.java | 44 ++++++++++--------- 1 file changed, 24 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java index 0c6e6067607..9d516c398f6 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/NodeJSServerCodegen.java @@ -1,11 +1,19 @@ package com.wordnik.swagger.codegen.languages; -import com.wordnik.swagger.codegen.*; -import com.wordnik.swagger.util.Json; -import com.wordnik.swagger.models.properties.*; - -import java.util.*; import java.io.File; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import com.wordnik.swagger.codegen.CodegenConfig; +import com.wordnik.swagger.codegen.CodegenOperation; +import com.wordnik.swagger.codegen.CodegenParameter; +import com.wordnik.swagger.codegen.CodegenResponse; +import com.wordnik.swagger.codegen.CodegenType; +import com.wordnik.swagger.codegen.DefaultCodegen; +import com.wordnik.swagger.codegen.SupportingFile; public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig { protected String apiVersion = "1.0.0"; @@ -156,8 +164,10 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig @Override public Map postProcessOperations(Map objs) { - Map objectMap = (Map)objs.get("operations"); - List operations = (List)objectMap.get("operation"); + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); for(CodegenOperation operation : operations) { operation.httpMethod = operation.httpMethod.toLowerCase(); List params = operation.allParams; @@ -170,20 +180,14 @@ public class NodeJSServerCodegen extends DefaultCodegen implements CodegenConfig resp.code = "default"; } } - if(operation.examples != null && operation.examples.size() > 0) { - List> examples = operation.examples; - for(int i = examples.size() - 1; i >= 0; i--) { - Map example = examples.get(i); - String contentType = example.get("contentType"); - if(contentType != null && contentType.indexOf("application/json") == 0) { - String jsonExample = example.get("example"); - if(jsonExample != null) { - jsonExample = jsonExample.replaceAll("\\\\n", "\n"); - example.put("example", jsonExample); - } + if(operation.examples != null && !operation.examples.isEmpty()) { + // Leave application/json* items only + for (Iterator> it = operation.examples.iterator(); it.hasNext();) { + final Map example = it.next(); + final String contentType = example.get("contentType"); + if (contentType == null || !contentType.startsWith("application/json")) { + it.remove(); } - else - examples.remove(i); } } } From 5c057e13062908b28b261d62672fa418280d592f Mon Sep 17 00:00:00 2001 From: wing328 Date: Sun, 12 Apr 2015 19:21:22 +0800 Subject: [PATCH 11/75] refactor csharp client using restsharp, getpetbyid working --- .../src/main/resources/csharp/api.mustache | 77 ++--- .../src/main/csharp/io/swagger/Api/PetApi.cs | 326 ++++++------------ .../main/csharp/io/swagger/Api/StoreApi.cs | 153 +++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 285 ++++++--------- 4 files changed, 286 insertions(+), 555 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 084caf97b9b..d2fd1835f3b 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using {{invokerPackage}}; using {{modelPackage}}; {{#imports}} @@ -10,10 +11,12 @@ namespace {{package}} { public class {{classname}} { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -39,65 +42,33 @@ namespace {{package}} { {{#hasMore}} {{/hasMore}}{{/allParams}} /// public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { - // create path and map variables - var path = "{{path}}".Replace("{format}","json"){{#pathParams}}.Replace("{" + "{{baseName}}" + "}", apiInvoker.ParameterToString({{{paramName}}})){{/pathParams}}; - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#requiredParamCount}} - // verify required params are set - if ({{/requiredParamCount}}{{#requiredParams}} {{paramName}} == null {{#hasMore}}|| {{/hasMore}}{{/requiredParams}}{{#requiredParamCount}}) { - throw new ApiException(400, "missing required params"); - } - {{/requiredParamCount}} + {{#requiredParams}} + // verify required param {{paramName}} is set + if ({{paramName}} == null) throw new ApiException(400, "missing required params {{paramName}}"); + {{/requiredParams}} - {{#queryParams}}if ({{paramName}} != null){ - queryParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } - {{/queryParams}} - - {{#headerParams}}headerParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - {{/headerParams}} - - {{#formParams}}if ({{paramName}} != null){ - if({{paramName}} is byte[]) { - formParams.Add("{{baseName}}", {{paramName}}); - } else { - formParams.Add("{{baseName}}", apiInvoker.ParameterToString({{paramName}})); - } - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", apiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}} + // query parameters, if any + {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", {{paramName}});{{/queryParams}} + // header parameters, if any + {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", {{paramName}});{{/headerParams}} + // form parameters, if any + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}} {{/formParams}} try { - if (typeof({{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}) == typeof(byte[])) { - {{#returnType}} - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as {{{returnType}}}; - {{/returnType}} - {{^returnType}} - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - {{/returnType}} - } else { - {{#returnType}} - var response = apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); - if (response != null){ - return ({{{returnType}}}) ApiInvoker.deserialize(response, typeof({{{returnType}}})); - } - else { - return null; - } - {{/returnType}} - {{^returnType}} - apiInvoker.invokeAPI(basePath, path, "{{httpMethod}}", queryParams, {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}, headerParams, formParams); - return; - {{/returnType}} - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + {{#returnType}}IRestResponse response = _client.Execute(_request); + return ({{{returnType}}}) ApiInvoker.deserialize(response.Content, typeof({{{returnType}}})); + //return ((object)response) as {{{returnType}}};{{/returnType}} + {{^returnType}}_client.Execute(_request); + return;{{/returnType}} + } catch (Exception ex) { + if(ex != null) { return {{#returnType}}null{{/returnType}}; } else { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 4f20c0cba45..ec781454cbb 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using io.swagger.client; using io.swagger.Model; @@ -8,10 +9,12 @@ namespace io.swagger.Api { public class PetApi { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -40,35 +43,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.PUT); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -88,35 +82,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -136,43 +121,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/findByStatus".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/findByStatus", Method.GET); - if (Status != null){ - queryParams.Add("status", apiInvoker.ParameterToString(Status)); - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any + if (Status != null) _request.AddParameter("status", Status); + // header parameters, if any - + // form parameters, if any try { - if (typeof(List) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as List; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + //return ((object)response) as List; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -192,43 +161,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/findByTags".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/findByTags", Method.GET); - if (Tags != null){ - queryParams.Add("tags", apiInvoker.ParameterToString(Tags)); - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any + if (Tags != null) _request.AddParameter("tags", Tags); + // header parameters, if any - + // form parameters, if any try { - if (typeof(List) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as List; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (List) ApiInvoker.deserialize(response, typeof(List)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + //return ((object)response) as List; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -248,40 +201,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any try { - if (typeof(Pet) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Pet; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Pet) ApiInvoker.deserialize(response, typeof(Pet)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (Pet) ApiInvoker.deserialize(response.Content, typeof(Pet)); + //return ((object)response) as Pet; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -303,49 +243,28 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - + // header parameters, if any - - if (Name != null){ - if(Name is byte[]) { - formParams.Add("name", Name); - } else { - formParams.Add("name", apiInvoker.ParameterToString(Name)); - } - } - if (Status != null){ - if(Status is byte[]) { - formParams.Add("status", Status); - } else { - formParams.Add("status", apiInvoker.ParameterToString(Status)); - } - } + // form parameters, if any + if (Name != null) _request.AddFile("name", Name); + if (Status != null) _request.AddFile("status", Status); try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -366,36 +285,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}", Method.DELETE); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - - headerParams.Add("api_key", apiInvoker.ParameterToString(ApiKey)); - - + // header parameters, if any + if (ApiKey != null) _request.AddHeader("api_key", ApiKey); + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -417,49 +326,28 @@ namespace io.swagger.Api { // create path and map variables var path = "/pet/{petId}/uploadImage".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + // query parameters, if any - + // header parameters, if any - - if (AdditionalMetadata != null){ - if(AdditionalMetadata is byte[]) { - formParams.Add("additionalMetadata", AdditionalMetadata); - } else { - formParams.Add("additionalMetadata", apiInvoker.ParameterToString(AdditionalMetadata)); - } - } - if (File != null){ - if(File is byte[]) { - formParams.Add("file", File); - } else { - formParams.Add("file", apiInvoker.ParameterToString(File)); - } - } + // form parameters, if any + if (AdditionalMetadata != null) _request.AddFile("additionalMetadata", AdditionalMetadata); + if (File != null) _request.AddParameter("file", File); try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 2514539e298..e921827d94b 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using io.swagger.client; using io.swagger.Model; @@ -8,10 +9,12 @@ namespace io.swagger.Api { public class StoreApi { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -39,40 +42,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/inventory".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/inventory", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(Dictionary) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Dictionary; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Dictionary) ApiInvoker.deserialize(response, typeof(Dictionary)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (Dictionary) ApiInvoker.deserialize(response.Content, typeof(Dictionary)); + //return ((object)response) as Dictionary; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -92,40 +82,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/order".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(Order) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Order; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - if (response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + //return ((object)response) as Order; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -145,40 +122,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order/{orderId}", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any try { - if (typeof(Order) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as Order; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (Order) ApiInvoker.deserialize(response, typeof(Order)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + //return ((object)response) as Order; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -198,35 +162,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/store/order/{orderId}", Method.DELETE); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 4f1f4a1bf19..dfbede38cfb 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using RestSharp; using io.swagger.client; using io.swagger.Model; @@ -8,10 +9,12 @@ namespace io.swagger.Api { public class UserApi { string basePath; private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); + protected RestClient _client; public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; + _client = new RestClient(basePath); } public ApiInvoker getInvoker() { @@ -40,35 +43,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -88,35 +82,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/createWithArray".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/createWithArray", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -136,35 +121,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/createWithList".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/createWithList", Method.POST); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "POST", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -185,46 +161,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/login".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/login", Method.GET); - if (Username != null){ - queryParams.Add("username", apiInvoker.ParameterToString(Username)); - } - if (Password != null){ - queryParams.Add("password", apiInvoker.ParameterToString(Password)); - } + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any + if (Username != null) _request.AddParameter("username", Username); if (Password != null) _request.AddParameter("password", Password); + // header parameters, if any - + // form parameters, if any try { - if (typeof(string) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as string; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (string) ApiInvoker.deserialize(response, typeof(string)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (string) ApiInvoker.deserialize(response.Content, typeof(string)); + //return ((object)response) as string; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -243,35 +200,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/logout".Replace("{format}","json"); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/logout", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default - + // query parameters, if any - + // header parameters, if any + + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -291,40 +239,27 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.GET); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any try { - if (typeof(User) == typeof(byte[])) { - - var response = apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return ((object)response) as User; - - - } else { - - var response = apiInvoker.invokeAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - if (response != null){ - return (User) ApiInvoker.deserialize(response, typeof(User)); - } - else { - return null; - } - - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + IRestResponse response = _client.Execute(_request); + return (User) ApiInvoker.deserialize(response.Content, typeof(User)); + //return ((object)response) as User; + + } catch (Exception ex) { + if(ex != null) { return null; } else { @@ -345,35 +280,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.PUT); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "PUT", queryParams, Body, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { @@ -393,35 +319,26 @@ namespace io.swagger.Api { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); - // query params - var queryParams = new Dictionary(); - var headerParams = new Dictionary(); - var formParams = new Dictionary(); + var _request = new RestRequest("/user/{username}", Method.DELETE); + // path (url segment) parameters + _request.AddUrlSegment("format", "json"); // set format to json by default + _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + // query parameters, if any - + // header parameters, if any - + // form parameters, if any try { - if (typeof(void) == typeof(byte[])) { - - - apiInvoker.invokeBinaryAPI(basePath, path, "GET", queryParams, null, headerParams, formParams); - return; - - } else { - - - apiInvoker.invokeAPI(basePath, path, "DELETE", queryParams, null, headerParams, formParams); - return; - - } - } catch (ApiException ex) { - if(ex.ErrorCode == 404) { + + _client.Execute(_request); + return; + } catch (Exception ex) { + if(ex != null) { return ; } else { From 8818c209df2d9dd49a6a40f2ae8bec348ad9c062 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 28 Apr 2015 23:48:29 +0800 Subject: [PATCH 12/75] udpate csharp client with restsharp --- .../languages/CSharpClientCodegen.java | 2 +- .../src/main/resources/csharp/api.mustache | 43 +-- .../main/resources/csharp/apiInvoker.mustache | 288 ++++-------------- .../src/main/resources/csharp/model.mustache | 10 +- .../src/main/csharp/io/swagger/Api/PetApi.cs | 102 ++++--- .../main/csharp/io/swagger/Api/StoreApi.cs | 58 ++-- .../src/main/csharp/io/swagger/Api/UserApi.cs | 88 +++--- .../main/csharp/io/swagger/Model/Category.cs | 9 +- .../src/main/csharp/io/swagger/Model/Order.cs | 18 +- .../src/main/csharp/io/swagger/Model/Pet.cs | 18 +- .../src/main/csharp/io/swagger/Model/Tag.cs | 9 +- .../src/main/csharp/io/swagger/Model/User.cs | 22 +- .../csharp/io/swagger/client/ApiInvoker.cs | 288 ++++-------------- 13 files changed, 347 insertions(+), 608 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java index 969b143c5a0..13a16747483 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java @@ -80,7 +80,7 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.put("double", "double?"); typeMapping.put("number", "double?"); typeMapping.put("Date", "DateTime"); - typeMapping.put("file", "byte[]"); + typeMapping.put("file", "string"); // path to file typeMapping.put("array", "List"); typeMapping.put("map", "Dictionary"); diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index d2fd1835f3b..ea0e9ab0786 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -10,36 +10,38 @@ namespace {{package}} { {{#operations}} public class {{classname}} { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public {{classname}}(String basePath = "{{basePath}}") { this.basePath = basePath; - _client = new RestClient(basePath); + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } {{#operation}} - + /// /// {{summary}} {{notes}} /// {{#allParams}}/// {{description}} - {{#hasMore}} {{/hasMore}}{{/allParams}} + {{/allParams}} /// public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { @@ -52,20 +54,23 @@ namespace {{package}} { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - {{#pathParams}}_request.AddUrlSegment("{{baseName}}", apiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}} + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}} // query parameters, if any {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", {{paramName}});{{/queryParams}} // header parameters, if any {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", {{paramName}});{{/headerParams}} // form parameters, if any - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}} {{/formParams}} + {{#bodyParam}} + _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); + {{/bodyParam}} try { - {{#returnType}}IRestResponse response = _client.Execute(_request); - return ({{{returnType}}}) ApiInvoker.deserialize(response.Content, typeof({{{returnType}}})); + {{#returnType}}IRestResponse response = restClient.Execute(_request); + return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}})); //return ((object)response) as {{{returnType}}};{{/returnType}} - {{^returnType}}_client.Execute(_request); + {{^returnType}}restClient.Execute(_request); return;{{/returnType}} } catch (Exception ex) { if(ex != null) { diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache index 4e7f1b6997b..9beebc19231 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiInvoker.mustache @@ -1,235 +1,81 @@ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Text; - using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; - namespace {{invokerPackage}} { - public class ApiInvoker { - private static readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); +namespace {{invokerPackage}} { + public class ApiInvoker { + private static Dictionary defaultHeaderMap = new Dictionary(); - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public static void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } + /// + /// Get default header + /// + /// Dictionary of default header + public static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public string escapeString(string str) { - return str; - } + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public static string EscapeString(string str) { + return str; + } - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public string ParameterToString(object obj) + /// + /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string + /// + /// The parameter (header, path, query, form) + /// Formatted string + public static string ParameterToString(object obj) + { + return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public static object Deserialize(string json, Type type) { + try { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + return JsonConvert.DeserializeObject(json, type); } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - + catch (IOException e) { + throw new ApiException(500, e.Message); } + } - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; - } - - private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.Method = method; - - byte[] formData = null; - if (formParams.Count > 0) - { - string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); - client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; - formData = GetMultipartFormData(formParams, formDataBoundary); - client.ContentLength = formData.Length; - } - else - { - client.ContentType = "application/json"; - } - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PATCH": - case "PUT": - case "DELETE": - using (Stream requestStream = client.GetRequestStream()) - { - if (formData != null) - { - requestStream.Write(formData, 0, formData.Length); - } - - var swRequestWriter = new StreamWriter(requestStream); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - } - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - - try - { - var webResponse = (HttpWebResponse)client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) - { - webResponse.Close(); - throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); - } - - if (binaryResponse) - { - using (var memoryStream = new MemoryStream()) - { - webResponse.GetResponseStream().CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - else - { - using (var responseReader = new StreamReader(webResponse.GetResponseStream())) - { - var responseData = responseReader.ReadToEnd(); - return responseData; - } - } - } - catch(WebException ex) - { - var response = ex.Response as HttpWebResponse; - int statusCode = 0; - if (response != null) - { - statusCode = (int)response.StatusCode; - response.Close(); - } - throw new ApiException(statusCode, ex.Message); - } - } - - private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) - { - Stream formDataStream = new System.IO.MemoryStream(); - bool needsCLRF = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsCLRF) - formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); - - needsCLRF = true; - - if (param.Value is byte[]) - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", - boundary, - param.Key, - "application/octet-stream"); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); - } - else - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - string footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - byte[] formData = new byte[formDataStream.Length]; - formDataStream.Read(formData, 0, formData.Length); - formDataStream.Close(); - - return formData; + catch (Exception e) { + throw new ApiException(500, e.Message); } } } +} diff --git a/modules/swagger-codegen/src/main/resources/csharp/model.mustache b/modules/swagger-codegen/src/main/resources/csharp/model.mustache index d9ef4ffbedd..a8a3aa3a7a2 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/model.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/model.mustache @@ -2,19 +2,19 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; {{#models}} {{#model}} namespace {{package}} { + [DataContract] public class {{classname}} { {{#vars}} - - {{#description}}/* {{{description}}} */ - {{/description}} + {{#description}}/* {{{description}}} */{{/description}} + [DataMember(Name="{{baseName}}", EmitDefaultValue=false)] public {{{datatype}}} {{name}} { get; set; } {{/vars}} - public override string ToString() { var sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); @@ -27,4 +27,4 @@ namespace {{package}} { } {{/model}} {{/models}} -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index ec781454cbb..e039513c581 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -8,31 +8,33 @@ namespace io.swagger.Api { public class PetApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public PetApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - _client = new RestClient(basePath); + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Update an existing pet /// @@ -56,10 +58,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -71,7 +76,7 @@ namespace io.swagger.Api { } } - + /// /// Add a new pet to the store /// @@ -95,10 +100,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -110,7 +118,7 @@ namespace io.swagger.Api { } } - + /// /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// @@ -134,10 +142,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + IRestResponse response = restClient.Execute(_request); + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); //return ((object)response) as List; } catch (Exception ex) { @@ -150,7 +159,7 @@ namespace io.swagger.Api { } } - + /// /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// @@ -174,10 +183,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (List) ApiInvoker.deserialize(response.Content, typeof(List)); + IRestResponse response = restClient.Execute(_request); + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); //return ((object)response) as List; } catch (Exception ex) { @@ -190,7 +200,7 @@ namespace io.swagger.Api { } } - + /// /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// @@ -207,17 +217,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (Pet) ApiInvoker.deserialize(response.Content, typeof(Pet)); + IRestResponse response = restClient.Execute(_request); + return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); //return ((object)response) as Pet; } catch (Exception ex) { @@ -230,13 +241,13 @@ namespace io.swagger.Api { } } - + /// /// Updates a pet in the store with form data /// /// ID of pet that needs to be updated - /// Updated name of the pet - /// Updated status of the pet + /// Updated name of the pet + /// Updated status of the pet /// public void UpdatePetWithForm (string PetId, string Name, string Status) { @@ -249,19 +260,20 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any // form parameters, if any - if (Name != null) _request.AddFile("name", Name); - if (Status != null) _request.AddFile("status", Status); + if (Name != null) _request.AddParameter("name", Name); + if (Status != null) _request.AddParameter("status", Status); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -273,12 +285,12 @@ namespace io.swagger.Api { } } - + /// /// Deletes a pet /// /// - /// Pet id to delete + /// Pet id to delete /// public void DeletePet (string ApiKey, long? PetId) { @@ -291,17 +303,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any if (ApiKey != null) _request.AddHeader("api_key", ApiKey); // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -313,13 +326,13 @@ namespace io.swagger.Api { } } - + /// /// uploads an image /// /// ID of pet to update - /// Additional data to pass to server - /// file to upload + /// Additional data to pass to server + /// file to upload /// public void UploadFile (long? PetId, string AdditionalMetadata, byte[] File) { @@ -332,19 +345,20 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", apiInvoker.ParameterToString(PetId)); + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // query parameters, if any // header parameters, if any // form parameters, if any - if (AdditionalMetadata != null) _request.AddFile("additionalMetadata", AdditionalMetadata); - if (File != null) _request.AddParameter("file", File); + if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", AdditionalMetadata); + if (File != null) _request.AddFile("file", File); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index e921827d94b..6d0b148ea15 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -8,31 +8,33 @@ namespace io.swagger.Api { public class StoreApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public StoreApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - _client = new RestClient(basePath); + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Returns pet inventories by status Returns a map of status codes to quantities /// @@ -55,10 +57,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (Dictionary) ApiInvoker.deserialize(response.Content, typeof(Dictionary)); + IRestResponse response = restClient.Execute(_request); + return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); //return ((object)response) as Dictionary; } catch (Exception ex) { @@ -71,7 +74,7 @@ namespace io.swagger.Api { } } - + /// /// Place an order for a pet /// @@ -95,10 +98,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - IRestResponse response = _client.Execute(_request); - return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + IRestResponse response = restClient.Execute(_request); + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); //return ((object)response) as Order; } catch (Exception ex) { @@ -111,7 +117,7 @@ namespace io.swagger.Api { } } - + /// /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// @@ -128,17 +134,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (Order) ApiInvoker.deserialize(response.Content, typeof(Order)); + IRestResponse response = restClient.Execute(_request); + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); //return ((object)response) as Order; } catch (Exception ex) { @@ -151,7 +158,7 @@ namespace io.swagger.Api { } } - + /// /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// @@ -168,17 +175,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", apiInvoker.ParameterToString(OrderId)); + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index dfbede38cfb..7ca6bd5b1fc 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -8,31 +8,33 @@ namespace io.swagger.Api { public class UserApi { string basePath; - private readonly ApiInvoker apiInvoker = ApiInvoker.GetInstance(); - protected RestClient _client; + protected RestClient restClient; public UserApi(String basePath = "http://petstore.swagger.io/v2") { this.basePath = basePath; - _client = new RestClient(basePath); + this.restClient = new RestClient(basePath); } - public ApiInvoker getInvoker() { - return apiInvoker; - } - - // Sets the endpoint base url for the services being accessed - public void setBasePath(string basePath) { + /// + /// Sets the endpoint base url for the services being accessed + /// + /// Base URL + /// + public void SetBasePath(string basePath) { this.basePath = basePath; } - // Gets the endpoint base url for the services being accessed - public String getBasePath() { - return basePath; + /// + /// Gets the endpoint base url for the services being accessed + /// Base URL + /// + public String GetBasePath() { + return this.basePath; } - + /// /// Create user This can only be done by the logged in user. /// @@ -56,10 +58,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -71,7 +76,7 @@ namespace io.swagger.Api { } } - + /// /// Creates list of users with given input array /// @@ -95,10 +100,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -110,7 +118,7 @@ namespace io.swagger.Api { } } - + /// /// Creates list of users with given input array /// @@ -134,10 +142,13 @@ namespace io.swagger.Api { // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -149,12 +160,12 @@ namespace io.swagger.Api { } } - + /// /// Logs user into the system /// /// The user name for login - /// The password for login in clear text + /// The password for login in clear text /// public string LoginUser (string Username, string Password) { @@ -174,10 +185,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (string) ApiInvoker.deserialize(response.Content, typeof(string)); + IRestResponse response = restClient.Execute(_request); + return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); //return ((object)response) as string; } catch (Exception ex) { @@ -190,7 +202,7 @@ namespace io.swagger.Api { } } - + /// /// Logs out current logged in user session /// @@ -213,10 +225,11 @@ namespace io.swagger.Api { // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -228,7 +241,7 @@ namespace io.swagger.Api { } } - + /// /// Get user by user name /// @@ -245,17 +258,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - IRestResponse response = _client.Execute(_request); - return (User) ApiInvoker.deserialize(response.Content, typeof(User)); + IRestResponse response = restClient.Execute(_request); + return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); //return ((object)response) as User; } catch (Exception ex) { @@ -268,12 +282,12 @@ namespace io.swagger.Api { } } - + /// /// Updated user This can only be done by the logged in user. /// /// name that need to be deleted - /// Updated user object + /// Updated user object /// public void UpdateUser (string Username, User Body) { @@ -286,17 +300,20 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // query parameters, if any // header parameters, if any // form parameters, if any + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { @@ -308,7 +325,7 @@ namespace io.swagger.Api { } } - + /// /// Delete user This can only be done by the logged in user. /// @@ -325,17 +342,18 @@ namespace io.swagger.Api { // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", apiInvoker.ParameterToString(Username)); + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // query parameters, if any // header parameters, if any // form parameters, if any + try { - _client.Execute(_request); + restClient.Execute(_request); return; } catch (Exception ex) { if(ex != null) { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs index bfe1c0c4be8..7b13e16523a 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs @@ -2,21 +2,22 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; namespace io.swagger.Model { + [DataContract] public class Category { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Category {\n"); @@ -31,4 +32,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs index 20a6d7367dd..3d67de0a82b 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs @@ -2,42 +2,42 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; namespace io.swagger.Model { + [DataContract] public class Order { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="petId", EmitDefaultValue=false)] public long? PetId { get; set; } - + [DataMember(Name="quantity", EmitDefaultValue=false)] public int? Quantity { get; set; } - + [DataMember(Name="shipDate", EmitDefaultValue=false)] public DateTime ShipDate { get; set; } - /* Order Status */ - + [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } - + [DataMember(Name="complete", EmitDefaultValue=false)] public bool? Complete { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Order {\n"); @@ -60,4 +60,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs index b0f3573b78c..a00f8729d3f 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs @@ -2,42 +2,42 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; namespace io.swagger.Model { + [DataContract] public class Pet { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="category", EmitDefaultValue=false)] public Category Category { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - + [DataMember(Name="photoUrls", EmitDefaultValue=false)] public List PhotoUrls { get; set; } - + [DataMember(Name="tags", EmitDefaultValue=false)] public List Tags { get; set; } - /* pet status in the store */ - + [DataMember(Name="status", EmitDefaultValue=false)] public string Status { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Pet {\n"); @@ -60,4 +60,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs index 2fbf7070050..b0c08431472 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs @@ -2,21 +2,22 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; namespace io.swagger.Model { + [DataContract] public class Tag { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class Tag {\n"); @@ -31,4 +32,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs index 146ba13c768..37931c6fbe4 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs @@ -2,52 +2,52 @@ using System; using System.Text; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; namespace io.swagger.Model { + [DataContract] public class User { - + [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } - + [DataMember(Name="username", EmitDefaultValue=false)] public string Username { get; set; } - + [DataMember(Name="firstName", EmitDefaultValue=false)] public string FirstName { get; set; } - + [DataMember(Name="lastName", EmitDefaultValue=false)] public string LastName { get; set; } - + [DataMember(Name="email", EmitDefaultValue=false)] public string Email { get; set; } - + [DataMember(Name="password", EmitDefaultValue=false)] public string Password { get; set; } - + [DataMember(Name="phone", EmitDefaultValue=false)] public string Phone { get; set; } - /* User Status */ - + [DataMember(Name="userStatus", EmitDefaultValue=false)] public int? UserStatus { get; set; } - public override string ToString() { var sb = new StringBuilder(); sb.Append("class User {\n"); @@ -74,4 +74,4 @@ namespace io.swagger.Model { } -} \ No newline at end of file +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs index ee2c5b1d889..abdfad1ae3b 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs @@ -1,235 +1,81 @@ - using System; - using System.Collections.Generic; - using System.IO; - using System.Linq; - using System.Net; - using System.Text; - using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text; +using Newtonsoft.Json; - namespace io.swagger.client { - public class ApiInvoker { - private static readonly ApiInvoker _instance = new ApiInvoker(); - private Dictionary defaultHeaderMap = new Dictionary(); +namespace io.swagger.client { + public class ApiInvoker { + private static Dictionary defaultHeaderMap = new Dictionary(); - public static ApiInvoker GetInstance() { - return _instance; - } + /// + /// Add default header + /// + /// Header field name + /// Header field value + /// + public static void AddDefaultHeader(string key, string value) { + defaultHeaderMap.Add(key, value); + } - /// - /// Add default header - /// - /// Header field name - /// Header field value - /// - public void addDefaultHeader(string key, string value) { - defaultHeaderMap.Add(key, value); - } + /// + /// Get default header + /// + /// Dictionary of default header + public static Dictionary GetDefaultHeader() { + return defaultHeaderMap; + } - /// - /// escape string (url-encoded) - /// - /// String to be escaped - /// Escaped string - public string escapeString(string str) { - return str; - } + /// + /// escape string (url-encoded) + /// + /// String to be escaped + /// Escaped string + public static string EscapeString(string str) { + return str; + } - /// - /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string - /// - /// The parameter (header, path, query, form) - /// Formatted string - public string ParameterToString(object obj) + /// + /// if parameter is DateTime, output in ISO8601 format, otherwise just return the string + /// + /// The parameter (header, path, query, form) + /// Formatted string + public static string ParameterToString(object obj) + { + return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + } + + /// + /// Deserialize the JSON string into a proper object + /// + /// JSON string + /// Object type + /// Object representation of the JSON string + public static object Deserialize(string json, Type type) { + try { - return (obj is DateTime) ? ((DateTime)obj).ToString ("u") : Convert.ToString (obj); + return JsonConvert.DeserializeObject(json, type); } - - /// - /// Deserialize the JSON string into a proper object - /// - /// JSON string - /// Object type - /// Object representation of the JSON string - public static object deserialize(string json, Type type) { - try - { - return JsonConvert.DeserializeObject(json, type); - } - catch (IOException e) { - throw new ApiException(500, e.Message); - } - + catch (IOException e) { + throw new ApiException(500, e.Message); } + } - public static string serialize(object obj) { - try - { - return obj != null ? JsonConvert.SerializeObject(obj) : null; - } - catch (Exception e) { - throw new ApiException(500, e.Message); - } - } - - public string invokeAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) + /// + /// Serialize an object into JSON string + /// + /// Object + /// JSON string + public static string Serialize(object obj) { + try { - return invokeAPIInternal(host, path, method, false, queryParams, body, headerParams, formParams) as string; + return obj != null ? JsonConvert.SerializeObject(obj) : null; } - - public byte[] invokeBinaryAPI(string host, string path, string method, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) - { - return invokeAPIInternal(host, path, method, true, queryParams, body, headerParams, formParams) as byte[]; - } - - private object invokeAPIInternal(string host, string path, string method, bool binaryResponse, Dictionary queryParams, object body, Dictionary headerParams, Dictionary formParams) { - var b = new StringBuilder(); - - foreach (var queryParamItem in queryParams) - { - var value = queryParamItem.Value; - if (value == null) continue; - b.Append(b.ToString().Length == 0 ? "?" : "&"); - b.Append(escapeString(queryParamItem.Key)).Append("=").Append(escapeString(value)); - } - - var querystring = b.ToString(); - - host = host.EndsWith("/") ? host.Substring(0, host.Length - 1) : host; - - var client = WebRequest.Create(host + path + querystring); - client.Method = method; - - byte[] formData = null; - if (formParams.Count > 0) - { - string formDataBoundary = String.Format("----------{0:N}", Guid.NewGuid()); - client.ContentType = "multipart/form-data; boundary=" + formDataBoundary; - formData = GetMultipartFormData(formParams, formDataBoundary); - client.ContentLength = formData.Length; - } - else - { - client.ContentType = "application/json"; - } - - foreach (var headerParamsItem in headerParams) - { - client.Headers.Add(headerParamsItem.Key, headerParamsItem.Value); - } - foreach (var defaultHeaderMapItem in defaultHeaderMap.Where(defaultHeaderMapItem => !headerParams.ContainsKey(defaultHeaderMapItem.Key))) - { - client.Headers.Add(defaultHeaderMapItem.Key, defaultHeaderMapItem.Value); - } - - switch (method) - { - case "GET": - break; - case "POST": - case "PATCH": - case "PUT": - case "DELETE": - using (Stream requestStream = client.GetRequestStream()) - { - if (formData != null) - { - requestStream.Write(formData, 0, formData.Length); - } - - var swRequestWriter = new StreamWriter(requestStream); - swRequestWriter.Write(serialize(body)); - swRequestWriter.Close(); - } - break; - default: - throw new ApiException(500, "unknown method type " + method); - } - - try - { - var webResponse = (HttpWebResponse)client.GetResponse(); - if (webResponse.StatusCode != HttpStatusCode.OK) - { - webResponse.Close(); - throw new ApiException((int)webResponse.StatusCode, webResponse.StatusDescription); - } - - if (binaryResponse) - { - using (var memoryStream = new MemoryStream()) - { - webResponse.GetResponseStream().CopyTo(memoryStream); - return memoryStream.ToArray(); - } - } - else - { - using (var responseReader = new StreamReader(webResponse.GetResponseStream())) - { - var responseData = responseReader.ReadToEnd(); - return responseData; - } - } - } - catch(WebException ex) - { - var response = ex.Response as HttpWebResponse; - int statusCode = 0; - if (response != null) - { - statusCode = (int)response.StatusCode; - response.Close(); - } - throw new ApiException(statusCode, ex.Message); - } - } - - private static byte[] GetMultipartFormData(Dictionary postParameters, string boundary) - { - Stream formDataStream = new System.IO.MemoryStream(); - bool needsCLRF = false; - - foreach (var param in postParameters) - { - // Thanks to feedback from commenters, add a CRLF to allow multiple parameters to be added. - // Skip it on the first parameter, add it to subsequent parameters. - if (needsCLRF) - formDataStream.Write(Encoding.UTF8.GetBytes("\r\n"), 0, Encoding.UTF8.GetByteCount("\r\n")); - - needsCLRF = true; - - if (param.Value is byte[]) - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n", - boundary, - param.Key, - "application/octet-stream"); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - - // Write the file data directly to the Stream, rather than serializing it to a string. - formDataStream.Write((param.Value as byte[]), 0, (param.Value as byte[]).Length); - } - else - { - string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}", - boundary, - param.Key, - param.Value); - formDataStream.Write(Encoding.UTF8.GetBytes(postData), 0, Encoding.UTF8.GetByteCount(postData)); - } - } - - // Add the end of the request. Start with a newline - string footer = "\r\n--" + boundary + "--\r\n"; - formDataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer)); - - // Dump the Stream into a byte[] - formDataStream.Position = 0; - byte[] formData = new byte[formDataStream.Length]; - formDataStream.Read(formData, 0, formData.Length); - formDataStream.Close(); - - return formData; + catch (Exception e) { + throw new ApiException(500, e.Message); } } } +} From 96d837274ea8d51699771c6c48195a03b19b408d Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 29 Apr 2015 10:43:57 +0800 Subject: [PATCH 13/75] udpate csharp template with better comment and ParameterToString --- .../src/main/resources/csharp/api.mustache | 24 +++--- .../src/main/csharp/io/swagger/Api/PetApi.cs | 81 ++++++------------- .../main/csharp/io/swagger/Api/StoreApi.cs | 32 ++------ .../src/main/csharp/io/swagger/Api/UserApi.cs | 77 +++++------------- 4 files changed, 63 insertions(+), 151 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index ea0e9ab0786..493a5a4de7c 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -40,10 +40,9 @@ namespace {{package}} { /// /// {{summary}} {{notes}} /// - {{#allParams}}/// {{description}} - {{/allParams}} - /// - public {{#returnType}}{{{returnType}}} {{/returnType}}{{^returnType}}void {{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { +{{#allParams}} /// {{description}} +{{/allParams}} /// {{#returnType}}{{{returnType}}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); @@ -52,18 +51,17 @@ namespace {{package}} { if ({{paramName}} == null) throw new ApiException(400, "missing required params {{paramName}}"); {{/requiredParams}} - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}}));{{/pathParams}} - // query parameters, if any - {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", {{paramName}});{{/queryParams}} - // header parameters, if any - {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", {{paramName}});{{/headerParams}} - // form parameters, if any - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", {{paramName}});{{/isFile}} + {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter + {{/pathParams}} + {{#queryParams}} if ({{paramName}} != null) _request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // query parameter + {{/queryParams}} + {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter + {{/headerParams}} + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}}));{{/isFile}} // form parameter {{/formParams}} {{#bodyParam}} - _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); + _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // HTTP request body (model) {{/bodyParam}} try { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index e039513c581..52f67631966 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -39,7 +39,6 @@ namespace io.swagger.Api { /// Update an existing pet /// /// Pet object that needs to be added to the store - /// public void UpdatePet (Pet Body) { // create path and map variables @@ -49,17 +48,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -81,7 +76,6 @@ namespace io.swagger.Api { /// Add a new pet to the store /// /// Pet object that needs to be added to the store - /// public void AddPet (Pet Body) { // create path and map variables @@ -91,17 +85,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -123,7 +113,6 @@ namespace io.swagger.Api { /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// public List FindPetsByStatus (List Status) { // create path and map variables @@ -133,14 +122,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - if (Status != null) _request.AddParameter("status", Status); - // header parameters, if any + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter + - // form parameters, if any @@ -164,7 +150,6 @@ namespace io.swagger.Api { /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// public List FindPetsByTags (List Tags) { // create path and map variables @@ -174,14 +159,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - if (Tags != null) _request.AddParameter("tags", Tags); - // header parameters, if any + if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter + - // form parameters, if any @@ -205,7 +187,6 @@ namespace io.swagger.Api { /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - /// public Pet GetPetById (long? PetId) { // create path and map variables @@ -215,14 +196,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any @@ -248,7 +226,6 @@ namespace io.swagger.Api { /// ID of pet that needs to be updated /// Updated name of the pet /// Updated status of the pet - /// public void UpdatePetWithForm (string PetId, string Name, string Status) { // create path and map variables @@ -258,16 +235,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - // header parameters, if any - // form parameters, if any - if (Name != null) _request.AddParameter("name", Name); - if (Status != null) _request.AddParameter("status", Status); + + if (Name != null) _request.AddParameter("name", ApiInvoker.ParameterToString(Name)); // form parameter + if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // form parameter @@ -291,7 +265,6 @@ namespace io.swagger.Api { /// /// /// Pet id to delete - /// public void DeletePet (string ApiKey, long? PetId) { // create path and map variables @@ -301,14 +274,12 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter + + + if (ApiKey != null) _request.AddHeader("api_key", ApiInvoker.ParameterToString(ApiKey)); // header parameter - // header parameters, if any - if (ApiKey != null) _request.AddHeader("api_key", ApiKey); - // form parameters, if any @@ -333,7 +304,6 @@ namespace io.swagger.Api { /// ID of pet to update /// Additional data to pass to server /// file to upload - /// public void UploadFile (long? PetId, string AdditionalMetadata, byte[] File) { // create path and map variables @@ -343,16 +313,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); - // query parameters, if any + _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter - // header parameters, if any - // form parameters, if any - if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", AdditionalMetadata); - if (File != null) _request.AddFile("file", File); + + if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter + if (File != null) _request.AddFile("file", File); // form parameter diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 6d0b148ea15..4aadd02e9cc 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -38,7 +38,6 @@ namespace io.swagger.Api { /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// public Dictionary GetInventory () { // create path and map variables @@ -48,14 +47,10 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - // header parameters, if any - // form parameters, if any @@ -79,7 +74,6 @@ namespace io.swagger.Api { /// Place an order for a pet /// /// order placed for purchasing the pet - /// public Order PlaceOrder (Order Body) { // create path and map variables @@ -89,17 +83,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -122,7 +112,6 @@ namespace io.swagger.Api { /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - /// public Order GetOrderById (string OrderId) { // create path and map variables @@ -132,14 +121,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); - // query parameters, if any + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any @@ -163,7 +149,6 @@ namespace io.swagger.Api { /// Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors /// /// ID of the order that needs to be deleted - /// public void DeleteOrder (string OrderId) { // create path and map variables @@ -173,14 +158,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); - // query parameters, if any + _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 7ca6bd5b1fc..154dd099ba9 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -39,7 +39,6 @@ namespace io.swagger.Api { /// Create user This can only be done by the logged in user. /// /// Created user object - /// public void CreateUser (User Body) { // create path and map variables @@ -49,17 +48,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -81,7 +76,6 @@ namespace io.swagger.Api { /// Creates list of users with given input array /// /// List of user object - /// public void CreateUsersWithArrayInput (List Body) { // create path and map variables @@ -91,17 +85,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -123,7 +113,6 @@ namespace io.swagger.Api { /// Creates list of users with given input array /// /// List of user object - /// public void CreateUsersWithListInput (List Body) { // create path and map variables @@ -133,17 +122,13 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - - // header parameters, if any - - // form parameters, if any - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -176,14 +161,12 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - if (Username != null) _request.AddParameter("username", Username); if (Password != null) _request.AddParameter("password", Password); - // header parameters, if any + if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter + if (Password != null) _request.AddParameter("password", ApiInvoker.ParameterToString(Password)); // query parameter + - // form parameters, if any @@ -206,7 +189,6 @@ namespace io.swagger.Api { /// /// Logs out current logged in user session /// - /// public void LogoutUser () { // create path and map variables @@ -216,14 +198,10 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - // query parameters, if any - // header parameters, if any - // form parameters, if any @@ -246,8 +224,6 @@ namespace io.swagger.Api { /// Get user by user name /// /// The name that needs to be fetched. Use user1 for testing. - - /// public User GetUserByName (string Username) { // create path and map variables var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); @@ -256,14 +232,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); - // query parameters, if any + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any @@ -288,7 +261,6 @@ namespace io.swagger.Api { /// /// name that need to be deleted /// Updated user object - /// public void UpdateUser (string Username, User Body) { // create path and map variables @@ -298,17 +270,14 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); - // query parameters, if any - - // header parameters, if any - - // form parameters, if any + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); + + + + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) try { @@ -330,7 +299,6 @@ namespace io.swagger.Api { /// Delete user This can only be done by the logged in user. /// /// The name that needs to be deleted - /// public void DeleteUser (string Username) { // create path and map variables @@ -340,14 +308,11 @@ namespace io.swagger.Api { - // path (url segment) parameters _request.AddUrlSegment("format", "json"); // set format to json by default - _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); - // query parameters, if any + _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter + - // header parameters, if any - // form parameters, if any From e7b170bf3ca890bfab6abf80c9d4464b4f4bef4c Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 29 Apr 2015 16:27:08 +0800 Subject: [PATCH 14/75] better comment on csharp api, add ParameterToString to handle date --- .../src/main/resources/csharp/api.mustache | 21 +++-- .../src/main/csharp/io/swagger/Api/PetApi.cs | 77 ++++++++----------- .../main/csharp/io/swagger/Api/StoreApi.cs | 42 +++++----- .../src/main/csharp/io/swagger/Api/UserApi.cs | 75 ++++++++---------- 4 files changed, 93 insertions(+), 122 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 493a5a4de7c..c524d7ed329 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -41,15 +41,16 @@ namespace {{package}} { /// {{summary}} {{notes}} /// {{#allParams}} /// {{description}} -{{/allParams}} /// {{#returnType}}{{{returnType}}}{{/returnType}} +{{/allParams}} + /// {{#returnType}}{{{returnType}}}{{/returnType}} public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{nickname}} ({{#allParams}}{{{dataType}}} {{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) { var _request = new RestRequest("{{path}}", Method.{{httpMethod}}); - {{#requiredParams}} - // verify required param {{paramName}} is set - if ({{paramName}} == null) throw new ApiException(400, "missing required params {{paramName}}"); - {{/requiredParams}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); + {{/required}}{{/allParams}} _request.AddUrlSegment("format", "json"); // set format to json by default {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter @@ -58,17 +59,15 @@ namespace {{package}} { {{/queryParams}} {{#headerParams}} if ({{paramName}} != null) _request.AddHeader("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // header parameter {{/headerParams}} - {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}}));{{/isFile}} // form parameter + {{#formParams}}if ({{paramName}} != null) {{#isFile}}_request.AddFile("{{baseName}}", {{paramName}});{{/isFile}}{{^isFile}}_request.AddParameter("{{baseName}}", ApiInvoker.ParameterToString({{paramName}})); // form parameter{{/isFile}} {{/formParams}} - {{#bodyParam}} - _request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // HTTP request body (model) + {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter {{/bodyParam}} try { + // make the HTTP request {{#returnType}}IRestResponse response = restClient.Execute(_request); - return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}})); - //return ((object)response) as {{{returnType}}};{{/returnType}} - {{^returnType}}restClient.Execute(_request); + return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}restClient.Execute(_request); return;{{/returnType}} } catch (Exception ex) { if(ex != null) { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 52f67631966..850d9fc5c54 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -40,9 +40,7 @@ namespace io.swagger.Api { /// /// Pet object that needs to be added to the store /// - public void UpdatePet (Pet Body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); + public void UpdatePet (Pet Body) { var _request = new RestRequest("/pet", Method.PUT); @@ -53,12 +51,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -77,9 +74,7 @@ namespace io.swagger.Api { /// /// Pet object that needs to be added to the store /// - public void AddPet (Pet Body) { - // create path and map variables - var path = "/pet".Replace("{format}","json"); + public void AddPet (Pet Body) { var _request = new RestRequest("/pet", Method.POST); @@ -90,12 +85,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -113,10 +107,8 @@ namespace io.swagger.Api { /// Finds Pets by status Multiple status values can be provided with comma seperated strings /// /// Status values that need to be considered for filter - /// - public List FindPetsByStatus (List Status) { - // create path and map variables - var path = "/pet/findByStatus".Replace("{format}","json"); + /// List + public List FindPetsByStatus (List Status) { var _request = new RestRequest("/pet/findByStatus", Method.GET); @@ -131,10 +123,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - //return ((object)response) as List; - } catch (Exception ex) { if(ex != null) { return null; @@ -150,10 +141,8 @@ namespace io.swagger.Api { /// Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. /// /// Tags to filter by - /// - public List FindPetsByTags (List Tags) { - // create path and map variables - var path = "/pet/findByTags".Replace("{format}","json"); + /// List + public List FindPetsByTags (List Tags) { var _request = new RestRequest("/pet/findByTags", Method.GET); @@ -168,10 +157,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - //return ((object)response) as List; - } catch (Exception ex) { if(ex != null) { return null; @@ -187,14 +175,15 @@ namespace io.swagger.Api { /// Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions /// /// ID of pet that needs to be fetched - /// - public Pet GetPetById (long? PetId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + /// Pet + public Pet GetPetById (long? PetId) { var _request = new RestRequest("/pet/{petId}", Method.GET); + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -205,10 +194,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); - //return ((object)response) as Pet; - } catch (Exception ex) { if(ex != null) { return null; @@ -227,13 +215,14 @@ namespace io.swagger.Api { /// Updated name of the pet /// Updated status of the pet /// - public void UpdatePetWithForm (string PetId, string Name, string Status) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void UpdatePetWithForm (string PetId, string Name, string Status) { var _request = new RestRequest("/pet/{petId}", Method.POST); + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -246,7 +235,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -266,13 +255,14 @@ namespace io.swagger.Api { /// /// Pet id to delete /// - public void DeletePet (string ApiKey, long? PetId) { - // create path and map variables - var path = "/pet/{petId}".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void DeletePet (string ApiKey, long? PetId) { var _request = new RestRequest("/pet/{petId}", Method.DELETE); + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -284,7 +274,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -305,13 +295,14 @@ namespace io.swagger.Api { /// Additional data to pass to server /// file to upload /// - public void UploadFile (long? PetId, string AdditionalMetadata, byte[] File) { - // create path and map variables - var path = "/pet/{petId}/uploadImage".Replace("{format}","json").Replace("{" + "petId" + "}", apiInvoker.ParameterToString(PetId)); + public void UploadFile (long? PetId, string AdditionalMetadata, string File) { var _request = new RestRequest("/pet/{petId}/uploadImage", Method.POST); + // verify the required parameter 'PetId' is set + if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -319,12 +310,12 @@ namespace io.swagger.Api { if (AdditionalMetadata != null) _request.AddParameter("additionalMetadata", ApiInvoker.ParameterToString(AdditionalMetadata)); // form parameter - if (File != null) _request.AddFile("file", File); // form parameter + if (File != null) _request.AddFile("file", File); try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 4aadd02e9cc..98b1b5f6526 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -38,10 +38,8 @@ namespace io.swagger.Api { /// /// Returns pet inventories by status Returns a map of status codes to quantities /// - /// - public Dictionary GetInventory () { - // create path and map variables - var path = "/store/inventory".Replace("{format}","json"); + /// Dictionary + public Dictionary GetInventory () { var _request = new RestRequest("/store/inventory", Method.GET); @@ -55,10 +53,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); - //return ((object)response) as Dictionary; - } catch (Exception ex) { if(ex != null) { return null; @@ -74,10 +71,8 @@ namespace io.swagger.Api { /// Place an order for a pet /// /// order placed for purchasing the pet - /// - public Order PlaceOrder (Order Body) { - // create path and map variables - var path = "/store/order".Replace("{format}","json"); + /// Order + public Order PlaceOrder (Order Body) { var _request = new RestRequest("/store/order", Method.POST); @@ -88,15 +83,13 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - //return ((object)response) as Order; - } catch (Exception ex) { if(ex != null) { return null; @@ -112,14 +105,15 @@ namespace io.swagger.Api { /// Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions /// /// ID of pet that needs to be fetched - /// - public Order GetOrderById (string OrderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); + /// Order + public Order GetOrderById (string OrderId) { var _request = new RestRequest("/store/order/{orderId}", Method.GET); + // verify the required parameter 'OrderId' is set + if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter @@ -130,10 +124,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - //return ((object)response) as Order; - } catch (Exception ex) { if(ex != null) { return null; @@ -150,13 +143,14 @@ namespace io.swagger.Api { /// /// ID of the order that needs to be deleted /// - public void DeleteOrder (string OrderId) { - // create path and map variables - var path = "/store/order/{orderId}".Replace("{format}","json").Replace("{" + "orderId" + "}", apiInvoker.ParameterToString(OrderId)); + public void DeleteOrder (string OrderId) { var _request = new RestRequest("/store/order/{orderId}", Method.DELETE); + // verify the required parameter 'OrderId' is set + if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter @@ -167,7 +161,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 154dd099ba9..d7ccf0e9429 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -40,9 +40,7 @@ namespace io.swagger.Api { /// /// Created user object /// - public void CreateUser (User Body) { - // create path and map variables - var path = "/user".Replace("{format}","json"); + public void CreateUser (User Body) { var _request = new RestRequest("/user", Method.POST); @@ -53,12 +51,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -77,9 +74,7 @@ namespace io.swagger.Api { /// /// List of user object /// - public void CreateUsersWithArrayInput (List Body) { - // create path and map variables - var path = "/user/createWithArray".Replace("{format}","json"); + public void CreateUsersWithArrayInput (List Body) { var _request = new RestRequest("/user/createWithArray", Method.POST); @@ -90,12 +85,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -114,9 +108,7 @@ namespace io.swagger.Api { /// /// List of user object /// - public void CreateUsersWithListInput (List Body) { - // create path and map variables - var path = "/user/createWithList".Replace("{format}","json"); + public void CreateUsersWithListInput (List Body) { var _request = new RestRequest("/user/createWithList", Method.POST); @@ -127,12 +119,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -151,11 +142,8 @@ namespace io.swagger.Api { /// /// The user name for login /// The password for login in clear text - - /// - public string LoginUser (string Username, string Password) { - // create path and map variables - var path = "/user/login".Replace("{format}","json"); + /// string + public string LoginUser (string Username, string Password) { var _request = new RestRequest("/user/login", Method.GET); @@ -171,10 +159,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); - //return ((object)response) as string; - } catch (Exception ex) { if(ex != null) { return null; @@ -190,9 +177,7 @@ namespace io.swagger.Api { /// Logs out current logged in user session /// /// - public void LogoutUser () { - // create path and map variables - var path = "/user/logout".Replace("{format}","json"); + public void LogoutUser () { var _request = new RestRequest("/user/logout", Method.GET); @@ -206,7 +191,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -224,13 +209,15 @@ namespace io.swagger.Api { /// Get user by user name /// /// The name that needs to be fetched. Use user1 for testing. - public User GetUserByName (string Username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + /// User + public User GetUserByName (string Username) { var _request = new RestRequest("/user/{username}", Method.GET); + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -241,10 +228,9 @@ namespace io.swagger.Api { try { + // make the HTTP request IRestResponse response = restClient.Execute(_request); return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); - //return ((object)response) as User; - } catch (Exception ex) { if(ex != null) { return null; @@ -262,13 +248,14 @@ namespace io.swagger.Api { /// name that need to be deleted /// Updated user object /// - public void UpdateUser (string Username, User Body) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + public void UpdateUser (string Username, User Body) { var _request = new RestRequest("/user/{username}", Method.PUT); + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -276,12 +263,11 @@ namespace io.swagger.Api { - - _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // HTTP request body (model) + _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { @@ -300,13 +286,14 @@ namespace io.swagger.Api { /// /// The name that needs to be deleted /// - public void DeleteUser (string Username) { - // create path and map variables - var path = "/user/{username}".Replace("{format}","json").Replace("{" + "username" + "}", apiInvoker.ParameterToString(Username)); + public void DeleteUser (string Username) { var _request = new RestRequest("/user/{username}", Method.DELETE); + // verify the required parameter 'Username' is set + if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser"); + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -317,7 +304,7 @@ namespace io.swagger.Api { try { - + // make the HTTP request restClient.Execute(_request); return; } catch (Exception ex) { From 5082f69631d9093a1bdd01e52351f1728e3b6f4c Mon Sep 17 00:00:00 2001 From: Andrew B Date: Wed, 29 Apr 2015 22:08:27 -0700 Subject: [PATCH 15/75] Adding maven publish functionality for android client --- .../languages/AndroidClientCodegen.java | 5 +- .../resources/android-java/build.mustache | 52 +++++- .../android-java/settings.gradle.mustache | 1 + .../client/petstore/android-java/build.gradle | 48 +++++- .../petstore/android-java/settings.gradle | 1 + .../io/swagger/petstore/test/PetApiTest.java | 155 ------------------ .../swagger/petstore/test/StoreApiTest.java | 68 -------- .../io/swagger/petstore/test/UserApiTest.java | 84 ---------- 8 files changed, 94 insertions(+), 320 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache create mode 100644 samples/client/petstore/android-java/settings.gradle delete mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java delete mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java delete mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java index df9e289297f..1df5d1bb1aa 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/AndroidClientCodegen.java @@ -13,6 +13,7 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi protected String artifactVersion = "1.0.0"; protected String projectFolder = "src/main"; protected String sourceFolder = projectFolder + "/java"; + protected Boolean useAndroidMavenGradlePlugin = true; public CodegenType getTag() { return CodegenType.CLIENT; @@ -50,7 +51,9 @@ public class AndroidClientCodegen extends DefaultCodegen implements CodegenConfi additionalProperties.put("groupId", groupId); additionalProperties.put("artifactId", artifactId); additionalProperties.put("artifactVersion", artifactVersion); - + additionalProperties.put("useAndroidMavenGradlePlugin", useAndroidMavenGradlePlugin); + + supportingFiles.add(new SupportingFile("settings.gradle.mustache", "", "settings.gradle")); supportingFiles.add(new SupportingFile("build.mustache", "", "build.gradle")); supportingFiles.add(new SupportingFile("manifest.mustache", projectFolder, "AndroidManifest.xml")); supportingFiles.add(new SupportingFile("apiInvoker.mustache", diff --git a/modules/swagger-codegen/src/main/resources/android-java/build.mustache b/modules/swagger-codegen/src/main/resources/android-java/build.mustache index dfe5e1725d4..1e0b3773488 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -1,9 +1,17 @@ +{{#useAndroidMavenGradlePlugin}} +group = '{{groupId}}' +project.version = '{{artifactVersion}}' +{{/useAndroidMavenGradlePlugin}} + buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.2' + {{#useAndroidMavenGradlePlugin}} + classpath 'com.github.dcendents:android-maven-plugin:1.2' + {{/useAndroidMavenGradlePlugin}} } } @@ -13,7 +21,11 @@ allprojects { } } + apply plugin: 'com.android.library' +{{#useAndroidMavenGradlePlugin}} +apply plugin: 'com.github.dcendents.android-maven' +{{/useAndroidMavenGradlePlugin}} android { compileSdkVersion 22 @@ -22,12 +34,25 @@ android { minSdkVersion 14 targetSdkVersion 22 } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } } ext { swagger_annotations_version = "1.5.3-M1" jackson_version = "2.5.2" - httpclient_version = "4.3.3" + httpclient_android_version = "4.3.5.1" + httpcore_version = "4.4.1" + httpmime_version = "4.4.1" junit_version = "4.8.1" } @@ -36,9 +61,13 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "org.apache.httpcomponents:httpcore:$httpclient_version" - compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile "org.apache.httpcomponents:httpmime:$httpclient_version" + compile "org.apache.httpcomponents:httpclient-android:$httpclient_android_version" + compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } + compile ("org.apache.httpcomponents:httpmime:$httpmime_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } testCompile "junit:junit:$junit_version" } @@ -49,7 +78,18 @@ afterEvaluate { task.dependsOn variant.javaCompile task.from variant.javaCompile.destinationDir task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}.jar" + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" artifacts.add('archives', task); } -} \ No newline at end of file +} + +{{#useAndroidMavenGradlePlugin}} +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +artifacts { + archives sourcesJar +} +{{/useAndroidMavenGradlePlugin}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache b/modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache new file mode 100644 index 00000000000..b8fd6c4c41f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/android-java/settings.gradle.mustache @@ -0,0 +1 @@ +rootProject.name = "{{artifactId}}" \ No newline at end of file diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index dfe5e1725d4..8a74e0c8fa1 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -1,9 +1,15 @@ +group = 'io.swagger' +project.version = '1.0.0' + buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:1.2.2' + + classpath 'com.github.dcendents:android-maven-plugin:1.2' + } } @@ -13,7 +19,10 @@ allprojects { } } + + apply plugin: 'com.android.library' +apply plugin: 'com.github.dcendents.android-maven' android { compileSdkVersion 22 @@ -22,12 +31,26 @@ android { minSdkVersion 14 targetSdkVersion 22 } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + } ext { swagger_annotations_version = "1.5.3-M1" jackson_version = "2.5.2" - httpclient_version = "4.3.3" + httpclient_android_version = "4.3.5.1" + httpcore_version = "4.4.1" + httpmime_version = "4.4.1" junit_version = "4.8.1" } @@ -36,9 +59,13 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "org.apache.httpcomponents:httpcore:$httpclient_version" - compile "org.apache.httpcomponents:httpclient:$httpclient_version" - compile "org.apache.httpcomponents:httpmime:$httpclient_version" + compile "org.apache.httpcomponents:httpclient-android:$httpclient_android_version" + compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } + compile ("org.apache.httpcomponents:httpmime:$httpmime_version") { + exclude(group: 'org.apache.httpcomponents', module: 'httpclient') + } testCompile "junit:junit:$junit_version" } @@ -49,7 +76,16 @@ afterEvaluate { task.dependsOn variant.javaCompile task.from variant.javaCompile.destinationDir task.destinationDir = project.file("${project.buildDir}/outputs/jar") - task.archiveName = "${project.name}-${variant.baseName}.jar" + task.archiveName = "${project.name}-${variant.baseName}-${version}.jar" artifacts.add('archives', task); } -} \ No newline at end of file +} + +task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' +} + +artifacts { + archives sourcesJar +} diff --git a/samples/client/petstore/android-java/settings.gradle b/samples/client/petstore/android-java/settings.gradle new file mode 100644 index 00000000000..6a6796bf9fe --- /dev/null +++ b/samples/client/petstore/android-java/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "swagger-android-client" \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java deleted file mode 100644 index 97f3b5f8006..00000000000 --- a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ /dev/null @@ -1,155 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.client.ApiException; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -import java.util.*; -import java.io.*; - -import static org.junit.Assert.*; -import org.junit.*; - -public class PetApiTest { - PetApi api = null; - - @Before - public void setup() { - api = new PetApi(); - } - - @Test - public void testCreateAndGetPet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testUpdatePet() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - - api.updatePet(pet); - - Pet fetched = api.getPetById(pet.getId()); - assertNotNull(fetched); - assertEquals(pet.getId(), fetched.getId()); - assertNotNull(fetched.getCategory()); - assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); - } - - @Test - public void testFindPetsByStatus() throws Exception { - Pet pet = createRandomPet(); - pet.setName("programmer"); - pet.setStatus(Pet.StatusEnum.available); - - api.updatePet(pet); - - List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); - assertNotNull(pets); - - boolean found = false; - for(Pet fetched : pets) { - if(fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - - assertTrue(found); - } - - @Test - public void testFindPetsByTags() throws Exception { - Pet pet = createRandomPet(); - pet.setName("monster"); - pet.setStatus(Pet.StatusEnum.available); - - List tags = new ArrayList(); - Tag tag1 = new Tag(); - tag1.setName("friendly"); - tags.add(tag1); - pet.setTags(tags); - - api.updatePet(pet); - - List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); - assertNotNull(pets); - - boolean found = false; - for(Pet fetched : pets) { - if(fetched.getId().equals(pet.getId())) { - found = true; - break; - } - } - assertTrue(found); - } - - @Test - public void testUpdatePetWithForm() throws Exception { - Pet pet = createRandomPet(); - pet.setName("frank"); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - - api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); - Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), fetched.getName()); - } - - @Test - public void testDeletePet() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - Pet fetched = api.getPetById(pet.getId()); - api.deletePet(null, fetched.getId()); - - try { - fetched = api.getPetById(fetched.getId()); - fail("expected an error"); - } - catch (ApiException e) { - assertEquals(404, e.getCode()); - } - } - - @Test - public void testUploadFile() throws Exception { - Pet pet = createRandomPet(); - api.addPet(pet); - - File file = new File("hello.txt"); - BufferedWriter writer = new BufferedWriter(new FileWriter(file)); - writer.write("Hello world!"); - writer.close(); - - api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); - } - - private Pet createRandomPet() { - Pet pet = new Pet(); - pet.setId(System.currentTimeMillis()); - pet.setName("gorilla"); - - Category category = new Category(); - category.setName("really-happy"); - - pet.setCategory(category); - pet.setStatus(Pet.StatusEnum.available); - List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); - pet.setPhotoUrls(photos); - - return pet; - } -} \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java deleted file mode 100644 index 25a52009b9e..00000000000 --- a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java +++ /dev/null @@ -1,68 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.client.ApiException; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -import java.util.*; -import java.io.*; - -import static org.junit.Assert.*; -import org.junit.*; - -public class StoreApiTest { - StoreApi api = null; - - @Before - public void setup() { - api = new StoreApi(); - } - - @Test - public void testGetInventory() throws Exception { - Map inventory = api.getInventory(); - assertTrue(inventory.keySet().size() > 0); - } - - @Test - public void testPlaceOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(String.valueOf(order.getId())); - assertEquals(order.getId(), fetched.getId()); - assertEquals(order.getPetId(), fetched.getPetId()); - assertEquals(order.getQuantity(), fetched.getQuantity()); - } - - @Test - public void testDeleteOrder() throws Exception { - Order order = createOrder(); - api.placeOrder(order); - - Order fetched = api.getOrderById(String.valueOf(order.getId())); - assertEquals(fetched.getId(), order.getId()); - - api.deleteOrder(String.valueOf(order.getId())); - - try { - api.getOrderById(String.valueOf(order.getId())); - // fail("expected an error"); - } - catch (ApiException e) { - // ok - } - } - - private Order createOrder() { - Order order = new Order(); - order.setId(new Long(System.currentTimeMillis())); - order.setPetId(new Long(200)); - order.setQuantity(new Integer(13)); - order.setShipDate(new java.util.Date()); - order.setStatus(Order.StatusEnum.placed); - order.setComplete(true); - - return order; - } -} \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java deleted file mode 100644 index 9d683faab7a..00000000000 --- a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java +++ /dev/null @@ -1,84 +0,0 @@ -package io.swagger.petstore.test; - -import io.swagger.client.ApiException; -import io.swagger.client.api.*; -import io.swagger.client.model.*; - -import java.util.*; -import java.io.*; - -import static org.junit.Assert.*; -import org.junit.*; - -public class UserApiTest { - UserApi api = null; - - @Before - public void setup() { - api = new UserApi(); - } - - @Test - public void testCreateUser() throws Exception { - User user = createUser(); - - api.createUser(user); - - User fetched = api.getUserByName(user.getUsername()); - assertEquals(user.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithArray() throws Exception { - User user1 = createUser(); - user1.setUsername("abc123"); - User user2 = createUser(); - user2.setUsername("123abc"); - - api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testCreateUsersWithList() throws Exception { - User user1 = createUser(); - user1.setUsername("abc123"); - User user2 = createUser(); - user2.setUsername("123abc"); - - api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); - - User fetched = api.getUserByName(user1.getUsername()); - assertEquals(user1.getId(), fetched.getId()); - } - - @Test - public void testLoginUser() throws Exception { - User user = createUser(); - api.createUser(user); - - String token = api.loginUser(user.getUsername(), user.getPassword()); - assertTrue(token.startsWith("logged in user session:")); - } - - @Test - public void logoutUser() throws Exception { - api.logoutUser(); - } - - private User createUser() { - User user = new User(); - user.setId(System.currentTimeMillis()); - user.setUsername("fred"); - user.setFirstName("Fred"); - user.setLastName("Meyer"); - user.setEmail("fred@fredmeyer.com"); - user.setPassword("xxXXxx"); - user.setPhone("408-867-5309"); - user.setUserStatus(123); - - return user; - } -} \ No newline at end of file From 6be2c06ed395f3c014c90e35079c25b59746e5d0 Mon Sep 17 00:00:00 2001 From: who Date: Thu, 30 Apr 2015 10:34:43 -0700 Subject: [PATCH 16/75] Adding maven publish functionality for android client --- .../src/main/resources/android-java/build.mustache | 4 ++-- samples/client/petstore/android-java/build.gradle | 6 ++---- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/android-java/build.mustache b/modules/swagger-codegen/src/main/resources/android-java/build.mustache index 1e0b3773488..ee38aa210b4 100644 --- a/modules/swagger-codegen/src/main/resources/android-java/build.mustache +++ b/modules/swagger-codegen/src/main/resources/android-java/build.mustache @@ -50,7 +50,7 @@ android { ext { swagger_annotations_version = "1.5.3-M1" jackson_version = "2.5.2" - httpclient_android_version = "4.3.5.1" + httpclient_version = "4.4.1" httpcore_version = "4.4.1" httpmime_version = "4.4.1" junit_version = "4.8.1" @@ -61,7 +61,7 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "org.apache.httpcomponents:httpclient-android:$httpclient_android_version" + compile "org.apache.httpcomponents:httpclient:$httpclient_version" compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } diff --git a/samples/client/petstore/android-java/build.gradle b/samples/client/petstore/android-java/build.gradle index 8a74e0c8fa1..72494590b7e 100644 --- a/samples/client/petstore/android-java/build.gradle +++ b/samples/client/petstore/android-java/build.gradle @@ -20,7 +20,6 @@ allprojects { } - apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' @@ -42,13 +41,12 @@ android { } } } - } ext { swagger_annotations_version = "1.5.3-M1" jackson_version = "2.5.2" - httpclient_android_version = "4.3.5.1" + httpclient_version = "4.4.1" httpcore_version = "4.4.1" httpmime_version = "4.4.1" junit_version = "4.8.1" @@ -59,7 +57,7 @@ dependencies { compile "com.fasterxml.jackson.core:jackson-core:$jackson_version" compile "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" compile "com.fasterxml.jackson.core:jackson-databind:$jackson_version" - compile "org.apache.httpcomponents:httpclient-android:$httpclient_android_version" + compile "org.apache.httpcomponents:httpclient:$httpclient_version" compile ("org.apache.httpcomponents:httpcore:$httpcore_version") { exclude(group: 'org.apache.httpcomponents', module: 'httpclient') } From b94eb443eabea0ae9c5bfb9763a474c347643022 Mon Sep 17 00:00:00 2001 From: who Date: Thu, 30 Apr 2015 12:52:21 -0700 Subject: [PATCH 17/75] Adding some tests that were accidentally deleted --- .../io/swagger/petstore/test/PetApiTest.java | 155 ++++++++++++++++++ .../swagger/petstore/test/StoreApiTest.java | 68 ++++++++ .../io/swagger/petstore/test/UserApiTest.java | 84 ++++++++++ 3 files changed, 307 insertions(+) create mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java create mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java create mode 100644 samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java new file mode 100644 index 00000000000..97f3b5f8006 --- /dev/null +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -0,0 +1,155 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.*; +import java.io.*; + +import static org.junit.Assert.*; +import org.junit.*; + +public class PetApiTest { + PetApi api = null; + + @Before + public void setup() { + api = new PetApi(); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertNotNull(fetched); + assertEquals(pet.getId(), fetched.getId()); + assertNotNull(fetched.getCategory()); + assertEquals(fetched.getCategory().getName(), pet.getCategory().getName()); + } + + @Test + public void testFindPetsByStatus() throws Exception { + Pet pet = createRandomPet(); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.available); + + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList(new String[]{"available"})); + assertNotNull(pets); + + boolean found = false; + for(Pet fetched : pets) { + if(fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + } + + @Test + public void testFindPetsByTags() throws Exception { + Pet pet = createRandomPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.available); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags(Arrays.asList(new String[]{"friendly"})); + assertNotNull(pets); + + boolean found = false; + for(Pet fetched : pets) { + if(fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createRandomPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), fetched.getName()); + } + + @Test + public void testDeletePet() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(null, fetched.getId()); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } + catch (ApiException e) { + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createRandomPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + } + + private Pet createRandomPet() { + Pet pet = new Pet(); + pet.setId(System.currentTimeMillis()); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.available); + List photos = Arrays.asList(new String[]{"http://foo.bar.com/1", "http://foo.bar.com/2"}); + pet.setPhotoUrls(photos); + + return pet; + } +} \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java new file mode 100644 index 00000000000..25a52009b9e --- /dev/null +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/StoreApiTest.java @@ -0,0 +1,68 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.*; +import java.io.*; + +import static org.junit.Assert.*; +import org.junit.*; + +public class StoreApiTest { + StoreApi api = null; + + @Before + public void setup() { + api = new StoreApi(); + } + + @Test + public void testGetInventory() throws Exception { + Map inventory = api.getInventory(); + assertTrue(inventory.keySet().size() > 0); + } + + @Test + public void testPlaceOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(order.getId(), fetched.getId()); + assertEquals(order.getPetId(), fetched.getPetId()); + assertEquals(order.getQuantity(), fetched.getQuantity()); + } + + @Test + public void testDeleteOrder() throws Exception { + Order order = createOrder(); + api.placeOrder(order); + + Order fetched = api.getOrderById(String.valueOf(order.getId())); + assertEquals(fetched.getId(), order.getId()); + + api.deleteOrder(String.valueOf(order.getId())); + + try { + api.getOrderById(String.valueOf(order.getId())); + // fail("expected an error"); + } + catch (ApiException e) { + // ok + } + } + + private Order createOrder() { + Order order = new Order(); + order.setId(new Long(System.currentTimeMillis())); + order.setPetId(new Long(200)); + order.setQuantity(new Integer(13)); + order.setShipDate(new java.util.Date()); + order.setStatus(Order.StatusEnum.placed); + order.setComplete(true); + + return order; + } +} \ No newline at end of file diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java new file mode 100644 index 00000000000..9d683faab7a --- /dev/null +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/UserApiTest.java @@ -0,0 +1,84 @@ +package io.swagger.petstore.test; + +import io.swagger.client.ApiException; +import io.swagger.client.api.*; +import io.swagger.client.model.*; + +import java.util.*; +import java.io.*; + +import static org.junit.Assert.*; +import org.junit.*; + +public class UserApiTest { + UserApi api = null; + + @Before + public void setup() { + api = new UserApi(); + } + + @Test + public void testCreateUser() throws Exception { + User user = createUser(); + + api.createUser(user); + + User fetched = api.getUserByName(user.getUsername()); + assertEquals(user.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithArray() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithArrayInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testCreateUsersWithList() throws Exception { + User user1 = createUser(); + user1.setUsername("abc123"); + User user2 = createUser(); + user2.setUsername("123abc"); + + api.createUsersWithListInput(Arrays.asList(new User[]{user1, user2})); + + User fetched = api.getUserByName(user1.getUsername()); + assertEquals(user1.getId(), fetched.getId()); + } + + @Test + public void testLoginUser() throws Exception { + User user = createUser(); + api.createUser(user); + + String token = api.loginUser(user.getUsername(), user.getPassword()); + assertTrue(token.startsWith("logged in user session:")); + } + + @Test + public void logoutUser() throws Exception { + api.logoutUser(); + } + + private User createUser() { + User user = new User(); + user.setId(System.currentTimeMillis()); + user.setUsername("fred"); + user.setFirstName("Fred"); + user.setLastName("Meyer"); + user.setEmail("fred@fredmeyer.com"); + user.setPassword("xxXXxx"); + user.setPhone("408-867-5309"); + user.setUserStatus(123); + + return user; + } +} \ No newline at end of file From 321dfb73118a1ccd7c40ff3d379f86234afbf6d3 Mon Sep 17 00:00:00 2001 From: Fake Bob Dobbs Date: Mon, 4 May 2015 17:04:09 -0400 Subject: [PATCH 18/75] For SpringMVC, RequestHeader annotations are not setting the required attribute, even when required is false (RequestHeader uses default of true). This change always sets the required param --- .../src/main/resources/JavaSpringMVC/headerParams.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache index dd0ea1ad4ce..229717ddaa9 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestHeader("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{paramName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} From 2edfb96c36e769e22057bf56f5e42b0dd842077c Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 7 May 2015 12:02:25 -0700 Subject: [PATCH 19/75] swagger codegen should honor global mime types --- .../swagger/codegen/DefaultCodegen.java | 10 +++++--- .../swagger/codegen/DefaultGenerator.java | 25 +++++++++++++++++++ .../src/main/resources/JavaJaxRS/api.mustache | 2 ++ 3 files changed, 33 insertions(+), 4 deletions(-) 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 6f51374c536..6275421d773 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 @@ -692,11 +692,13 @@ public class DefaultCodegen { for(String key: operation.getConsumes()) { Map mediaType = new HashMap(); mediaType.put("mediaType", key); - if (count < operation.getConsumes().size()) - mediaType.put("hasMore", "true"); - else - mediaType.put("hasMore", null); count += 1; + if (count < operation.getConsumes().size()) { + mediaType.put("hasMore", "true"); + } + else { + mediaType.put("hasMore", null); + } c.add(mediaType); } op.consumes = c; 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 17509973215..634a93c30cd 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 @@ -165,6 +165,9 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); + processMimeTypes(swagger.getConsumes(), operation, "consumes"); + processMimeTypes(swagger.getProduces(), operation, "produces"); + allOperations.add(new HashMap(operation)); for (int i = 0; i < allOperations.size(); i++) { @@ -291,6 +294,28 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { return files; } + private void processMimeTypes(List mimeTypeList, Map operation, String source) { + if(mimeTypeList != null && mimeTypeList.size() > 0) { + List> c = new ArrayList>(); + int count = 0; + for(String key: mimeTypeList) { + Map mediaType = new HashMap(); + mediaType.put("mediaType", key); + count += 1; + if (count < mimeTypeList.size()) { + mediaType.put("hasMore", "true"); + } + else { + mediaType.put("hasMore", null); + } + c.add(mediaType); + } + operation.put(source, c); + String flagFieldName = "has" + source.substring(0, 1).toUpperCase() + source.substring(1); + operation.put(flagFieldName, true); + } + } + public Map> processPaths(Map paths) { Map> ops = new HashMap>(); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index b5ebb30f193..832a8bb8243 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -21,6 +21,8 @@ import javax.ws.rs.core.Response; import javax.ws.rs.*; @Path("/{{baseName}}") +{{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} +{{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} @com.wordnik.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") {{#operations}} public class {{classname}} { From 2eeb96116d8e698025dca093e1500a0e4b42c241 Mon Sep 17 00:00:00 2001 From: russellb337 Date: Thu, 7 May 2015 12:16:44 -0700 Subject: [PATCH 20/75] simplifying diff --- .../java/com/wordnik/swagger/codegen/DefaultCodegen.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 6275421d773..74adbe945f0 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 @@ -693,12 +693,10 @@ public class DefaultCodegen { Map mediaType = new HashMap(); mediaType.put("mediaType", key); count += 1; - if (count < operation.getConsumes().size()) { + if (count < operation.getConsumes().size()) mediaType.put("hasMore", "true"); - } - else { + else mediaType.put("hasMore", null); - } c.add(mediaType); } op.consumes = c; From 2f5f2b367b18773d5f6324c4ad564d073770d8f9 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 12 May 2015 12:45:59 +0800 Subject: [PATCH 21/75] update package name to confirm to csharp convention, fix default header --- .../languages/CSharpClientCodegen.java | 6 +-- .../src/main/resources/csharp/api.mustache | 6 +++ samples/client/petstore/csharp/compile.bat | 2 +- .../src/main/csharp/io/swagger/Api/PetApi.cs | 54 +++++++++++++++++-- .../main/csharp/io/swagger/Api/StoreApi.cs | 30 +++++++++-- .../src/main/csharp/io/swagger/Api/UserApi.cs | 54 +++++++++++++++++-- .../main/csharp/io/swagger/Model/Category.cs | 2 +- .../src/main/csharp/io/swagger/Model/Order.cs | 2 +- .../src/main/csharp/io/swagger/Model/Pet.cs | 2 +- .../src/main/csharp/io/swagger/Model/Tag.cs | 2 +- .../src/main/csharp/io/swagger/Model/User.cs | 2 +- .../csharp/io/swagger/client/ApiException.cs | 2 +- .../csharp/io/swagger/client/ApiInvoker.cs | 2 +- 13 files changed, 146 insertions(+), 20 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java index 13a16747483..5060899d498 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/CSharpClientCodegen.java @@ -7,7 +7,7 @@ import java.util.*; import java.io.File; public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "io.swagger.client"; + protected String invokerPackage = "IO.Swagger.Client"; protected String groupId = "io.swagger"; protected String artifactId = "swagger-csharp-client"; protected String artifactVersion = "1.0.0"; @@ -31,8 +31,8 @@ public class CSharpClientCodegen extends DefaultCodegen implements CodegenConfig modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("api.mustache", ".cs"); templateDir = "csharp"; - apiPackage = "io.swagger.Api"; - modelPackage = "io.swagger.Model"; + apiPackage = "IO.Swagger.Api"; + modelPackage = "IO.Swagger.Model"; reservedWords = new HashSet ( Arrays.asList( diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index c524d7ed329..6e06087c1ae 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -52,6 +52,12 @@ namespace {{package}} { if ({{paramName}} == null) throw new ApiException(400, "Missing required parameter '{{paramName}}' when calling {{nickname}}"); {{/required}}{{/allParams}} + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default {{#pathParams}}_request.AddUrlSegment("{{baseName}}", ApiInvoker.ParameterToString({{{paramName}}})); // path (url segment) parameter {{/pathParams}} diff --git a/samples/client/petstore/csharp/compile.bat b/samples/client/petstore/csharp/compile.bat index 18a85febb70..1ced2568767 100644 --- a/samples/client/petstore/csharp/compile.bat +++ b/samples/client/petstore/csharp/compile.bat @@ -1,2 +1,2 @@ SET CSCPATH=%SYSTEMROOT%\Microsoft.NET\Framework\v4.0.30319 -%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/io.swagger.client.dll /recurse:src\*.cs /doc:bin/io.swagger.client.xml \ No newline at end of file +%CSCPATH%\csc /reference:bin/Newtonsoft.Json.dll /target:library /out:bin/IO.Swagger.Client.dll /recurse:src\*.cs /doc:bin/IO.Swagger.Client.xml \ No newline at end of file diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 850d9fc5c54..91e650b2bae 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using RestSharp; -using io.swagger.client; -using io.swagger.Model; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class PetApi { string basePath; @@ -46,6 +46,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -80,6 +86,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -114,6 +126,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default if (Status != null) _request.AddParameter("status", ApiInvoker.ParameterToString(Status)); // query parameter @@ -148,6 +166,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default if (Tags != null) _request.AddParameter("tags", ApiInvoker.ParameterToString(Tags)); // query parameter @@ -185,6 +209,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling GetPetById"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -224,6 +254,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UpdatePetWithForm"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -264,6 +300,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling DeletePet"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter @@ -304,6 +346,12 @@ namespace io.swagger.Api { if (PetId == null) throw new ApiException(400, "Missing required parameter 'PetId' when calling UploadFile"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("petId", ApiInvoker.ParameterToString(PetId)); // path (url segment) parameter diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 98b1b5f6526..1f4b4441ae1 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using RestSharp; -using io.swagger.client; -using io.swagger.Model; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class StoreApi { string basePath; @@ -45,6 +45,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -78,6 +84,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -115,6 +127,12 @@ namespace io.swagger.Api { if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling GetOrderById"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter @@ -152,6 +170,12 @@ namespace io.swagger.Api { if (OrderId == null) throw new ApiException(400, "Missing required parameter 'OrderId' when calling DeleteOrder"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("orderId", ApiInvoker.ParameterToString(OrderId)); // path (url segment) parameter diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index d7ccf0e9429..1dd08f7c697 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -1,10 +1,10 @@ using System; using System.Collections.Generic; using RestSharp; -using io.swagger.client; -using io.swagger.Model; +using IO.Swagger.Client; +using IO.Swagger.Model; -namespace io.swagger.Api { +namespace IO.Swagger.Api { public class UserApi { string basePath; @@ -46,6 +46,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -80,6 +86,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -114,6 +126,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -149,6 +167,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default if (Username != null) _request.AddParameter("username", ApiInvoker.ParameterToString(Username)); // query parameter @@ -183,6 +207,12 @@ namespace io.swagger.Api { + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default @@ -219,6 +249,12 @@ namespace io.swagger.Api { if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling GetUserByName"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -257,6 +293,12 @@ namespace io.swagger.Api { if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling UpdateUser"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter @@ -295,6 +337,12 @@ namespace io.swagger.Api { if (Username == null) throw new ApiException(400, "Missing required parameter 'Username' when calling DeleteUser"); + // add default header, if any + foreach(KeyValuePair defaultHeader in ApiInvoker.GetDefaultHeader()) + { + _request.AddHeader(defaultHeader.Key, defaultHeader.Value); + } + _request.AddUrlSegment("format", "json"); // set format to json by default _request.AddUrlSegment("username", ApiInvoker.ParameterToString(Username)); // path (url segment) parameter diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs index 7b13e16523a..04867ca365f 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Category.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Category { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs index 3d67de0a82b..cf773a7a150 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Order.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Order { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs index a00f8729d3f..41f4081d371 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Pet.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Pet { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs index b0c08431472..44b6ae29297 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/Tag.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class Tag { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs index 37931c6fbe4..0fb3bfc86ce 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Model/User.cs @@ -4,7 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; -namespace io.swagger.Model { +namespace IO.Swagger.Model { [DataContract] public class User { diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index 01648d1607c..ffa49217bb8 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs @@ -1,6 +1,6 @@ using System; -namespace io.swagger.client { +namespace IO.Swagger.Client { public class ApiException : Exception { private int errorCode = 0; diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs index abdfad1ae3b..144027b2314 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiInvoker.cs @@ -6,7 +6,7 @@ using System.Net; using System.Text; using Newtonsoft.Json; -namespace io.swagger.client { +namespace IO.Swagger.Client { public class ApiInvoker { private static Dictionary defaultHeaderMap = new Dictionary(); From 75b39e812ef3a692a4ea86b9b055a3cfdea96337 Mon Sep 17 00:00:00 2001 From: Ole Lensmar Date: Tue, 12 May 2015 13:18:35 -0400 Subject: [PATCH 22/75] refactored to create separate serviceinterface, implementation and corresponding factory. JaxRs class uses the factory to find the implementation. Also fixed possibility for a code generator to control which API files that should be overwritten --- .../swagger/codegen/CodegenConfig.java | 4 ++ .../swagger/codegen/DefaultCodegen.java | 9 +++++ .../swagger/codegen/DefaultGenerator.java | 10 ++--- .../codegen/languages/JavaClientCodegen.java | 1 - .../codegen/languages/JaxRSServerCodegen.java | 30 ++++++++++++++ .../src/main/resources/JavaJaxRS/api.mustache | 39 +++++++++++-------- .../resources/JavaJaxRS/apiService.mustache | 28 +++++++++++++ .../JavaJaxRS/apiServiceFactory.mustache | 14 +++++++ .../JavaJaxRS/apiServiceImpl.mustache | 31 +++++++++++++++ .../src/main/resources/JavaJaxRS/pom.mustache | 2 +- .../JavaJaxRS/serviceBodyParams.mustache | 1 + .../JavaJaxRS/serviceFormParams.mustache | 1 + .../JavaJaxRS/serviceHeaderParams.mustache | 1 + .../JavaJaxRS/servicePathParams.mustache | 1 + .../JavaJaxRS/serviceQueryParams.mustache | 1 + 15 files changed, 149 insertions(+), 24 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache create mode 100644 modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java index ca73a819fb5..167610fcd70 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenConfig.java @@ -56,4 +56,8 @@ public interface CodegenConfig { Map postProcessModels(Map objs); Map postProcessOperations(Map objs); Map postProcessSupportingFileData(Map objs); + + String apiFilename(String templateName, String tag); + + boolean shouldOverwrite(String filename); } 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 6f51374c536..0da4560f4b0 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 @@ -1169,4 +1169,13 @@ public class DefaultCodegen { } + public String apiFilename(String templateName, String tag) + { + String suffix = apiTemplateFiles().get(templateName); + return apiFileFolder() + File.separator + toApiFilename(tag) + suffix; + } + + public boolean shouldOverwrite( String filename ){ + return true; + } } 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 17509973215..7c1792a88ad 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 @@ -175,11 +175,11 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { } for (String templateName : config.apiTemplateFiles().keySet()) { - String suffix = config.apiTemplateFiles().get(templateName); - String filename = config.apiFileFolder() + - File.separator + - config.toApiFilename(tag) + - suffix; + + String filename = config.apiFilename( templateName, tag ); + if( new File( filename ).exists() && !config.shouldOverwrite( filename )){ + continue; + } String template = readTemplate(config.templateDir() + File.separator + templateName); Template tmpl = Mustache.compiler() diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java index 39ed9dfe540..7c0ac7422ff 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JavaClientCodegen.java @@ -130,7 +130,6 @@ public class JavaClientCodegen extends DefaultCodegen implements CodegenConfig { return toModelName(name); } - @Override public String getTypeDeclaration(Property p) { if(p instanceof ArrayProperty) { diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java index e6447b9484b..f4f16ca63f9 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -31,9 +31,14 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf public JaxRSServerCodegen() { super(); + outputFolder = "generated-code/javaJaxRS"; modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); + apiTemplateFiles.put("apiService.mustache", ".java"); + apiTemplateFiles.put("apiServiceImpl.mustache", ".java"); + apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); + templateDir = "JavaJaxRS"; apiPackage = "io.swagger.api"; modelPackage = "io.swagger.model"; @@ -146,4 +151,29 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf } return objs; } + + @Override + public String apiFilename(String templateName, String tag) { + + String result = super.apiFilename(templateName, tag); + + if( templateName.endsWith( "Impl.mustache")){ + int ix = result.lastIndexOf( '/' ); + result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java"; + } else if( templateName.endsWith( "Service.mustache")){ + int ix = result.lastIndexOf( '.' ); + result = result.substring( 0, ix ) + "Service.java"; + } + else if( templateName.endsWith( "Factory.mustache")){ + int ix = result.lastIndexOf( '/' ); + result = result.substring( 0, ix ) + "/factories" + result.substring( ix, result.length()-5 ) + "ServiceFactory.java"; + } + + return result; + } + + public boolean shouldOverwrite( String filename ){ + + return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.java"); + } } \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache index b5ebb30f193..3aa1a8d20e3 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/api.mustache @@ -1,6 +1,8 @@ package {{package}}; import {{modelPackage}}.*; +import {{package}}.{{classname}}Service; +import {{package}}.factories.{{classname}}ServiceFactory; import com.wordnik.swagger.annotations.ApiParam; @@ -23,24 +25,27 @@ import javax.ws.rs.*; @Path("/{{baseName}}") @com.wordnik.swagger.annotations.Api(value = "/{{baseName}}", description = "the {{baseName}} API") {{#operations}} -public class {{classname}} { - {{#operation}} - @{{httpMethod}} - {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} - {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} - {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} - @com.wordnik.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) - @com.wordnik.swagger.annotations.ApiResponses(value = { {{#responses}} - @com.wordnik.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, - {{/hasMore}}{{/responses}} }) +public class {{classname}} { - public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, + private final {{classname}}Service delegate = {{classname}}ServiceFactory.get{{classname}}(); + +{{#operation}} + @{{httpMethod}} + {{#subresourceOperation}}@Path("{{path}}"){{/subresourceOperation}} + {{#hasConsumes}}@Consumes({ {{#consumes}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} }){{/hasConsumes}} + {{#hasProduces}}@Produces({ {{#produces}}"{{mediaType}}"{{#hasMore}}, {{/hasMore}}{{/produces}} }){{/hasProduces}} + @com.wordnik.swagger.annotations.ApiOperation(value = "{{{summary}}}", notes = "{{{notes}}}", response = {{{returnType}}}.class{{#returnContainer}}, responseContainer = "{{{returnContainer}}}"{{/returnContainer}}) + @com.wordnik.swagger.annotations.ApiResponses(value = { {{#responses}} + @com.wordnik.swagger.annotations.ApiResponse(code = {{{code}}}, message = "{{{message}}}"){{#hasMore}}, + {{/hasMore}}{{/responses}} }) + + public Response {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) - throws NotFoundException { - // do some magic! - return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); - } - - {{/operation}} + throws NotFoundException { + // do some magic! + return delegate.{{nickname}}({{#allParams}}{{#isFile}}fileDetail{{/isFile}}{{^isFile}}{{paramName}}{{/isFile}}{{#hasMore}},{{/hasMore}}{{/allParams}}); + } +{{/operation}} } {{/operations}} + diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache new file mode 100644 index 00000000000..53f420d620a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -0,0 +1,28 @@ +package {{package}}; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +{{#operations}} +public interface {{classname}}Service { + {{#operation}} + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException; + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache new file mode 100644 index 00000000000..a434311d285 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceFactory.mustache @@ -0,0 +1,14 @@ +package {{package}}.factories; + +import {{package}}.{{classname}}Service; +import {{package}}.impl.{{classname}}ServiceImpl; + +public class {{classname}}ServiceFactory { + + private final static {{classname}}Service service = new {{classname}}ServiceImpl(); + + public static {{classname}}Service get{{classname}}() + { + return service; + } +} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache new file mode 100644 index 00000000000..185de10e439 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -0,0 +1,31 @@ +package {{package}}.impl; + +import {{package}}.*; +import {{modelPackage}}.*; + +import com.sun.jersey.multipart.FormDataParam; + +{{#imports}}import {{import}}; +{{/imports}} + +import java.util.List; +import {{package}}.NotFoundException; + +import java.io.InputStream; + +import com.sun.jersey.core.header.FormDataContentDisposition; +import com.sun.jersey.multipart.FormDataParam; + +import javax.ws.rs.core.Response; + +{{#operations}} +public class {{classname}}ServiceImpl implements {{classname}}Service { + {{#operation}} + public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + {{/operation}} +} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index d9e3b90bc95..1bd168af747 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -129,7 +129,7 @@ - 2.1.1-M2-SNAPSHOT + 1.5.2-M2-SNAPSHOT 9.2.9.v20150224 1.13 1.6.3 diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache new file mode 100644 index 00000000000..c7d1abfe527 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceBodyParams.mustache @@ -0,0 +1 @@ +{{#isBodyParam}}{{{dataType}}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache new file mode 100644 index 00000000000..e44ab167e8f --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceFormParams.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#notFile}}{{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}FormDataContentDisposition fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache new file mode 100644 index 00000000000..bd03573d196 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceHeaderParams.mustache @@ -0,0 +1 @@ +{{#isHeaderParam}}{{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache new file mode 100644 index 00000000000..6829cf8c7a6 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/servicePathParams.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{{dataType}}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache new file mode 100644 index 00000000000..ff79730471d --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/serviceQueryParams.mustache @@ -0,0 +1 @@ +{{#isQueryParam}}{{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file From adcd0f4bb8d020efe06881a3f7eb4f649da2182b Mon Sep 17 00:00:00 2001 From: Ole Lensmar Date: Wed, 13 May 2015 15:58:20 -0700 Subject: [PATCH 23/75] changed interface to abstract class instead so we can use Override annotation to warn if we get dead methods when the definitions changes --- .../src/main/resources/JavaJaxRS/apiService.mustache | 4 ++-- .../src/main/resources/JavaJaxRS/apiServiceImpl.mustache | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache index 53f420d620a..43e7cd8685c 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiService.mustache @@ -19,9 +19,9 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; {{#operations}} -public interface {{classname}}Service { +public abstract class {{classname}}Service { {{#operation}} - public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) + public abstract Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) throws NotFoundException; {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index 185de10e439..d49fa4952a2 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -19,8 +19,9 @@ import com.sun.jersey.multipart.FormDataParam; import javax.ws.rs.core.Response; {{#operations}} -public class {{classname}}ServiceImpl implements {{classname}}Service { +public class {{classname}}ServiceImpl extends {{classname}}Service { {{#operation}} + @Override public Response {{nickname}}({{#allParams}}{{>serviceQueryParams}}{{>servicePathParams}}{{>serviceHeaderParams}}{{>serviceBodyParams}}{{>serviceFormParams}}{{#hasMore}},{{/hasMore}}{{/allParams}}) throws NotFoundException { // do some magic! From 86e48ceef8120fa5b9ecbae397c038f7446bc9b1 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Thu, 14 May 2015 10:45:05 +0800 Subject: [PATCH 24/75] refactor python client using urllib3 --- .../languages/PythonClientCodegen.java | 7 +- .../resources/python/__init__api.mustache | 15 + .../resources/python/__init__model.mustache | 2 + .../resources/python/__init__package.mustache | 4 +- .../src/main/resources/python/api.mustache | 95 +-- .../src/main/resources/python/model.mustache | 17 +- .../src/main/resources/python/rest.mustache | 223 +++++++ .../src/main/resources/python/setup.mustache | 2 +- .../main/resources/python/swagger.mustache | 322 +++++----- .../SwaggerPetstore/__init__.py | 8 +- .../SwaggerPetstore/apis/__init__.py | 19 + .../SwaggerPetstore/apis/pet_api.py | 426 ++++++++++++++ .../SwaggerPetstore/apis/store_api.py | 226 +++++++ .../SwaggerPetstore/apis/user_api.py | 416 +++++++++++++ .../SwaggerPetstore/models/__init__.py | 2 + .../SwaggerPetstore/models/category.py | 21 +- .../SwaggerPetstore/models/order.py | 25 +- .../SwaggerPetstore/models/pet.py | 21 +- .../SwaggerPetstore/models/tag.py | 21 +- .../SwaggerPetstore/models/user.py | 21 +- .../SwaggerPetstore/pet_api.py | 551 ------------------ .../SwaggerPetstore/rest.py | 223 +++++++ .../SwaggerPetstore/store_api.py | 289 --------- .../SwaggerPetstore/swagger.py | 322 +++++----- .../SwaggerPetstore/user_api.py | 526 ----------------- .../python/SwaggerPetstore-python/setup.py | 2 +- .../tests/test_pet_api.py | 16 +- 27 files changed, 1983 insertions(+), 1839 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/python/__init__api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/python/rest.mustache create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py delete mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index bbb07b1592a..7a866dd13b3 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -34,13 +34,12 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig apiTemplateFiles.put("api.mustache", ".py"); templateDir = "python"; - apiPackage = invokerPackage; + apiPackage = invokerPackage + ".apis"; modelPackage = invokerPackage + ".models"; languageSpecificPrimitives.clear(); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("float"); - languageSpecificPrimitives.add("long"); languageSpecificPrimitives.add("list"); languageSpecificPrimitives.add("bool"); languageSpecificPrimitives.add("str"); @@ -49,7 +48,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig typeMapping.clear(); typeMapping.put("integer", "int"); typeMapping.put("float", "float"); - typeMapping.put("long", "long"); + typeMapping.put("long", "int"); typeMapping.put("double", "float"); typeMapping.put("array", "list"); typeMapping.put("map", "map"); @@ -70,8 +69,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("README.mustache", eggPackage, "README.md")); supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); supportingFiles.add(new SupportingFile("swagger.mustache", invokerPackage, "swagger.py")); + supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage.replace('.', File.separatorChar), "__init__.py")); } @Override diff --git a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache new file mode 100644 index 00000000000..1597be6991a --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache @@ -0,0 +1,15 @@ +#!/usr/bin/env python +"""Add all of the modules in the current directory to __all__""" +from __future__ import absolute_import + +import os + +{{#apiInfo}}{{#apis}} +from .{{classVarName}} import {{classname}} +{{/apis}}{{/apiInfo}} + +__all__ = [] + +for module in os.listdir(os.path.dirname(__file__)): + if module != '__init__.py' and module[-3:] == '.py': + __all__.append(module[:-3]) diff --git a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache index 93d18228d25..202879d39fd 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache @@ -1,5 +1,7 @@ #!/usr/bin/env python """Add all of the modules in the current directory to __all__""" +from __future__ import absolute_import + import os {{#models}}{{#model}} diff --git a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache index e88c5f01ee2..704aceb176a 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache @@ -1,5 +1,7 @@ #!/usr/bin/env python """Add all of the modules in the current directory to __all__""" +from __future__ import absolute_import + import os # import models into package @@ -9,7 +11,7 @@ from .models.{{classVarName}} import {{classname}} # import apis into package {{#apiInfo}}{{#apis}} -from .{{classVarName}} import {{classname}} +from .apis.{{classVarName}} import {{classname}} {{/apis}}{{/apiInfo}} # import ApiClient diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index ba17e6993a2..e7902c25fc6 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -21,98 +21,65 @@ NOTE: This class is auto generated by the swagger code generator program. Do not """ import sys import os -import urllib - -from models import * +# python 2 and python 3 compatibility library +from six import iteritems {{#operations}} class {{classname}}(object): - def __init__(self, apiClient): - self.apiClient = apiClient + def __init__(self, api_client): + self.api_client = api_client - {{newline}} {{#operation}} def {{nickname}}(self, {{#requiredParams}}{{paramName}}{{#defaultValue}} = None{{/defaultValue}}, {{/requiredParams}}**kwargs): - """{{{summary}}} + """ + {{{summary}}} {{{notes}}} - Args: - {{#allParams}}{{paramName}}, {{dataType}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} - {{/allParams}} + {{#allParams}} + :param {{dataType}} {{paramName}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{/allParams}} - Returns: {{returnType}} + :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} """ - allParams = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] + all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: + for key, val in iteritems(params['kwargs']): + if key not in all_params: raise TypeError("Got an unexpected keyword argument '%s' to method {{nickname}}" % key) params[key] = val del params['kwargs'] - resourcePath = '{{path}}' - resourcePath = resourcePath.replace('{format}', 'json') + resource_path = '{{path}}'.replace('{format}', 'json') method = '{{httpMethod}}' - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None + path_params = dict({{#pathParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/pathParams}}) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict({{#queryParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/queryParams}}) + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict({{#headerParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/headerParams}}) + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict({{#formParams}}{{^isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}}) + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict({{#formParams}}{{#isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}}) + files = {k: v for k, v in iteritems(files) if v} + body_params = {{#bodyParam}}params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}}None{{/bodyParam}} accepts = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - headerParams['Accept'] = ', '.join(accepts) + header_params['Accept'] = ', '.join(accepts) content_types = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - {{#queryParams}} - if ('{{paramName}}' in params): - queryParams['{{baseName}}'] = self.apiClient.toPathValue(params['{{paramName}}']) - {{/queryParams}} - - {{#headerParams}} - if ('{{paramName}}' in params): - headerParams['{{baseName}}'] = params['{{paramName}}'] - {{/headerParams}} - - {{#pathParams}} - if ('{{paramName}}' in params): - replacement = str(self.apiClient.toPathValue(params['{{paramName}}'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + '{{baseName}}' + '}', - replacement) - {{/pathParams}} - - {{#formParams}} - if ('{{paramName}}' in params): - {{#notFile}}formParams['{{baseName}}'] = params['{{paramName}}']{{/notFile}}{{#isFile}}files['{{baseName}}'] = params['{{paramName}}']{{/isFile}} - {{/formParams}} - - {{#bodyParam}} - if ('{{paramName}}' in params): - bodyParam = params['{{paramName}}'] - {{/bodyParam}} - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}) {{#returnType}} - if not response: - return None - - responseObject = self.apiClient.deserialize(response, '{{returnType}}') - return responseObject + return response {{/returnType}} - {{newline}} - {{newline}} {{/operation}} -{{newline}} {{/operations}} {{newline}} diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index e46c63df637..9e41e78af7f 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -20,24 +20,27 @@ Copyright 2015 Reverb Technologies, Inc. {{#model}} class {{classname}}(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + """ + 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. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { + self.swagger_types = { {{#vars}} '{{name}}': '{{{datatype}}}'{{#hasMore}}, {{/hasMore}} {{/vars}}{{newline}} } - self.attributeMap = { + self.attribute_map = { {{#vars}} '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} {{/vars}} diff --git a/modules/swagger-codegen/src/main/resources/python/rest.mustache b/modules/swagger-codegen/src/main/resources/python/rest.mustache new file mode 100644 index 00000000000..06b817da757 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/rest.mustache @@ -0,0 +1,223 @@ +# coding: utf-8 +import sys +import io +import json + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + import urllib3 +except ImportError: + raise ImportError('Swagger python client requires urllib3.') + +try: + # for python3 + from urllib.parse import urlencode +except ImportError: + # for python2 + from urllib import urlencode + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """ + Returns a dictionary of the response headers. + """ + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """ + Returns a given response header. + """ + return self.urllib3_response.getheader(name, default) + +class RESTClientObject(object): + + def __init__(self, pools_size=4): + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None): + """ + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, `application/x-www-form-urlencode` + and `multipart/form-data` + :param raw_response: if return the raw response + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] + + if post_params and body: + raise ValueError("body parameter cannot be used with post_params parameter.") + + post_params = post_params or {} + headers = headers or {} + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + # For `POST`, `PUT`, `PATCH` + if method in ['POST', 'PUT', 'PATCH']: + if query_params: + url += '?' + urlencode(query_params) + if headers['Content-Type'] == 'application/json': + r = self.pool_manager.request(method, url, + body=json.dumps(body), + headers=headers) + if headers['Content-Type'] == 'application/x-www-form-urlencoded': + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=False, + headers=headers) + if headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct Content-Type + # which generated by urllib3 will be overwritten. + del headers['Content-Type'] + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=True, + headers=headers) + # For `GET`, `HEAD`, `DELETE` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + headers=headers) + r = RESTResponse(r) + + if r.status not in range(200, 206): + raise ErrorResponse(r) + + return self.process_response(r) + + def process_response(self, response): + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = response.data.decode('utf8') + else: + data = response.data + try: + resp = json.loads(data) + except ValueError: + resp = data + + return resp + + def GET(self, url, headers=None, query_params=None): + return self.request("GET", url, headers=headers, query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None): + return self.request("HEAD", url, headers=headers, query_params=query_params) + + def DELETE(self, url, headers=None, query_params=None): + return self.request("DELETE", url, headers=headers, query_params=query_params) + + def POST(self, url, headers=None, post_params=None, body=None): + return self.request("POST", url, headers=headers, post_params=post_params, body=body) + + def PUT(self, url, headers=None, post_params=None, body=None): + return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + + def PATCH(self, url, headers=None, post_params=None, body=None): + return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + + +class ErrorResponse(Exception): + """ + Non-2xx HTTP response + """ + + def __init__(self, http_resp): + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + + # In the python 3, the self.body is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = self.body.decode('utf8') + else: + data = self.body + + try: + self.body = json.loads(data) + except ValueError: + self.body = data + + def __str__(self): + """ + Custom error response messages + """ + return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + format(self.status, self.reason, self.headers, self.body) + +class RESTClient(object): + """ + A class with all class methods to perform JSON requests. + """ + + IMPL = RESTClientObject() + + @classmethod + def request(cls, *n, **kw): + """ + Perform a REST request and parse the response. + """ + return cls.IMPL.request(*n, **kw) + + @classmethod + def GET(cls, *n, **kw): + """ + Perform a GET request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def HEAD(cls, *n, **kw): + """ + Perform a HEAD request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def POST(cls, *n, **kw): + """ + Perform a POST request using `RESTClient.request()` + """ + return cls.IMPL.POST(*n, **kw) + + @classmethod + def PUT(cls, *n, **kw): + """ + Perform a PUT request using `RESTClient.request()` + """ + return cls.IMPL.PUT(*n, **kw) + + @classmethod + def PATCH(cls, *n, **kw): + """ + Perform a PATCH request using `RESTClient.request()` + """ + return cls.IMPL.PATCH(*n, **kw) + + @classmethod + def DELETE(cls, *n, **kw): + """ + Perform a DELETE request using `RESTClient.request()` + """ + return cls.IMPL.DELETE(*n, **kw) diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index d10da4c68d0..64609c37dd1 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -12,7 +12,7 @@ from setuptools import setup, find_packages # Try reading the setuptools documentation: # http://pypi.python.org/pypi/setuptools -REQUIRES = [] +REQUIRES = ["urllib3 >= 1.10", "six >= 1.9"] setup( name="{{module}}", diff --git a/modules/swagger-codegen/src/main/resources/python/swagger.mustache b/modules/swagger-codegen/src/main/resources/python/swagger.mustache index 10ac54d527d..549106014e3 100644 --- a/modules/swagger-codegen/src/main/resources/python/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/python/swagger.mustache @@ -6,118 +6,109 @@ server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the Swagger templates.""" -import sys +from __future__ import absolute_import +from . import models +from .rest import RESTClient + import os import re import urllib -import urllib2 -import httplib import json import datetime import mimetypes import random -import string -import models + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + # for python3 + from urllib.parse import quote +except ImportError: + # for python2 + from urllib import quote class ApiClient(object): - """Generic API client for Swagger client library builds - - Attributes: - host: The base path for the server to call - headerName: a header to pass when making calls to the API - headerValue: a header value to pass when making calls to the API """ - def __init__(self, host=None, headerName=None, headerValue=None): - self.defaultHeaders = {} - if (headerName is not None): - self.defaultHeaders[headerName] = headerValue + Generic API client for Swagger client library builds + + :param host: The base path for the server to call + :param header_name: a header to pass when making calls to the API + :param header_value: a header value to pass when making calls to the API + """ + def __init__(self, host=None, header_name=None, header_value=None): + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value self.host = host self.cookie = None - self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) # Set default User-Agent. self.user_agent = 'Python-Swagger' @property def user_agent(self): - return self.defaultHeaders['User-Agent'] + return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - self.defaultHeaders['User-Agent'] = value + self.default_headers['User-Agent'] = value - def setDefaultHeader(self, headerName, headerValue): - self.defaultHeaders[headerName] = headerValue + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None, files=None): - - url = self.host + resourcePath - - mergedHeaderParams = self.defaultHeaders.copy() - mergedHeaderParams.update(headerParams) - headers = {} - if mergedHeaderParams: - for param, value in mergedHeaderParams.iteritems(): - headers[param] = ApiClient.sanitizeForSerialization(value) + def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, response=None): + # headers parameters + headers = self.default_headers.copy() + headers.update(header_params) if self.cookie: - headers['Cookie'] = ApiClient.sanitizeForSerialization(self.cookie) + headers['Cookie'] = self.cookie + if headers: + headers = ApiClient.sanitize_for_serialization(headers) - data = None + # path parameters + if path_params: + path_params = ApiClient.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.replace('{' + k + '}', replacement) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value is not None: - sentQueryParams[param] = ApiClient.sanitizeForSerialization(value) - url = url + '?' + urllib.urlencode(sentQueryParams) + # query parameters + if query_params: + query_params = ApiClient.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - if method in ['GET']: - #Options to add statements later on and for compatibility - pass + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = ApiClient.sanitize_for_serialization(post_params) - elif method in ['POST', 'PUT', 'DELETE']: - if postData: - postData = ApiClient.sanitizeForSerialization(postData) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - data = json.dumps(postData) - elif headers['Content-Type'] == 'application/json': - data = json.dumps(postData) - elif headers['Content-Type'] == 'multipart/form-data': - data = self.buildMultipartFormData(postData, files) - headers['Content-Type'] = 'multipart/form-data; boundary={0}'.format(self.boundary) - headers['Content-length'] = str(len(data)) - else: - data = urllib.urlencode(postData) + # body + if body: + body = ApiClient.sanitize_for_serialization(body) + # request url + url = self.host + resource_path + + # perform request and return response + response_data = self.request(method, url, query_params=query_params, headers=headers, + post_params=post_params, body=body) + + # deserialize response data + if response: + return self.deserialize(response_data, response) else: - raise Exception('Method ' + method + ' is not recognized.') + return None - request = MethodRequest(method=method, url=url, headers=headers, - data=data) + def to_path_value(self, obj): + """ + Convert a string or object to a path-friendly value + + :param obj: object or string value - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value + :return string: quoted value """ if type(obj) == list: return ','.join(obj) @@ -125,12 +116,12 @@ class ApiClient(object): return str(obj) @staticmethod - def sanitizeForSerialization(obj): + def sanitize_for_serialization(obj): """ Sanitize an object for Request. If obj is None, return None. - If obj is str, int, long, float, bool, return directly. + If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, santize each element in the list. If obj is dict, return the dict. @@ -138,113 +129,80 @@ class ApiClient(object): """ if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, long, float, bool, file)): + elif isinstance(obj, (str, int, float, bool, tuple)): return obj elif isinstance(obj, list): - return [ApiClient.sanitizeForSerialization(subObj) for subObj in obj] + return [ApiClient.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() else: if isinstance(obj, dict): - objDict = obj + obj_dict = obj else: - # Convert model obj to dict except attributes `swaggerTypes`, `attributeMap` + # Convert model obj to dict except attributes `swagger_types`, `attribute_map` # 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()} + obj_dict = {obj.attribute_map[key]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' and key != 'attribute_map' and val is not None} + return {key: ApiClient.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - def buildMultipartFormData(self, postData, files): - def escape_quotes(s): - return s.replace('"', '\\"') + def deserialize(self, obj, obj_class): + """ + Derialize a JSON string into an object. - lines = [] + :param obj: string or object to be deserialized + :param obj_class: class literal for deserialzied object, or string of class name - for name, value in postData.items(): - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)), - '', - str(value), - )) - - for name, filepath in files.items(): - f = open(filepath, 'r') - filename = filepath.split('/')[-1] - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)), - 'Content-Type: {0}'.format(mimetype), - '', - f.read() - )) - - lines.extend(( - '--{0}--'.format(self.boundary), - '' - )) - return '\r\n'.join(lines) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a + :return object: deserialized object + """ + # Have to accept obj_class as string or actual type. Type could be a # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] + if type(obj_class) == str: + if 'list[' in obj_class: + match = re.match('list\[(.*)\]', obj_class) + sub_class = match.group(1) + return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) + if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: + obj_class = eval(obj_class) else: # not a native type, must be model class - objClass = eval('models.' + objClass) + obj_class = eval('models.' + obj_class) - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: + if obj_class in [int, float, dict, list, str, bool]: + return obj_class(obj) + elif obj_class == datetime: return self.__parse_string_to_datetime(obj) - instance = objClass() + instance = obj_class() - for attr, attrType in instance.swaggerTypes.iteritems(): - 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) + for attr, attr_type in iteritems(instance.swagger_types): + if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: + value = obj[instance.attribute_map[attr]] + if attr_type in ['str', 'int', 'float', 'bool']: + attr_type = eval(attr_type) try: - value = attrType(value) + value = attr_type(value) except UnicodeEncodeError: value = unicode(value) except TypeError: value = value setattr(instance, attr, value) - elif (attrType == 'datetime'): + elif attr_type == 'datetime': setattr(instance, attr, self.__parse_string_to_datetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] + elif 'list[' in attr_type: + match = re.match('list\[(.*)\]', attr_type) + sub_class = match.group(1) + sub_values = [] if not value: setattr(instance, attr, None) else: - for subValue in value: - subValues.append(self.deserialize(subValue, subClass)) - setattr(instance, attr, subValues) + for sub_value in value: + sub_values.append(self.deserialize(sub_value, sub_class)) + setattr(instance, attr, sub_values) else: - setattr(instance, attr, self.deserialize(value, attrType)) + setattr(instance, attr, self.deserialize(value, attr_type)) return instance @@ -260,16 +218,42 @@ class ApiClient(object): except ImportError: return string -class MethodRequest(urllib2.Request): - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" + def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): + """ + Perform http request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, query_params=query_params, headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, query_params=query_params, headers=headers) + elif method == "POST": + return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) + elif method == "PUT": + return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, query_params=query_params, headers=headers) + else: + raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") + + def prepare_post_parameters(self, post_params=None, files=None): + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + + - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py index 30d634bc4b3..91427e9d686 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py @@ -1,5 +1,7 @@ #!/usr/bin/env python """Add all of the modules in the current directory to __all__""" +from __future__ import absolute_import + import os # import models into package @@ -17,11 +19,11 @@ from .models.order import Order # import apis into package -from .user_api import UserApi +from .apis.user_api import UserApi -from .pet_api import PetApi +from .apis.pet_api import PetApi -from .store_api import StoreApi +from .apis.store_api import StoreApi # import ApiClient diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py new file mode 100644 index 00000000000..e4f2bbde841 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py @@ -0,0 +1,19 @@ +#!/usr/bin/env python +"""Add all of the modules in the current directory to __all__""" +from __future__ import absolute_import + +import os + + +from .user_api import UserApi + +from .pet_api import PetApi + +from .store_api import StoreApi + + +__all__ = [] + +for module in os.listdir(os.path.dirname(__file__)): + if module != '__init__.py' and module[-3:] == '.py': + __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py new file mode 100644 index 00000000000..8a21d3900d1 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -0,0 +1,426 @@ +#!/usr/bin/env python +# coding: utf-8 + +""" +PetApi.py +Copyright 2015 Reverb Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +""" +import sys +import os + +# python 2 and python 3 compatibility library +from six import iteritems + +class PetApi(object): + + def __init__(self, api_client): + self.api_client = api_client + + + def update_pet(self, **kwargs): + """ + Update an existing pet + + + + :param Pet body: Pet object that needs to be added to the store (required) + + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet'.replace('{format}', 'json') + method = 'PUT' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['application/json', 'application/xml', ] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def add_pet(self, **kwargs): + """ + Add a new pet to the store + + + + :param Pet body: Pet object that needs to be added to the store (required) + + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet'.replace('{format}', 'json') + method = 'POST' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['application/json', 'application/xml', ] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def find_pets_by_status(self, **kwargs): + """ + Finds Pets by status + Multiple status values can be provided with comma seperated strings + + + :param list[str] status: Status values that need to be considered for filter (required) + + + :return: list[Pet] + """ + + all_params = ['status'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/findByStatus'.replace('{format}', 'json') + method = 'GET' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict(status=params.get('status')) + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='list[Pet]') + + return response + + + def find_pets_by_tags(self, **kwargs): + """ + Finds Pets by tags + Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + + + :param list[str] tags: Tags to filter by (required) + + + :return: list[Pet] + """ + + all_params = ['tags'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/findByTags'.replace('{format}', 'json') + method = 'GET' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict(tags=params.get('tags')) + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='list[Pet]') + + return response + + + def get_pet_by_id(self, **kwargs): + """ + Find pet by ID + Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + + + :param int pet_id: ID of pet that needs to be fetched (required) + + + :return: Pet + """ + + all_params = ['pet_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + method = 'GET' + + path_params = dict(petId=params.get('pet_id')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='Pet') + + return response + + + def update_pet_with_form(self, **kwargs): + """ + Updates a pet in the store with form data + + + + :param str pet_id: ID of pet that needs to be updated (required) + + :param str name: Updated name of the pet (required) + + :param str status: Updated status of the pet (required) + + + :return: None + """ + + all_params = ['pet_id', 'name', 'status'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + method = 'POST' + + path_params = dict(petId=params.get('pet_id')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict(name=params.get('name'), status=params.get('status')) + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['application/x-www-form-urlencoded', ] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def delete_pet(self, **kwargs): + """ + Deletes a pet + + + + :param str api_key: (required) + + :param int pet_id: Pet id to delete (required) + + + :return: None + """ + + all_params = ['api_key', 'pet_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}'.replace('{format}', 'json') + method = 'DELETE' + + path_params = dict(petId=params.get('pet_id')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict(api_key=params.get('api_key')) + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def upload_file(self, **kwargs): + """ + uploads an image + + + + :param int pet_id: ID of pet to update (required) + + :param str additional_metadata: Additional data to pass to server (required) + + :param file file: file to upload (required) + + + :return: None + """ + + all_params = ['pet_id', 'additional_metadata', 'file'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') + method = 'POST' + + path_params = dict(petId=params.get('pet_id')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict(additionalMetadata=params.get('additional_metadata'), ) + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict(file=params.get('file')) + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = ['multipart/form-data', ] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py new file mode 100644 index 00000000000..37cfb524ad0 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python +# coding: utf-8 + +""" +StoreApi.py +Copyright 2015 Reverb Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +""" +import sys +import os + +# python 2 and python 3 compatibility library +from six import iteritems + +class StoreApi(object): + + def __init__(self, api_client): + self.api_client = api_client + + + def get_inventory(self, **kwargs): + """ + Returns pet inventories by status + Returns a map of status codes to quantities + + + + :return: map(String, int) + """ + + all_params = [] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/inventory'.replace('{format}', 'json') + method = 'GET' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='map(String, int)') + + return response + + + def place_order(self, **kwargs): + """ + Place an order for a pet + + + + :param Order body: order placed for purchasing the pet (required) + + + :return: Order + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/order'.replace('{format}', 'json') + method = 'POST' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='Order') + + return response + + + def get_order_by_id(self, **kwargs): + """ + Find purchase order by ID + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + + :param str order_id: ID of pet that needs to be fetched (required) + + + :return: Order + """ + + all_params = ['order_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') + method = 'GET' + + path_params = dict(orderId=params.get('order_id')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='Order') + + return response + + + def delete_order(self, **kwargs): + """ + Delete purchase order by ID + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + + :param str order_id: ID of the order that needs to be deleted (required) + + + :return: None + """ + + all_params = ['order_id'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/store/order/{orderId}'.replace('{format}', 'json') + method = 'DELETE' + + path_params = dict(orderId=params.get('order_id')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py new file mode 100644 index 00000000000..158a03f14d2 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -0,0 +1,416 @@ +#!/usr/bin/env python +# coding: utf-8 + +""" +UserApi.py +Copyright 2015 Reverb Technologies, Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. +""" +import sys +import os + +# python 2 and python 3 compatibility library +from six import iteritems + +class UserApi(object): + + def __init__(self, api_client): + self.api_client = api_client + + + def create_user(self, **kwargs): + """ + Create user + This can only be done by the logged in user. + + + :param User body: Created user object (required) + + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user'.replace('{format}', 'json') + method = 'POST' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def create_users_with_array_input(self, **kwargs): + """ + Creates list of users with given input array + + + + :param list[User] body: List of user object (required) + + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/createWithArray'.replace('{format}', 'json') + method = 'POST' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def create_users_with_list_input(self, **kwargs): + """ + Creates list of users with given input array + + + + :param list[User] body: List of user object (required) + + + :return: None + """ + + all_params = ['body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/createWithList'.replace('{format}', 'json') + method = 'POST' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def login_user(self, **kwargs): + """ + Logs user into the system + + + + :param str username: The user name for login (required) + + :param str password: The password for login in clear text (required) + + + :return: str + """ + + all_params = ['username', 'password'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/login'.replace('{format}', 'json') + method = 'GET' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict(username=params.get('username'), password=params.get('password')) + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='str') + + return response + + + def logout_user(self, **kwargs): + """ + Logs out current logged in user session + + + + + :return: None + """ + + all_params = [] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/logout'.replace('{format}', 'json') + method = 'GET' + + path_params = dict() + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def get_user_by_name(self, **kwargs): + """ + Get user by user name + + + + :param str username: The name that needs to be fetched. Use user1 for testing. (required) + + + :return: User + """ + + all_params = ['username'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/{username}'.replace('{format}', 'json') + method = 'GET' + + path_params = dict(username=params.get('username')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response='User') + + return response + + + def update_user(self, **kwargs): + """ + Updated user + This can only be done by the logged in user. + + + :param str username: name that need to be deleted (required) + + :param User body: Updated user object (required) + + + :return: None + """ + + all_params = ['username', 'body'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/{username}'.replace('{format}', 'json') + method = 'PUT' + + path_params = dict(username=params.get('username')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = params.get('body') + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + def delete_user(self, **kwargs): + """ + Delete user + This can only be done by the logged in user. + + + :param str username: The name that needs to be deleted (required) + + + :return: None + """ + + all_params = ['username'] + + params = locals() + for key, val in iteritems(params['kwargs']): + if key not in all_params: + raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) + params[key] = val + del params['kwargs'] + + resource_path = '/user/{username}'.replace('{format}', 'json') + method = 'DELETE' + + path_params = dict(username=params.get('username')) + path_params = {k: v for k, v in iteritems(path_params) if v} + query_params = dict() + query_params = {k: v for k, v in iteritems(query_params) if v} + header_params = dict() + header_params = {k: v for k, v in iteritems(header_params) if v} + form_params = dict() + form_params = {k: v for k, v in iteritems(form_params) if v} + files = dict() + files = {k: v for k, v in iteritems(files) if v} + body_params = None + + accepts = ['application/json', 'application/xml'] + header_params['Accept'] = ', '.join(accepts) + + content_types = [] + header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' + + response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, + body=body_params, post_params=form_params, files=files, + response=None) + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py index ce94c72a70c..96d0a37ec60 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py @@ -1,5 +1,7 @@ #!/usr/bin/env python """Add all of the modules in the current directory to __all__""" +from __future__ import absolute_import + import os diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py index 7b41a32a7d7..c9c009dd68f 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py @@ -18,26 +18,29 @@ Copyright 2015 Reverb Technologies, Inc. """ class Category(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + """ + 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. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { + self.swagger_types = { - 'id': 'long', + 'id': 'int', 'name': 'str' } - self.attributeMap = { + self.attribute_map = { 'id': 'id', @@ -47,7 +50,7 @@ class Category(object): - self.id = None # long + self.id = None # int self.name = None # str diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py index 84780db3780..ab5384ee270 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py @@ -18,22 +18,25 @@ Copyright 2015 Reverb Technologies, Inc. """ class Order(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + """ + 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. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { + self.swagger_types = { - 'id': 'long', + 'id': 'int', - 'pet_id': 'long', + 'pet_id': 'int', 'quantity': 'int', @@ -49,7 +52,7 @@ class Order(object): } - self.attributeMap = { + self.attribute_map = { 'id': 'id', @@ -67,10 +70,10 @@ class Order(object): - self.id = None # long + self.id = None # int - self.pet_id = None # long + self.pet_id = None # int self.quantity = None # int diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py index 1415d6f8535..8266556946d 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py @@ -18,19 +18,22 @@ Copyright 2015 Reverb Technologies, Inc. """ class Pet(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + """ + 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. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { + self.swagger_types = { - 'id': 'long', + 'id': 'int', 'category': 'Category', @@ -49,7 +52,7 @@ class Pet(object): } - self.attributeMap = { + self.attribute_map = { 'id': 'id', @@ -67,7 +70,7 @@ class Pet(object): - self.id = None # long + self.id = None # int self.category = None # Category diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py index a6ed3083422..dd8f0c0057a 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py @@ -18,26 +18,29 @@ Copyright 2015 Reverb Technologies, Inc. """ class Tag(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + """ + 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. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { + self.swagger_types = { - 'id': 'long', + 'id': 'int', 'name': 'str' } - self.attributeMap = { + self.attribute_map = { 'id': 'id', @@ -47,7 +50,7 @@ class Tag(object): - self.id = None # long + self.id = None # int self.name = None # str diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py index 8559b331203..2fd47ee47e5 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py @@ -18,19 +18,22 @@ Copyright 2015 Reverb Technologies, Inc. """ class User(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually.""" + """ + 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. + Swagger model + + :param dict swaggerTypes: The key is attribute name and the value is attribute type. + :param dict attributeMap: The key is attribute name and the value is json key in definition. """ - self.swaggerTypes = { + self.swagger_types = { - 'id': 'long', + 'id': 'int', 'username': 'str', @@ -55,7 +58,7 @@ class User(object): } - self.attributeMap = { + self.attribute_map = { 'id': 'id', @@ -77,7 +80,7 @@ class User(object): - self.id = None # long + self.id = None # int self.username = None # str diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py deleted file mode 100644 index d842c2f0a0f..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py +++ /dev/null @@ -1,551 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -""" -PetApi.py -Copyright 2015 Reverb Technologies, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os -import urllib - -from models import * - - -class PetApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def update_pet(self, **kwargs): - """Update an existing pet - - - Args: - body, Pet: Pet object that needs to be added to the store (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['application/json', 'application/xml', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def add_pet(self, **kwargs): - """Add a new pet to the store - - - Args: - body, Pet: Pet object that needs to be added to the store (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method add_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['application/json', 'application/xml', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def find_pets_by_status(self, **kwargs): - """Finds Pets by status - Multiple status values can be provided with comma seperated strings - - Args: - status, list[str]: Status values that need to be considered for filter (required) - - - Returns: list[Pet] - """ - - allParams = ['status'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_status" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByStatus' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - if ('status' in params): - queryParams['status'] = self.apiClient.toPathValue(params['status']) - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Pet]') - return responseObject - - - - - def find_pets_by_tags(self, **kwargs): - """Finds Pets by tags - Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - - Args: - tags, list[str]: Tags to filter by (required) - - - Returns: list[Pet] - """ - - allParams = ['tags'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method find_pets_by_tags" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/findByTags' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - if ('tags' in params): - queryParams['tags'] = self.apiClient.toPathValue(params['tags']) - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'list[Pet]') - return responseObject - - - - - def get_pet_by_id(self, **kwargs): - """Find pet by ID - Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - - Args: - pet_id, long: ID of pet that needs to be fetched (required) - - - Returns: Pet - """ - - allParams = ['pet_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_pet_by_id" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Pet') - return responseObject - - - - - def update_pet_with_form(self, **kwargs): - """Updates a pet in the store with form data - - - Args: - pet_id, str: ID of pet that needs to be updated (required) - name, str: Updated name of the pet (required) - status, str: Updated status of the pet (required) - - - Returns: - """ - - allParams = ['pet_id', 'name', 'status'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_pet_with_form" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['application/x-www-form-urlencoded', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - if ('name' in params): - formParams['name'] = params['name'] - - if ('status' in params): - formParams['status'] = params['status'] - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def delete_pet(self, **kwargs): - """Deletes a pet - - - Args: - api_key, str: (required) - pet_id, long: Pet id to delete (required) - - - Returns: - """ - - allParams = ['api_key', 'pet_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_pet" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - if ('api_key' in params): - headerParams['api_key'] = params['api_key'] - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def upload_file(self, **kwargs): - """uploads an image - - - Args: - pet_id, long: ID of pet to update (required) - additional_metadata, str: Additional data to pass to server (required) - file, file: file to upload (required) - - - Returns: - """ - - allParams = ['pet_id', 'additional_metadata', 'file'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method upload_file" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/pet/{petId}/uploadImage' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = ['multipart/form-data', ] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('pet_id' in params): - replacement = str(self.apiClient.toPathValue(params['pet_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'petId' + '}', - replacement) - - - - if ('additional_metadata' in params): - formParams['additionalMetadata'] = params['additional_metadata'] - - if ('file' in params): - files['file'] = params['file'] - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py new file mode 100644 index 00000000000..06b817da757 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/rest.py @@ -0,0 +1,223 @@ +# coding: utf-8 +import sys +import io +import json + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + import urllib3 +except ImportError: + raise ImportError('Swagger python client requires urllib3.') + +try: + # for python3 + from urllib.parse import urlencode +except ImportError: + # for python2 + from urllib import urlencode + + +class RESTResponse(io.IOBase): + + def __init__(self, resp): + self.urllib3_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = resp.data + + def getheaders(self): + """ + Returns a dictionary of the response headers. + """ + return self.urllib3_response.getheaders() + + def getheader(self, name, default=None): + """ + Returns a given response header. + """ + return self.urllib3_response.getheader(name, default) + +class RESTClientObject(object): + + def __init__(self, pools_size=4): + self.pool_manager = urllib3.PoolManager( + num_pools=pools_size + ) + + def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None): + """ + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, `application/x-www-form-urlencode` + and `multipart/form-data` + :param raw_response: if return the raw response + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', 'PATCH'] + + if post_params and body: + raise ValueError("body parameter cannot be used with post_params parameter.") + + post_params = post_params or {} + headers = headers or {} + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + # For `POST`, `PUT`, `PATCH` + if method in ['POST', 'PUT', 'PATCH']: + if query_params: + url += '?' + urlencode(query_params) + if headers['Content-Type'] == 'application/json': + r = self.pool_manager.request(method, url, + body=json.dumps(body), + headers=headers) + if headers['Content-Type'] == 'application/x-www-form-urlencoded': + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=False, + headers=headers) + if headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct Content-Type + # which generated by urllib3 will be overwritten. + del headers['Content-Type'] + r = self.pool_manager.request(method, url, + fields=post_params, + encode_multipart=True, + headers=headers) + # For `GET`, `HEAD`, `DELETE` + else: + r = self.pool_manager.request(method, url, + fields=query_params, + headers=headers) + r = RESTResponse(r) + + if r.status not in range(200, 206): + raise ErrorResponse(r) + + return self.process_response(r) + + def process_response(self, response): + # In the python 3, the response.data is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = response.data.decode('utf8') + else: + data = response.data + try: + resp = json.loads(data) + except ValueError: + resp = data + + return resp + + def GET(self, url, headers=None, query_params=None): + return self.request("GET", url, headers=headers, query_params=query_params) + + def HEAD(self, url, headers=None, query_params=None): + return self.request("HEAD", url, headers=headers, query_params=query_params) + + def DELETE(self, url, headers=None, query_params=None): + return self.request("DELETE", url, headers=headers, query_params=query_params) + + def POST(self, url, headers=None, post_params=None, body=None): + return self.request("POST", url, headers=headers, post_params=post_params, body=body) + + def PUT(self, url, headers=None, post_params=None, body=None): + return self.request("PUT", url, headers=headers, post_params=post_params, body=body) + + def PATCH(self, url, headers=None, post_params=None, body=None): + return self.request("PATCH", url, headers=headers, post_params=post_params, body=body) + + +class ErrorResponse(Exception): + """ + Non-2xx HTTP response + """ + + def __init__(self, http_resp): + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data + self.headers = http_resp.getheaders() + + # In the python 3, the self.body is bytes. + # we need to decode it to string. + if sys.version_info > (3,): + data = self.body.decode('utf8') + else: + data = self.body + + try: + self.body = json.loads(data) + except ValueError: + self.body = data + + def __str__(self): + """ + Custom error response messages + """ + return "({0})\nReason: {1}\nHeader: {2}\nBody: {3}\n".\ + format(self.status, self.reason, self.headers, self.body) + +class RESTClient(object): + """ + A class with all class methods to perform JSON requests. + """ + + IMPL = RESTClientObject() + + @classmethod + def request(cls, *n, **kw): + """ + Perform a REST request and parse the response. + """ + return cls.IMPL.request(*n, **kw) + + @classmethod + def GET(cls, *n, **kw): + """ + Perform a GET request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def HEAD(cls, *n, **kw): + """ + Perform a HEAD request using `RESTClient.request()`. + """ + return cls.IMPL.GET(*n, **kw) + + @classmethod + def POST(cls, *n, **kw): + """ + Perform a POST request using `RESTClient.request()` + """ + return cls.IMPL.POST(*n, **kw) + + @classmethod + def PUT(cls, *n, **kw): + """ + Perform a PUT request using `RESTClient.request()` + """ + return cls.IMPL.PUT(*n, **kw) + + @classmethod + def PATCH(cls, *n, **kw): + """ + Perform a PATCH request using `RESTClient.request()` + """ + return cls.IMPL.PATCH(*n, **kw) + + @classmethod + def DELETE(cls, *n, **kw): + """ + Perform a DELETE request using `RESTClient.request()` + """ + return cls.IMPL.DELETE(*n, **kw) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py deleted file mode 100644 index b2de83e85da..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/store_api.py +++ /dev/null @@ -1,289 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -""" -StoreApi.py -Copyright 2015 Reverb Technologies, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os -import urllib - -from models import * - - -class StoreApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def get_inventory(self, **kwargs): - """Returns pet inventories by status - Returns a map of status codes to quantities - - Args: - - - Returns: map(String, int) - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_inventory" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/inventory' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'map(String, int)') - return responseObject - - - - - def place_order(self, **kwargs): - """Place an order for a pet - - - Args: - body, Order: order placed for purchasing the pet (required) - - - Returns: Order - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method place_order" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def get_order_by_id(self, **kwargs): - """Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - - Args: - order_id, str: ID of pet that needs to be fetched (required) - - - Returns: Order - """ - - allParams = ['order_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_order_by_id" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('order_id' in params): - replacement = str(self.apiClient.toPathValue(params['order_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'Order') - return responseObject - - - - - def delete_order(self, **kwargs): - """Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - - Args: - order_id, str: ID of the order that needs to be deleted (required) - - - Returns: - """ - - allParams = ['order_id'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_order" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/store/order/{orderId}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('order_id' in params): - replacement = str(self.apiClient.toPathValue(params['order_id'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'orderId' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py index 10ac54d527d..549106014e3 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/swagger.py @@ -6,118 +6,109 @@ server communication, and is invariant across implementations. Specifics of the methods and models for each application are generated from the Swagger templates.""" -import sys +from __future__ import absolute_import +from . import models +from .rest import RESTClient + import os import re import urllib -import urllib2 -import httplib import json import datetime import mimetypes import random -import string -import models + +# python 2 and python 3 compatibility library +from six import iteritems + +try: + # for python3 + from urllib.parse import quote +except ImportError: + # for python2 + from urllib import quote class ApiClient(object): - """Generic API client for Swagger client library builds - - Attributes: - host: The base path for the server to call - headerName: a header to pass when making calls to the API - headerValue: a header value to pass when making calls to the API """ - def __init__(self, host=None, headerName=None, headerValue=None): - self.defaultHeaders = {} - if (headerName is not None): - self.defaultHeaders[headerName] = headerValue + Generic API client for Swagger client library builds + + :param host: The base path for the server to call + :param header_name: a header to pass when making calls to the API + :param header_value: a header value to pass when making calls to the API + """ + def __init__(self, host=None, header_name=None, header_value=None): + self.default_headers = {} + if header_name is not None: + self.default_headers[header_name] = header_value self.host = host self.cookie = None - self.boundary = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(30)) # Set default User-Agent. self.user_agent = 'Python-Swagger' @property def user_agent(self): - return self.defaultHeaders['User-Agent'] + return self.default_headers['User-Agent'] @user_agent.setter def user_agent(self, value): - self.defaultHeaders['User-Agent'] = value + self.default_headers['User-Agent'] = value - def setDefaultHeader(self, headerName, headerValue): - self.defaultHeaders[headerName] = headerValue + def set_default_header(self, header_name, header_value): + self.default_headers[header_name] = header_value - def callAPI(self, resourcePath, method, queryParams, postData, - headerParams=None, files=None): - - url = self.host + resourcePath - - mergedHeaderParams = self.defaultHeaders.copy() - mergedHeaderParams.update(headerParams) - headers = {} - if mergedHeaderParams: - for param, value in mergedHeaderParams.iteritems(): - headers[param] = ApiClient.sanitizeForSerialization(value) + def call_api(self, resource_path, method, path_params=None, query_params=None, header_params=None, + body=None, post_params=None, files=None, response=None): + # headers parameters + headers = self.default_headers.copy() + headers.update(header_params) if self.cookie: - headers['Cookie'] = ApiClient.sanitizeForSerialization(self.cookie) + headers['Cookie'] = self.cookie + if headers: + headers = ApiClient.sanitize_for_serialization(headers) - data = None + # path parameters + if path_params: + path_params = ApiClient.sanitize_for_serialization(path_params) + for k, v in iteritems(path_params): + replacement = quote(str(self.to_path_value(v))) + resource_path = resource_path.replace('{' + k + '}', replacement) - if queryParams: - # Need to remove None values, these should not be sent - sentQueryParams = {} - for param, value in queryParams.items(): - if value is not None: - sentQueryParams[param] = ApiClient.sanitizeForSerialization(value) - url = url + '?' + urllib.urlencode(sentQueryParams) + # query parameters + if query_params: + query_params = ApiClient.sanitize_for_serialization(query_params) + query_params = {k: self.to_path_value(v) for k, v in iteritems(query_params)} - if method in ['GET']: - #Options to add statements later on and for compatibility - pass + # post parameters + if post_params: + post_params = self.prepare_post_parameters(post_params, files) + post_params = ApiClient.sanitize_for_serialization(post_params) - elif method in ['POST', 'PUT', 'DELETE']: - if postData: - postData = ApiClient.sanitizeForSerialization(postData) - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' - data = json.dumps(postData) - elif headers['Content-Type'] == 'application/json': - data = json.dumps(postData) - elif headers['Content-Type'] == 'multipart/form-data': - data = self.buildMultipartFormData(postData, files) - headers['Content-Type'] = 'multipart/form-data; boundary={0}'.format(self.boundary) - headers['Content-length'] = str(len(data)) - else: - data = urllib.urlencode(postData) + # body + if body: + body = ApiClient.sanitize_for_serialization(body) + # request url + url = self.host + resource_path + + # perform request and return response + response_data = self.request(method, url, query_params=query_params, headers=headers, + post_params=post_params, body=body) + + # deserialize response data + if response: + return self.deserialize(response_data, response) else: - raise Exception('Method ' + method + ' is not recognized.') + return None - request = MethodRequest(method=method, url=url, headers=headers, - data=data) + def to_path_value(self, obj): + """ + Convert a string or object to a path-friendly value + + :param obj: object or string value - # Make the request - response = urllib2.urlopen(request) - if 'Set-Cookie' in response.headers: - self.cookie = response.headers['Set-Cookie'] - string = response.read() - - try: - data = json.loads(string) - except ValueError: # PUT requests don't return anything - data = None - - return data - - def toPathValue(self, obj): - """Convert a string or object to a path-friendly value - Args: - obj -- object or string value - Returns: - string -- quoted value + :return string: quoted value """ if type(obj) == list: return ','.join(obj) @@ -125,12 +116,12 @@ class ApiClient(object): return str(obj) @staticmethod - def sanitizeForSerialization(obj): + def sanitize_for_serialization(obj): """ Sanitize an object for Request. If obj is None, return None. - If obj is str, int, long, float, bool, return directly. + If obj is str, int, float, bool, return directly. If obj is datetime.datetime, datetime.date convert to string in iso8601 format. If obj is list, santize each element in the list. If obj is dict, return the dict. @@ -138,113 +129,80 @@ class ApiClient(object): """ if isinstance(obj, type(None)): return None - elif isinstance(obj, (str, int, long, float, bool, file)): + elif isinstance(obj, (str, int, float, bool, tuple)): return obj elif isinstance(obj, list): - return [ApiClient.sanitizeForSerialization(subObj) for subObj in obj] + return [ApiClient.sanitize_for_serialization(sub_obj) for sub_obj in obj] elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() else: if isinstance(obj, dict): - objDict = obj + obj_dict = obj else: - # Convert model obj to dict except attributes `swaggerTypes`, `attributeMap` + # Convert model obj to dict except attributes `swagger_types`, `attribute_map` # 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()} + obj_dict = {obj.attribute_map[key]: val + for key, val in iteritems(obj.__dict__) + if key != 'swagger_types' and key != 'attribute_map' and val is not None} + return {key: ApiClient.sanitize_for_serialization(val) + for key, val in iteritems(obj_dict)} - def buildMultipartFormData(self, postData, files): - def escape_quotes(s): - return s.replace('"', '\\"') + def deserialize(self, obj, obj_class): + """ + Derialize a JSON string into an object. - lines = [] + :param obj: string or object to be deserialized + :param obj_class: class literal for deserialzied object, or string of class name - for name, value in postData.items(): - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"'.format(escape_quotes(name)), - '', - str(value), - )) - - for name, filepath in files.items(): - f = open(filepath, 'r') - filename = filepath.split('/')[-1] - mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' - lines.extend(( - '--{0}'.format(self.boundary), - 'Content-Disposition: form-data; name="{0}"; filename="{1}"'.format(escape_quotes(name), escape_quotes(filename)), - 'Content-Type: {0}'.format(mimetype), - '', - f.read() - )) - - lines.extend(( - '--{0}--'.format(self.boundary), - '' - )) - return '\r\n'.join(lines) - - def deserialize(self, obj, objClass): - """Derialize a JSON string into an object. - - Args: - obj -- string or object to be deserialized - objClass -- class literal for deserialzied object, or string - of class name - Returns: - object -- deserialized object""" - - # Have to accept objClass as string or actual type. Type could be a + :return object: deserialized object + """ + # Have to accept obj_class as string or actual type. Type could be a # native Python type, or one of the model classes. - if type(objClass) == str: - if 'list[' in objClass: - match = re.match('list\[(.*)\]', objClass) - subClass = match.group(1) - return [self.deserialize(subObj, subClass) for subObj in obj] + if type(obj_class) == str: + if 'list[' in obj_class: + match = re.match('list\[(.*)\]', obj_class) + sub_class = match.group(1) + return [self.deserialize(sub_obj, sub_class) for sub_obj in obj] - if (objClass in ['int', 'float', 'long', 'dict', 'list', 'str', 'bool', 'datetime']): - objClass = eval(objClass) + if obj_class in ['int', 'float', 'dict', 'list', 'str', 'bool', 'datetime']: + obj_class = eval(obj_class) else: # not a native type, must be model class - objClass = eval('models.' + objClass) + obj_class = eval('models.' + obj_class) - if objClass in [int, long, float, dict, list, str, bool]: - return objClass(obj) - elif objClass == datetime: + if obj_class in [int, float, dict, list, str, bool]: + return obj_class(obj) + elif obj_class == datetime: return self.__parse_string_to_datetime(obj) - instance = objClass() + instance = obj_class() - for attr, attrType in instance.swaggerTypes.iteritems(): - 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) + for attr, attr_type in iteritems(instance.swagger_types): + if obj is not None and instance.attribute_map[attr] in obj and type(obj) in [list, dict]: + value = obj[instance.attribute_map[attr]] + if attr_type in ['str', 'int', 'float', 'bool']: + attr_type = eval(attr_type) try: - value = attrType(value) + value = attr_type(value) except UnicodeEncodeError: value = unicode(value) except TypeError: value = value setattr(instance, attr, value) - elif (attrType == 'datetime'): + elif attr_type == 'datetime': setattr(instance, attr, self.__parse_string_to_datetime(value)) - elif 'list[' in attrType: - match = re.match('list\[(.*)\]', attrType) - subClass = match.group(1) - subValues = [] + elif 'list[' in attr_type: + match = re.match('list\[(.*)\]', attr_type) + sub_class = match.group(1) + sub_values = [] if not value: setattr(instance, attr, None) else: - for subValue in value: - subValues.append(self.deserialize(subValue, subClass)) - setattr(instance, attr, subValues) + for sub_value in value: + sub_values.append(self.deserialize(sub_value, sub_class)) + setattr(instance, attr, sub_values) else: - setattr(instance, attr, self.deserialize(value, attrType)) + setattr(instance, attr, self.deserialize(value, attr_type)) return instance @@ -260,16 +218,42 @@ class ApiClient(object): except ImportError: return string -class MethodRequest(urllib2.Request): - def __init__(self, *args, **kwargs): - """Construct a MethodRequest. Usage is the same as for - `urllib2.Request` except it also takes an optional `method` - keyword argument. If supplied, `method` will be used instead of - the default.""" + def request(self, method, url, query_params=None, headers=None, post_params=None, body=None): + """ + Perform http request using RESTClient. + """ + if method == "GET": + return RESTClient.GET(url, query_params=query_params, headers=headers) + elif method == "HEAD": + return RESTClient.HEAD(url, query_params=query_params, headers=headers) + elif method == "POST": + return RESTClient.POST(url, headers=headers, post_params=post_params, body=body) + elif method == "PUT": + return RESTClient.PUT(url, headers=headers, post_params=post_params, body=body) + elif method == "PATCH": + return RESTClient.PATCH(url, headers=headers, post_params=post_params, body=body) + elif method == "DELETE": + return RESTClient.DELETE(url, query_params=query_params, headers=headers) + else: + raise ValueError("http method must be `GET`, `HEAD`, `POST`, `PATCH`, `PUT` or `DELETE`") + + def prepare_post_parameters(self, post_params=None, files=None): + params = {} + + if post_params: + params.update(post_params) + + if files: + for k, v in iteritems(files): + with open(v, 'rb') as f: + filename = os.path.basename(f.name) + filedata = f.read() + mimetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream' + params[k] = tuple([filename, filedata, mimetype]) + + return params + + + - if 'method' in kwargs: - self.method = kwargs.pop('method') - return urllib2.Request.__init__(self, *args, **kwargs) - def get_method(self): - return getattr(self, 'method', urllib2.Request.get_method(self)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py deleted file mode 100644 index d36a95514bd..00000000000 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/user_api.py +++ /dev/null @@ -1,526 +0,0 @@ -#!/usr/bin/env python -# coding: utf-8 - -""" -UserApi.py -Copyright 2015 Reverb Technologies, Inc. - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. - -NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. -""" -import sys -import os -import urllib - -from models import * - - -class UserApi(object): - - def __init__(self, apiClient): - self.apiClient = apiClient - - - - def create_user(self, **kwargs): - """Create user - This can only be done by the logged in user. - - Args: - body, User: Created user object (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def create_users_with_array_input(self, **kwargs): - """Creates list of users with given input array - - - Args: - body, list[User]: List of user object (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_array_input" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithArray' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def create_users_with_list_input(self, **kwargs): - """Creates list of users with given input array - - - Args: - body, list[User]: List of user object (required) - - - Returns: - """ - - allParams = ['body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method create_users_with_list_input" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/createWithList' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'POST' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def login_user(self, **kwargs): - """Logs user into the system - - - Args: - username, str: The user name for login (required) - password, str: The password for login in clear text (required) - - - Returns: str - """ - - allParams = ['username', 'password'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method login_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/login' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - if ('username' in params): - queryParams['username'] = self.apiClient.toPathValue(params['username']) - - if ('password' in params): - queryParams['password'] = self.apiClient.toPathValue(params['password']) - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'str') - return responseObject - - - - - def logout_user(self, **kwargs): - """Logs out current logged in user session - - - Args: - - - Returns: - """ - - allParams = [] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method logout_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/logout' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def get_user_by_name(self, **kwargs): - """Get user by user name - - - Args: - username, str: The name that needs to be fetched. Use user1 for testing. (required) - - - Returns: User - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method get_user_by_name" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'GET' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - if not response: - return None - - responseObject = self.apiClient.deserialize(response, 'User') - return responseObject - - - - - def update_user(self, **kwargs): - """Updated user - This can only be done by the logged in user. - - Args: - username, str: name that need to be deleted (required) - body, User: Updated user object (required) - - - Returns: - """ - - allParams = ['username', 'body'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method update_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'PUT' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - - - - if ('body' in params): - bodyParam = params['body'] - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - def delete_user(self, **kwargs): - """Delete user - This can only be done by the logged in user. - - Args: - username, str: The name that needs to be deleted (required) - - - Returns: - """ - - allParams = ['username'] - - params = locals() - for (key, val) in params['kwargs'].iteritems(): - if key not in allParams: - raise TypeError("Got an unexpected keyword argument '%s' to method delete_user" % key) - params[key] = val - del params['kwargs'] - - resourcePath = '/user/{username}' - resourcePath = resourcePath.replace('{format}', 'json') - method = 'DELETE' - - queryParams = {} - headerParams = {} - formParams = {} - files = {} - bodyParam = None - - accepts = ['application/json', 'application/xml'] - headerParams['Accept'] = ', '.join(accepts) - - content_types = [] - headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' - - - - - - - if ('username' in params): - replacement = str(self.apiClient.toPathValue(params['username'])) - replacement = urllib.quote(replacement) - resourcePath = resourcePath.replace('{' + 'username' + '}', - replacement) - - - - - - - postData = (formParams if formParams else bodyParam) - - response = self.apiClient.callAPI(resourcePath, method, queryParams, - postData, headerParams, files=files) - - - - - - - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.py b/samples/client/petstore/python/SwaggerPetstore-python/setup.py index 14d6a73b3b1..946274c5acd 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/setup.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.py @@ -12,7 +12,7 @@ from setuptools import setup, find_packages # Try reading the setuptools documentation: # http://pypi.python.org/pypi/setuptools -REQUIRES = [] +REQUIRES = ["urllib3 >= 1.10", "six >= 1.9"] setup( name="SwaggerPetstore", diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index b6088ae34b9..92b4e70dbce 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -10,9 +10,9 @@ $ nosetests -v import os import time import unittest -import urllib2 import SwaggerPetstore +from SwaggerPetstore.rest import ErrorResponse HOST = 'http://petstore.swagger.io/v2' @@ -52,7 +52,7 @@ class PetApiTests(unittest.TestCase): def test_1_add_pet(self): try: self.pet_api.add_pet(body=self.pet) - except (urllib2.HTTPError, urllib2.URLError) as e: + except ErrorResponse as e: self.fail("add_pet() raised {0} unexpectedly".format(type(e))) def test_2_get_pet_by_id(self): @@ -65,19 +65,19 @@ class PetApiTests(unittest.TestCase): try: self.pet.name = "hello kity with updated" self.pet_api.update_pet(body=self.pet) - except (urllib2.HTTPError, urllib2.URLError) as e: + except ErrorResponse as e: self.fail("update_pet() raised {0} unexpectedly".format(type(e))) def test_4_find_pets_by_status(self): self.assertIn( dir(self.pet), - map(dir, self.pet_api.find_pets_by_status(status=["sold"])) + list(map(dir, self.pet_api.find_pets_by_status(status=["sold"]))) ) def test_5_find_pets_by_tags(self): self.assertIn( dir(self.pet), - map(dir, self.pet_api.find_pets_by_tags(tags=["blank"])) + list(map(dir, self.pet_api.find_pets_by_tags(tags=["blank"]))) ) def test_6_update_pet_with_form(self): @@ -87,7 +87,7 @@ class PetApiTests(unittest.TestCase): self.pet_api.update_pet_with_form( pet_id=self.pet.id, name=name, status=status ) - except (urllib2.HTTPError, urllib2.URLError) as e: + except ErrorResponse as e: self.fail("update_pet_with_form() raised {0} unexpectedly".format(type(e))) def test_7_upload_file(self): @@ -98,14 +98,14 @@ class PetApiTests(unittest.TestCase): additional_metadata=additional_metadata, file=self.foo ) - except (urllib2.HTTPError, urllib2.URLError) as e: + except ErrorResponse as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) def test_8_delete_pet(self): try: api_key = "special-key" self.pet_api.delete_pet(pet_id=self.pet.id, api_key=api_key) - except (urllib2.HTTPError, urllib2.URLError) as e: + except ErrorResponse as e: self.fail("delete_pet() raised {0} unexpectedly".format(type(e))) From c12673a40765c2c3592073106ea815b44e464647 Mon Sep 17 00:00:00 2001 From: wing328 Date: Thu, 14 May 2015 14:16:12 +0800 Subject: [PATCH 25/75] fix error handling for 4xx, 5xx returned by server --- .../src/main/resources/csharp/api.mustache | 18 +-- .../resources/csharp/apiException.mustache | 18 +-- .../src/main/csharp/io/swagger/Api/PetApi.cs | 133 ++++++----------- .../main/csharp/io/swagger/Api/StoreApi.cs | 65 +++------ .../src/main/csharp/io/swagger/Api/UserApi.cs | 134 ++++++------------ .../csharp/io/swagger/client/ApiException.cs | 18 +-- 6 files changed, 132 insertions(+), 254 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/csharp/api.mustache b/modules/swagger-codegen/src/main/resources/csharp/api.mustache index 6e06087c1ae..f7cc79c5255 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/api.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/api.mustache @@ -70,19 +70,13 @@ namespace {{package}} { {{#bodyParam}}_request.AddParameter("application/json", ApiInvoker.Serialize({{paramName}}), ParameterType.RequestBody); // http body (model) parameter {{/bodyParam}} - try { - // make the HTTP request - {{#returnType}}IRestResponse response = restClient.Execute(_request); - return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}}restClient.Execute(_request); - return;{{/returnType}} - } catch (Exception ex) { - if(ex != null) { - return {{#returnType}}null{{/returnType}}; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling {{nickname}}: " + response.Content); } + {{#returnType}}return ({{{returnType}}}) ApiInvoker.Deserialize(response.Content, typeof({{{returnType}}}));{{/returnType}}{{^returnType}} + return;{{/returnType}} } {{/operation}} } diff --git a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache index 3b371aea9a8..f28eb8de6f7 100644 --- a/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache +++ b/modules/swagger-codegen/src/main/resources/csharp/apiException.mustache @@ -1,21 +1,17 @@ using System; namespace {{invokerPackage}} { + public class ApiException : Exception { - - private int errorCode = 0; + + public int ErrorCode { get; set; } public ApiException() {} - public int ErrorCode { - get - { - return errorCode; - } + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; } - public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; - } } -} \ No newline at end of file + +} diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs index 91e650b2bae..6a39ce7ba75 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/PetApi.cs @@ -60,18 +60,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePet: " + response.Content); } + + return; } @@ -100,18 +95,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling AddPet: " + response.Content); } + + return; } @@ -140,18 +130,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByStatus: " + response.Content); } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); } @@ -180,18 +164,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling FindPetsByTags: " + response.Content); } + return (List) ApiInvoker.Deserialize(response.Content, typeof(List)); } @@ -223,18 +201,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetPetById: " + response.Content); } + return (Pet) ApiInvoker.Deserialize(response.Content, typeof(Pet)); } @@ -270,18 +242,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdatePetWithForm: " + response.Content); } + + return; } @@ -315,18 +282,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeletePet: " + response.Content); } + + return; } @@ -362,18 +324,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UploadFile: " + response.Content); } + + return; } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs index 1f4b4441ae1..5b4236c7a77 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/StoreApi.cs @@ -58,18 +58,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetInventory: " + response.Content); } + return (Dictionary) ApiInvoker.Deserialize(response.Content, typeof(Dictionary)); } @@ -98,18 +92,12 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling PlaceOrder: " + response.Content); } + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); } @@ -141,18 +129,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetOrderById: " + response.Content); } + return (Order) ApiInvoker.Deserialize(response.Content, typeof(Order)); } @@ -184,18 +166,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteOrder: " + response.Content); } + + return; } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs index 1dd08f7c697..ff8f23a18b2 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/Api/UserApi.cs @@ -60,18 +60,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUser: " + response.Content); } + + return; } @@ -100,18 +95,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithArrayInput: " + response.Content); } + + return; } @@ -140,18 +130,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling CreateUsersWithListInput: " + response.Content); } + + return; } @@ -182,18 +167,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LoginUser: " + response.Content); } + return (string) ApiInvoker.Deserialize(response.Content, typeof(string)); } @@ -220,18 +199,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling LogoutUser: " + response.Content); } + + return; } @@ -263,18 +237,12 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - IRestResponse response = restClient.Execute(_request); - return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); - } catch (Exception ex) { - if(ex != null) { - return null; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling GetUserByName: " + response.Content); } + return (User) ApiInvoker.Deserialize(response.Content, typeof(User)); } @@ -308,18 +276,13 @@ namespace IO.Swagger.Api { _request.AddParameter("application/json", ApiInvoker.Serialize(Body), ParameterType.RequestBody); // http body (model) parameter - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling UpdateUser: " + response.Content); } + + return; } @@ -351,18 +314,13 @@ namespace IO.Swagger.Api { - try { - // make the HTTP request - restClient.Execute(_request); - return; - } catch (Exception ex) { - if(ex != null) { - return ; - } - else { - throw ex; - } + // make the HTTP request + IRestResponse response = restClient.Execute(_request); + if (((int)response.StatusCode) >= 400) { + throw new ApiException ((int)response.StatusCode, "Error calling DeleteUser: " + response.Content); } + + return; } } diff --git a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs index ffa49217bb8..7c4a7934681 100644 --- a/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs +++ b/samples/client/petstore/csharp/src/main/csharp/io/swagger/client/ApiException.cs @@ -1,21 +1,17 @@ using System; namespace IO.Swagger.Client { + public class ApiException : Exception { - - private int errorCode = 0; + + public int ErrorCode { get; set; } public ApiException() {} - public int ErrorCode { - get - { - return errorCode; - } + public ApiException(int errorCode, string message) : base(message) { + this.ErrorCode = errorCode; } - public ApiException(int errorCode, string message) : base(message) { - this.errorCode = errorCode; - } } -} \ No newline at end of file + +} From d798b943f5b47e19c517609644824c467debb36e Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 15 May 2015 14:38:06 +0800 Subject: [PATCH 26/75] added python 2.7 and python 3.4 test environments --- .../languages/PythonClientCodegen.java | 1 + .../src/main/resources/python/README.mustache | 19 +- .../resources/python/__init__api.mustache | 14 +- .../resources/python/__init__model.mustache | 14 +- .../resources/python/__init__package.mustache | 22 +- .../src/main/resources/python/api.mustache | 47 ++-- .../src/main/resources/python/model.mustache | 20 +- .../src/main/resources/python/setup.mustache | 8 + .../src/main/resources/python/util.mustache | 17 ++ .../python/SwaggerPetstore-python/Makefile | 35 +++ .../python/SwaggerPetstore-python/README.md | 18 +- .../SwaggerPetstore/__init__.py | 24 +- .../SwaggerPetstore/apis/__init__.py | 14 +- .../SwaggerPetstore/apis/pet_api.py | 222 +++++++----------- .../SwaggerPetstore/apis/store_api.py | 108 ++++----- .../SwaggerPetstore/apis/user_api.py | 206 +++++++--------- .../SwaggerPetstore/models/__init__.py | 16 +- .../SwaggerPetstore/models/category.py | 23 +- .../SwaggerPetstore/models/order.py | 60 ++--- .../SwaggerPetstore/models/pet.py | 60 ++--- .../SwaggerPetstore/models/tag.py | 23 +- .../SwaggerPetstore/models/user.py | 78 ++---- .../SwaggerPetstore/util.py | 17 ++ .../dev-requirements.txt | 4 + .../python/SwaggerPetstore-python/pom.xml | 19 +- .../python/SwaggerPetstore-python/setup.cfg | 10 + .../python/SwaggerPetstore-python/setup.py | 8 + .../tests/test_pet_api.py | 96 ++++---- .../python/SwaggerPetstore-python/tox.ini | 10 + 29 files changed, 551 insertions(+), 662 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/python/util.mustache create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/Makefile create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/setup.cfg create mode 100644 samples/client/petstore/python/SwaggerPetstore-python/tox.ini diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index 7a866dd13b3..bab41e227c2 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -70,6 +70,7 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig supportingFiles.add(new SupportingFile("setup.mustache", eggPackage, "setup.py")); supportingFiles.add(new SupportingFile("swagger.mustache", invokerPackage, "swagger.py")); supportingFiles.add(new SupportingFile("rest.mustache", invokerPackage, "rest.py")); + supportingFiles.add(new SupportingFile("util.mustache", invokerPackage, "util.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", invokerPackage, "__init__.py")); supportingFiles.add(new SupportingFile("__init__model.mustache", modelPackage.replace('.', File.separatorChar), "__init__.py")); supportingFiles.add(new SupportingFile("__init__api.mustache", apiPackage.replace('.', File.separatorChar), "__init__.py")); diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 3b69aba0f82..8cfb970d0de 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -38,5 +38,22 @@ TODO ## Tests -TODO +We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. +Our Makefile handles much of this for you as long as you're running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): + +```sh +$ make test +[... magically installs dependencies and runs tests on your virtualenv] +Ran 182 tests in 1.633s +OK (SKIP=6) +``` + +You can test in various python versions using: + +```sh +$ make test-all +[... tox creates a virtualenv for every platform and runs tests inside of each] +py27: commands succeeded +py34: commands succeeded +``` diff --git a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache index 1597be6991a..b4442b736ff 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__api.mustache @@ -1,15 +1,5 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" from __future__ import absolute_import -import os - -{{#apiInfo}}{{#apis}} -from .{{classVarName}} import {{classname}} +# import apis into api package +{{#apiInfo}}{{#apis}}from .{{classVarName}} import {{classname}} {{/apis}}{{/apiInfo}} - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache index 202879d39fd..7a3f1866ea7 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__model.mustache @@ -1,15 +1,5 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" from __future__ import absolute_import -import os - -{{#models}}{{#model}} -from .{{classVarName}} import {{classname}} +# import models into model package +{{#models}}{{#model}}from .{{classVarName}} import {{classname}} {{/model}}{{/models}} - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache index 704aceb176a..7b48136d3a9 100644 --- a/modules/swagger-codegen/src/main/resources/python/__init__package.mustache +++ b/modules/swagger-codegen/src/main/resources/python/__init__package.mustache @@ -1,24 +1,10 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" from __future__ import absolute_import -import os - -# import models into package -{{#models}}{{#model}} -from .models.{{classVarName}} import {{classname}} +# import models into sdk package +{{#models}}{{#model}}from .models.{{classVarName}} import {{classname}} {{/model}}{{/models}} - -# import apis into package -{{#apiInfo}}{{#apis}} -from .apis.{{classVarName}} import {{classname}} +# import apis into sdk package +{{#apiInfo}}{{#apis}}from .apis.{{classVarName}} import {{classname}} {{/apis}}{{/apiInfo}} - # import ApiClient from .swagger import ApiClient - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/modules/swagger-codegen/src/main/resources/python/api.mustache b/modules/swagger-codegen/src/main/resources/python/api.mustache index e7902c25fc6..b853cbc9c95 100644 --- a/modules/swagger-codegen/src/main/resources/python/api.mustache +++ b/modules/swagger-codegen/src/main/resources/python/api.mustache @@ -19,31 +19,36 @@ Copyright 2015 Reverb Technologies, Inc. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ +from __future__ import absolute_import + import sys import os # python 2 and python 3 compatibility library from six import iteritems +from ..util import remove_none + {{#operations}} class {{classname}}(object): def __init__(self, api_client): - self.api_client = api_client - + self.api_client = api_client {{#operation}} - def {{nickname}}(self, {{#requiredParams}}{{paramName}}{{#defaultValue}} = None{{/defaultValue}}, {{/requiredParams}}**kwargs): + def {{nickname}}(self, {{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}**kwargs): """ {{{summary}}} {{{notes}}} - {{#allParams}} - :param {{dataType}} {{paramName}}: {{{description}}} {{^optional}}(required){{/optional}}{{#optional}}(optional){{/optional}} + {{#allParams}}:param {{dataType}} {{paramName}}: {{{description}}} {{#required}}(required){{/required}}{{#optional}}(optional){{/optional}} {{/allParams}} - :return: {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}None{{/returnType}} """ - + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + if {{paramName}} is None: + raise ValueError("Missing the required parameter `{{paramName}}` when calling `{{nickname}}`") + {{/required}}{{/allParams}} all_params = [{{#allParams}}'{{paramName}}'{{#hasMore}}, {{/hasMore}}{{/allParams}}] params = locals() @@ -56,16 +61,11 @@ class {{classname}}(object): resource_path = '{{path}}'.replace('{format}', 'json') method = '{{httpMethod}}' - path_params = dict({{#pathParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/pathParams}}) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict({{#queryParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/queryParams}}) - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict({{#headerParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/headerParams}}) - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict({{#formParams}}{{^isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}}) - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict({{#formParams}}{{#isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}}) - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict({{#pathParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/pathParams}})) + query_params = remove_none(dict({{#queryParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/queryParams}})) + header_params = remove_none(dict({{#headerParams}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/headerParams}})) + form_params = remove_none(dict({{#formParams}}{{^isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) + files = remove_none(dict({{#formParams}}{{#isFile}}{{baseName}}=params.get('{{paramName}}'){{#hasMore}}, {{/hasMore}}{{/isFile}}{{/formParams}})) body_params = {{#bodyParam}}params.get('{{paramName}}'){{/bodyParam}}{{^bodyParam}}None{{/bodyParam}} accepts = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] @@ -79,7 +79,14 @@ class {{classname}}(object): response={{#returnType}}'{{returnType}}'{{/returnType}}{{^returnType}}None{{/returnType}}) {{#returnType}} return response - {{/returnType}} - {{/operation}} + {{/returnType}}{{/operation}} {{/operations}} -{{newline}} + + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index 9e41e78af7f..62a5d12a04f 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -25,7 +25,6 @@ class {{classname}}(object): Do not edit the class manually. """ - def __init__(self): """ Swagger model @@ -34,22 +33,19 @@ class {{classname}}(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - {{#vars}} - '{{name}}': '{{{datatype}}}'{{#hasMore}}, - {{/hasMore}} - {{/vars}}{{newline}} + {{#vars}}'{{name}}': '{{{datatype}}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} } self.attribute_map = { - {{#vars}} - '{{name}}': '{{baseName}}'{{#hasMore}},{{/hasMore}} - {{/vars}} + {{#vars}}'{{name}}': '{{baseName}}'{{#hasMore}}, + {{/hasMore}}{{/vars}} } - {{#vars}} - {{#description}}#{{description}} - {{/description}} - self.{{name}} = None # {{{datatype}}} + {{#description}}# {{description}}{{/description}} + self.{{name}} = None # {{{datatype}}} {{/vars}} {{/model}} {{/models}} + + diff --git a/modules/swagger-codegen/src/main/resources/python/setup.mustache b/modules/swagger-codegen/src/main/resources/python/setup.mustache index 64609c37dd1..a049057c920 100644 --- a/modules/swagger-codegen/src/main/resources/python/setup.mustache +++ b/modules/swagger-codegen/src/main/resources/python/setup.mustache @@ -30,3 +30,11 @@ setup( ) {{/hasMore}}{{/apis}}{{/apiInfo}} + + + + + + + + diff --git a/modules/swagger-codegen/src/main/resources/python/util.mustache b/modules/swagger-codegen/src/main/resources/python/util.mustache new file mode 100644 index 00000000000..1137a5d2d23 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/python/util.mustache @@ -0,0 +1,17 @@ +from six import iteritems + +def remove_none(obj): + if isinstance(obj, (list, tuple, set)): + return type(obj)(remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((remove_none(k), remove_none(v)) + for k, v in iteritems(obj) if k is not None and v is not None) + else: + return obj + + +def inspect_vars(obj): + if not hasattr(obj, '__dict__'): + return obj + else: + return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/Makefile b/samples/client/petstore/python/SwaggerPetstore-python/Makefile new file mode 100644 index 00000000000..8acdd7cc5ac --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/Makefile @@ -0,0 +1,35 @@ +REQUIREMENTS_FILE=dev-requirements.txt +REQUIREMENTS_OUT=dev-requirements.txt.log +SETUP_OUT=*.egg-info + +virtualenv: +ifndef VIRTUAL_ENV + $(error Must be run inside of a virtualenv\ + http://docs.python-guide.org/en/latest/dev/virtualenvs/) +endif + +setup: virtualenv $(SETUP_OUT) + +$(SETUP_OUT): setup.py setup.cfg + python setup.py develop + touch $(SETUP_OUT) + +$(REQUIREMENTS_OUT): $(REQUIREMENTS_FILE) + pip install -r $(REQUIREMENTS_FILE) | tee -a $(REQUIREMENTS_OUT) + python setup.py develop + +clean: + find . -name "*.py[oc]" -delete + find . -name "__pycache__" -delete + rm -f $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + +requirements: setup $(REQUIREMENTS_OUT) + +test: requirements + nosetests + +test-all: requirements + tox + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/README.md b/samples/client/petstore/python/SwaggerPetstore-python/README.md index 3b69aba0f82..833151c5769 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/README.md +++ b/samples/client/petstore/python/SwaggerPetstore-python/README.md @@ -38,5 +38,21 @@ TODO ## Tests -TODO +We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. +Our Makefile handles much of this for you as long as you're running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): +```sh +$ make test +[... magically installs dependencies and runs tests on your virtualenv] +Ran 182 tests in 1.633s +OK (SKIP=6) +``` + +You can test in various python versions using: + +```sh +$ make test-all +[... tox creates a virtualenv for every platform and runs tests inside of each] +py27: commands succeeded +py34: commands succeeded +``` diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py index 91427e9d686..9d4b2db3de5 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/__init__.py @@ -1,36 +1,16 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" from __future__ import absolute_import -import os - -# import models into package - +# import models into sdk package from .models.user import User - from .models.category import Category - from .models.pet import Pet - from .models.tag import Tag - from .models.order import Order - -# import apis into package - +# import apis into sdk package from .apis.user_api import UserApi - from .apis.pet_api import PetApi - from .apis.store_api import StoreApi - # import ApiClient from .swagger import ApiClient - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py index e4f2bbde841..128b25dad82 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/__init__.py @@ -1,19 +1,7 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" from __future__ import absolute_import -import os - - +# import apis into api package from .user_api import UserApi - from .pet_api import PetApi - from .store_api import StoreApi - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index 8a21d3900d1..e6bd35514f4 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -19,30 +19,31 @@ Copyright 2015 Reverb Technologies, Inc. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ +from __future__ import absolute_import + import sys import os # python 2 and python 3 compatibility library from six import iteritems +from ..util import remove_none + class PetApi(object): def __init__(self, api_client): - self.api_client = api_client - + self.api_client = api_client def update_pet(self, **kwargs): """ Update an existing pet + :param Pet body: Pet object that needs to be added to the store - :param Pet body: Pet object that needs to be added to the store (required) - - :return: None """ - + all_params = ['body'] params = locals() @@ -55,16 +56,11 @@ class PetApi(object): resource_path = '/pet'.replace('{format}', 'json') method = 'PUT' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -77,19 +73,16 @@ class PetApi(object): body=body_params, post_params=form_params, files=files, response=None) - def add_pet(self, **kwargs): """ Add a new pet to the store + :param Pet body: Pet object that needs to be added to the store - :param Pet body: Pet object that needs to be added to the store (required) - - :return: None """ - + all_params = ['body'] params = locals() @@ -102,16 +95,11 @@ class PetApi(object): resource_path = '/pet'.replace('{format}', 'json') method = 'POST' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -124,19 +112,16 @@ class PetApi(object): body=body_params, post_params=form_params, files=files, response=None) - def find_pets_by_status(self, **kwargs): """ Finds Pets by status Multiple status values can be provided with comma seperated strings + :param list[str] status: Status values that need to be considered for filter - :param list[str] status: Status values that need to be considered for filter (required) - - :return: list[Pet] """ - + all_params = ['status'] params = locals() @@ -149,16 +134,11 @@ class PetApi(object): resource_path = '/pet/findByStatus'.replace('{format}', 'json') method = 'GET' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict(status=params.get('status')) - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict(status=params.get('status'))) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -173,19 +153,16 @@ class PetApi(object): return response - def find_pets_by_tags(self, **kwargs): """ Finds Pets by tags Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + :param list[str] tags: Tags to filter by - :param list[str] tags: Tags to filter by (required) - - :return: list[Pet] """ - + all_params = ['tags'] params = locals() @@ -198,16 +175,11 @@ class PetApi(object): resource_path = '/pet/findByTags'.replace('{format}', 'json') method = 'GET' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict(tags=params.get('tags')) - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict(tags=params.get('tags'))) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -222,19 +194,20 @@ class PetApi(object): return response - - def get_pet_by_id(self, **kwargs): + def get_pet_by_id(self, pet_id, **kwargs): """ Find pet by ID Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - :param int pet_id: ID of pet that needs to be fetched (required) - :return: Pet """ - + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `get_pet_by_id`") + all_params = ['pet_id'] params = locals() @@ -247,16 +220,11 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'GET' - path_params = dict(petId=params.get('pet_id')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -271,23 +239,22 @@ class PetApi(object): return response - - def update_pet_with_form(self, **kwargs): + def update_pet_with_form(self, pet_id, **kwargs): """ Updates a pet in the store with form data - :param str pet_id: ID of pet that needs to be updated (required) + :param str name: Updated name of the pet + :param str status: Updated status of the pet - :param str name: Updated name of the pet (required) - - :param str status: Updated status of the pet (required) - - :return: None """ - + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `update_pet_with_form`") + all_params = ['pet_id', 'name', 'status'] params = locals() @@ -300,16 +267,11 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'POST' - path_params = dict(petId=params.get('pet_id')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict(name=params.get('name'), status=params.get('status')) - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict(name=params.get('name'), status=params.get('status'))) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -322,21 +284,21 @@ class PetApi(object): body=body_params, post_params=form_params, files=files, response=None) - - def delete_pet(self, **kwargs): + def delete_pet(self, pet_id, **kwargs): """ Deletes a pet - - :param str api_key: (required) - + :param str api_key: :param int pet_id: Pet id to delete (required) - :return: None """ - + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `delete_pet`") + all_params = ['api_key', 'pet_id'] params = locals() @@ -349,16 +311,11 @@ class PetApi(object): resource_path = '/pet/{petId}'.replace('{format}', 'json') method = 'DELETE' - path_params = dict(petId=params.get('pet_id')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict(api_key=params.get('api_key')) - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict(api_key=params.get('api_key'))) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -371,23 +328,22 @@ class PetApi(object): body=body_params, post_params=form_params, files=files, response=None) - - def upload_file(self, **kwargs): + def upload_file(self, pet_id, **kwargs): """ uploads an image - :param int pet_id: ID of pet to update (required) + :param str additional_metadata: Additional data to pass to server + :param file file: file to upload - :param str additional_metadata: Additional data to pass to server (required) - - :param file file: file to upload (required) - - :return: None """ - + + # verify the required parameter 'pet_id' is set + if pet_id is None: + raise ValueError("Missing the required parameter `pet_id` when calling `upload_file`") + all_params = ['pet_id', 'additional_metadata', 'file'] params = locals() @@ -400,16 +356,11 @@ class PetApi(object): resource_path = '/pet/{petId}/uploadImage'.replace('{format}', 'json') method = 'POST' - path_params = dict(petId=params.get('pet_id')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict(additionalMetadata=params.get('additional_metadata'), ) - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict(file=params.get('file')) - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(petId=params.get('pet_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict(additionalMetadata=params.get('additional_metadata'), )) + files = remove_none(dict(file=params.get('file'))) body_params = None accepts = ['application/json', 'application/xml'] @@ -422,5 +373,12 @@ class PetApi(object): body=body_params, post_params=form_params, files=files, response=None) - + + + + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py index 37cfb524ad0..0df9a84fe75 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/store_api.py @@ -19,17 +19,20 @@ Copyright 2015 Reverb Technologies, Inc. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ +from __future__ import absolute_import + import sys import os # python 2 and python 3 compatibility library from six import iteritems +from ..util import remove_none + class StoreApi(object): def __init__(self, api_client): - self.api_client = api_client - + self.api_client = api_client def get_inventory(self, **kwargs): """ @@ -37,10 +40,9 @@ class StoreApi(object): Returns a map of status codes to quantities - :return: map(String, int) """ - + all_params = [] params = locals() @@ -53,16 +55,11 @@ class StoreApi(object): resource_path = '/store/inventory'.replace('{format}', 'json') method = 'GET' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -77,19 +74,16 @@ class StoreApi(object): return response - def place_order(self, **kwargs): """ Place an order for a pet + :param Order body: order placed for purchasing the pet - :param Order body: order placed for purchasing the pet (required) - - :return: Order """ - + all_params = ['body'] params = locals() @@ -102,16 +96,11 @@ class StoreApi(object): resource_path = '/store/order'.replace('{format}', 'json') method = 'POST' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -126,19 +115,20 @@ class StoreApi(object): return response - - def get_order_by_id(self, **kwargs): + def get_order_by_id(self, order_id, **kwargs): """ Find purchase order by ID For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - :param str order_id: ID of pet that needs to be fetched (required) - :return: Order """ - + + # verify the required parameter 'order_id' is set + if order_id is None: + raise ValueError("Missing the required parameter `order_id` when calling `get_order_by_id`") + all_params = ['order_id'] params = locals() @@ -151,16 +141,11 @@ class StoreApi(object): resource_path = '/store/order/{orderId}'.replace('{format}', 'json') method = 'GET' - path_params = dict(orderId=params.get('order_id')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(orderId=params.get('order_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -175,19 +160,20 @@ class StoreApi(object): return response - - def delete_order(self, **kwargs): + def delete_order(self, order_id, **kwargs): """ Delete purchase order by ID For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - :param str order_id: ID of the order that needs to be deleted (required) - :return: None """ - + + # verify the required parameter 'order_id' is set + if order_id is None: + raise ValueError("Missing the required parameter `order_id` when calling `delete_order`") + all_params = ['order_id'] params = locals() @@ -200,16 +186,11 @@ class StoreApi(object): resource_path = '/store/order/{orderId}'.replace('{format}', 'json') method = 'DELETE' - path_params = dict(orderId=params.get('order_id')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(orderId=params.get('order_id'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -222,5 +203,12 @@ class StoreApi(object): body=body_params, post_params=form_params, files=files, response=None) - + + + + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py index 158a03f14d2..720843bd508 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/user_api.py @@ -19,30 +19,31 @@ Copyright 2015 Reverb Technologies, Inc. NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ +from __future__ import absolute_import + import sys import os # python 2 and python 3 compatibility library from six import iteritems +from ..util import remove_none + class UserApi(object): def __init__(self, api_client): - self.api_client = api_client - + self.api_client = api_client def create_user(self, **kwargs): """ Create user This can only be done by the logged in user. + :param User body: Created user object - :param User body: Created user object (required) - - :return: None """ - + all_params = ['body'] params = locals() @@ -55,16 +56,11 @@ class UserApi(object): resource_path = '/user'.replace('{format}', 'json') method = 'POST' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -77,19 +73,16 @@ class UserApi(object): body=body_params, post_params=form_params, files=files, response=None) - def create_users_with_array_input(self, **kwargs): """ Creates list of users with given input array + :param list[User] body: List of user object - :param list[User] body: List of user object (required) - - :return: None """ - + all_params = ['body'] params = locals() @@ -102,16 +95,11 @@ class UserApi(object): resource_path = '/user/createWithArray'.replace('{format}', 'json') method = 'POST' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -124,19 +112,16 @@ class UserApi(object): body=body_params, post_params=form_params, files=files, response=None) - def create_users_with_list_input(self, **kwargs): """ Creates list of users with given input array + :param list[User] body: List of user object - :param list[User] body: List of user object (required) - - :return: None """ - + all_params = ['body'] params = locals() @@ -149,16 +134,11 @@ class UserApi(object): resource_path = '/user/createWithList'.replace('{format}', 'json') method = 'POST' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -171,21 +151,17 @@ class UserApi(object): body=body_params, post_params=form_params, files=files, response=None) - def login_user(self, **kwargs): """ Logs user into the system + :param str username: The user name for login + :param str password: The password for login in clear text - :param str username: The user name for login (required) - - :param str password: The password for login in clear text (required) - - :return: str """ - + all_params = ['username', 'password'] params = locals() @@ -198,16 +174,11 @@ class UserApi(object): resource_path = '/user/login'.replace('{format}', 'json') method = 'GET' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict(username=params.get('username'), password=params.get('password')) - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict(username=params.get('username'), password=params.get('password'))) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -222,17 +193,15 @@ class UserApi(object): return response - def logout_user(self, **kwargs): """ Logs out current logged in user session - :return: None """ - + all_params = [] params = locals() @@ -245,16 +214,11 @@ class UserApi(object): resource_path = '/user/logout'.replace('{format}', 'json') method = 'GET' - path_params = dict() - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict()) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -267,19 +231,20 @@ class UserApi(object): body=body_params, post_params=form_params, files=files, response=None) - - def get_user_by_name(self, **kwargs): + def get_user_by_name(self, username, **kwargs): """ Get user by user name - :param str username: The name that needs to be fetched. Use user1 for testing. (required) - :return: User """ - + + # verify the required parameter 'username' is set + if username is None: + raise ValueError("Missing the required parameter `username` when calling `get_user_by_name`") + all_params = ['username'] params = locals() @@ -292,16 +257,11 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'GET' - path_params = dict(username=params.get('username')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(username=params.get('username'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -316,21 +276,21 @@ class UserApi(object): return response - - def update_user(self, **kwargs): + def update_user(self, username, **kwargs): """ Updated user This can only be done by the logged in user. - :param str username: name that need to be deleted (required) + :param User body: Updated user object - :param User body: Updated user object (required) - - :return: None """ - + + # verify the required parameter 'username' is set + if username is None: + raise ValueError("Missing the required parameter `username` when calling `update_user`") + all_params = ['username', 'body'] params = locals() @@ -343,16 +303,11 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'PUT' - path_params = dict(username=params.get('username')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(username=params.get('username'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = params.get('body') accepts = ['application/json', 'application/xml'] @@ -365,19 +320,20 @@ class UserApi(object): body=body_params, post_params=form_params, files=files, response=None) - - def delete_user(self, **kwargs): + def delete_user(self, username, **kwargs): """ Delete user This can only be done by the logged in user. - :param str username: The name that needs to be deleted (required) - :return: None """ - + + # verify the required parameter 'username' is set + if username is None: + raise ValueError("Missing the required parameter `username` when calling `delete_user`") + all_params = ['username'] params = locals() @@ -390,16 +346,11 @@ class UserApi(object): resource_path = '/user/{username}'.replace('{format}', 'json') method = 'DELETE' - path_params = dict(username=params.get('username')) - path_params = {k: v for k, v in iteritems(path_params) if v} - query_params = dict() - query_params = {k: v for k, v in iteritems(query_params) if v} - header_params = dict() - header_params = {k: v for k, v in iteritems(header_params) if v} - form_params = dict() - form_params = {k: v for k, v in iteritems(form_params) if v} - files = dict() - files = {k: v for k, v in iteritems(files) if v} + path_params = remove_none(dict(username=params.get('username'))) + query_params = remove_none(dict()) + header_params = remove_none(dict()) + form_params = remove_none(dict()) + files = remove_none(dict()) body_params = None accepts = ['application/json', 'application/xml'] @@ -412,5 +363,12 @@ class UserApi(object): body=body_params, post_params=form_params, files=files, response=None) - + + + + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py index 96d0a37ec60..de307a26503 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/__init__.py @@ -1,23 +1,9 @@ -#!/usr/bin/env python -"""Add all of the modules in the current directory to __all__""" from __future__ import absolute_import -import os - - +# import models into model package from .user import User - from .category import Category - from .pet import Pet - from .tag import Tag - from .order import Order - -__all__ = [] - -for module in os.listdir(os.path.dirname(__file__)): - if module != '__init__.py' and module[-3:] == '.py': - __all__.append(module[:-3]) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py index c9c009dd68f..cfa9811c487 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py @@ -23,7 +23,6 @@ class Category(object): Do not edit the class manually. """ - def __init__(self): """ Swagger model @@ -32,26 +31,20 @@ class Category(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - 'id': 'int', - - 'name': 'str' - } self.attribute_map = { - 'id': 'id', - 'name': 'name' - } + + + self.id = None # int + + + self.name = None # str + + - - - self.id = None # int - - - self.name = None # str - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py index ab5384ee270..25c6e8f5462 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py @@ -23,7 +23,6 @@ class Order(object): Do not edit the class manually. """ - def __init__(self): """ Swagger model @@ -32,59 +31,40 @@ class Order(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - 'id': 'int', - - 'pet_id': 'int', - - 'quantity': 'int', - - 'ship_date': 'DateTime', - - 'status': 'str', - - 'complete': 'bool' - } self.attribute_map = { - 'id': 'id', - 'pet_id': 'petId', - 'quantity': 'quantity', - 'ship_date': 'shipDate', - 'status': 'status', - 'complete': 'complete' - } + + + self.id = None # int + + + self.pet_id = None # int + + + self.quantity = None # int + + + self.ship_date = None # DateTime + + # Order Status + self.status = None # str + + + self.complete = None # bool + + - - - self.id = None # int - - - self.pet_id = None # int - - - self.quantity = None # int - - - self.ship_date = None # DateTime - - #Order Status - - self.status = None # str - - - self.complete = None # bool - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py index 8266556946d..021dc00d0fd 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py @@ -23,7 +23,6 @@ class Pet(object): Do not edit the class manually. """ - def __init__(self): """ Swagger model @@ -32,59 +31,40 @@ class Pet(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - 'id': 'int', - - 'category': 'Category', - - 'name': 'str', - - 'photo_urls': 'list[str]', - - 'tags': 'list[Tag]', - - 'status': 'str' - } self.attribute_map = { - 'id': 'id', - 'category': 'category', - 'name': 'name', - 'photo_urls': 'photoUrls', - 'tags': 'tags', - 'status': 'status' - } + + + self.id = None # int + + + self.category = None # Category + + + self.name = None # str + + + self.photo_urls = None # list[str] + + + self.tags = None # list[Tag] + + # pet status in the store + self.status = None # str + + - - - self.id = None # int - - - self.category = None # Category - - - self.name = None # str - - - self.photo_urls = None # list[str] - - - self.tags = None # list[Tag] - - #pet status in the store - - self.status = None # str - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py index dd8f0c0057a..474aa1f03c9 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py @@ -23,7 +23,6 @@ class Tag(object): Do not edit the class manually. """ - def __init__(self): """ Swagger model @@ -32,26 +31,20 @@ class Tag(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - 'id': 'int', - - 'name': 'str' - } self.attribute_map = { - 'id': 'id', - 'name': 'name' - } + + + self.id = None # int + + + self.name = None # str + + - - - self.id = None # int - - - self.name = None # str - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py index 2fd47ee47e5..a37ad9f0879 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py @@ -23,7 +23,6 @@ class User(object): Do not edit the class manually. """ - def __init__(self): """ Swagger model @@ -32,75 +31,50 @@ class User(object): :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { - 'id': 'int', - - 'username': 'str', - - 'first_name': 'str', - - 'last_name': 'str', - - 'email': 'str', - - 'password': 'str', - - 'phone': 'str', - - 'user_status': 'int' - } self.attribute_map = { - 'id': 'id', - 'username': 'username', - 'first_name': 'firstName', - 'last_name': 'lastName', - 'email': 'email', - 'password': 'password', - 'phone': 'phone', - 'user_status': 'userStatus' - } + + + self.id = None # int + + + self.username = None # str + + + self.first_name = None # str + + + self.last_name = None # str + + + self.email = None # str + + + self.password = None # str + + + self.phone = None # str + + # User Status + self.user_status = None # int + + - - - self.id = None # int - - - self.username = None # str - - - self.first_name = None # str - - - self.last_name = None # str - - - self.email = None # str - - - self.password = None # str - - - self.phone = None # str - - #User Status - - self.user_status = None # int - diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py new file mode 100644 index 00000000000..1137a5d2d23 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/util.py @@ -0,0 +1,17 @@ +from six import iteritems + +def remove_none(obj): + if isinstance(obj, (list, tuple, set)): + return type(obj)(remove_none(x) for x in obj if x is not None) + elif isinstance(obj, dict): + return type(obj)((remove_none(k), remove_none(v)) + for k, v in iteritems(obj) if k is not None and v is not None) + else: + return obj + + +def inspect_vars(obj): + if not hasattr(obj, '__dict__'): + return obj + else: + return {k: inspect_vars(getattr(obj, k)) for k in dir(obj)} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt new file mode 100644 index 00000000000..01a2e25f1c7 --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/dev-requirements.txt @@ -0,0 +1,4 @@ +nose +tox +coverage +randomize diff --git a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml b/samples/client/petstore/python/SwaggerPetstore-python/pom.xml index c06d3a1cdf6..3ff908ed770 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml +++ b/samples/client/petstore/python/SwaggerPetstore-python/pom.xml @@ -26,21 +26,6 @@ exec-maven-plugin 1.2.1 - - nose-install - pre-integration-test - - exec - - - pip - - install - nose - --user - - - nose-test integration-test @@ -48,9 +33,9 @@ exec - nosetests + make - -v + test-all diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg b/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg new file mode 100644 index 00000000000..f1ef0cc4d0f --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg @@ -0,0 +1,10 @@ +[nosetests] +logging-clear-handlers=true +verbosity=2 +randomize=true +with-coverage=true +cover-package=SwaggerPetstore +cover-erase=true + +[flake8] +max-line-length=99 diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.py b/samples/client/petstore/python/SwaggerPetstore-python/setup.py index 946274c5acd..fd0b786efa3 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/setup.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.py @@ -30,3 +30,11 @@ setup( ) + + + + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index 92b4e70dbce..88a19f61d3c 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -31,15 +31,15 @@ class PetApiTests(unittest.TestCase): def setUpModels(self): self.category = SwaggerPetstore.Category() - self.category.id = 1010 + self.category.id = int(time.time()) self.category.name = "dog" self.tag = SwaggerPetstore.Tag() - self.tag.id = 1010 + self.tag.id = int(time.time()) self.tag.name = "blank" self.pet = SwaggerPetstore.Pet() - self.pet.id = 1010 + self.pet.id = int(time.time()) self.pet.name = "hello kity" - self.pet.photo_urls = ["sample urls"] + self.pet.photo_urls = ["http://foo.bar.com/1", "http://foo.bar.com/2"] self.pet.status = "sold" self.pet.category = self.category self.pet.tags = [self.tag] @@ -49,48 +49,55 @@ class PetApiTests(unittest.TestCase): self.test_file_dir = os.path.realpath(self.test_file_dir) self.foo = os.path.join(self.test_file_dir, "foo.png") - def test_1_add_pet(self): - try: - self.pet_api.add_pet(body=self.pet) - except ErrorResponse as e: - self.fail("add_pet() raised {0} unexpectedly".format(type(e))) + def test_add_pet_and_get_pet_by_id(self): + self.pet_api.add_pet(body=self.pet) - def test_2_get_pet_by_id(self): - self.assertEqual( - dir(self.pet_api.get_pet_by_id(pet_id=self.pet.id)), - dir(self.pet) - ) + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertIsNotNone(fetched.category) + self.assertEqual(self.pet.category.name, fetched.category.name) - def test_3_update_pet(self): - try: - self.pet.name = "hello kity with updated" - self.pet_api.update_pet(body=self.pet) - except ErrorResponse as e: - self.fail("update_pet() raised {0} unexpectedly".format(type(e))) + def test_update_pet(self): + self.pet.name = "hello kity with updated" + self.pet_api.update_pet(body=self.pet) - def test_4_find_pets_by_status(self): + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertIsNotNone(fetched) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(self.pet.name, fetched.name) + self.assertIsNotNone(fetched.category) + self.assertEqual(fetched.category.name, self.pet.category.name) + + def test_find_pets_by_status(self): + self.pet_api.add_pet(body=self.pet) + self.assertIn( - dir(self.pet), - list(map(dir, self.pet_api.find_pets_by_status(status=["sold"]))) + self.pet.id, + list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_status(status=[self.pet.status]))) ) - def test_5_find_pets_by_tags(self): + def test_find_pets_by_tags(self): + self.pet_api.add_pet(body=self.pet) + self.assertIn( - dir(self.pet), - list(map(dir, self.pet_api.find_pets_by_tags(tags=["blank"]))) + self.pet.id, + list(map(lambda x: getattr(x, 'id'), self.pet_api.find_pets_by_tags(tags=[self.tag.name]))) ) - def test_6_update_pet_with_form(self): - try: - name = "hello kity with form updated" - status = "pending" - self.pet_api.update_pet_with_form( - pet_id=self.pet.id, name=name, status=status - ) - except ErrorResponse as e: - self.fail("update_pet_with_form() raised {0} unexpectedly".format(type(e))) + def test_update_pet_with_form(self): + self.pet_api.add_pet(body=self.pet) + + name = "hello kity with form updated" + status = "pending" + self.pet_api.update_pet_with_form(pet_id=self.pet.id, name=name, status=status) - def test_7_upload_file(self): + fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) + self.assertEqual(self.pet.id, fetched.id) + self.assertEqual(self.pet.name, fetched.name) + self.assertEqual(self.pet.status, fetched.status) + + def test_upload_file(self): try: additional_metadata = "special" self.pet_api.upload_file( @@ -101,13 +108,20 @@ class PetApiTests(unittest.TestCase): except ErrorResponse as e: self.fail("upload_file() raised {0} unexpectedly".format(type(e))) - def test_8_delete_pet(self): + def test_delete_pet(self): + self.pet_api.add_pet(body=self.pet) + self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") + try: - api_key = "special-key" - self.pet_api.delete_pet(pet_id=self.pet.id, api_key=api_key) + self.pet_api.get_pet_by_id(pet_id=self.pet.id) + raise "expected an error" except ErrorResponse as e: - self.fail("delete_pet() raised {0} unexpectedly".format(type(e))) - + self.assertEqual(404, e.status) if __name__ == '__main__': unittest.main() + + + + + diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tox.ini b/samples/client/petstore/python/SwaggerPetstore-python/tox.ini new file mode 100644 index 00000000000..9f62f3845bf --- /dev/null +++ b/samples/client/petstore/python/SwaggerPetstore-python/tox.ini @@ -0,0 +1,10 @@ +[tox] +envlist = py27, py34 + +[testenv] +deps= -r{toxinidir}/dev-requirements.txt +commands= + nosetests \ + [] +setenv = + PYTHONWARNINGS=always::DeprecationWarning From 6826a1d7dfe4796a93d68d1e6012417f58a0c68a Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 15 May 2015 14:51:51 +0800 Subject: [PATCH 27/75] updated readme.mustache in python client --- .../src/main/resources/python/README.mustache | 10 ++++++---- .../petstore/python/SwaggerPetstore-python/README.md | 11 +++++++---- 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 8cfb970d0de..2c5c75fc764 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -44,8 +44,9 @@ Our Makefile handles much of this for you as long as you're running it inside of ```sh $ make test [... magically installs dependencies and runs tests on your virtualenv] -Ran 182 tests in 1.633s -OK (SKIP=6) +Ran 7 tests in 19.289s + +OK ``` You can test in various python versions using: @@ -53,7 +54,8 @@ You can test in various python versions using: ```sh $ make test-all [... tox creates a virtualenv for every platform and runs tests inside of each] -py27: commands succeeded -py34: commands succeeded + py27: commands succeeded + py34: commands succeeded + congratulations :) ``` diff --git a/samples/client/petstore/python/SwaggerPetstore-python/README.md b/samples/client/petstore/python/SwaggerPetstore-python/README.md index 833151c5769..2c5c75fc764 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/README.md +++ b/samples/client/petstore/python/SwaggerPetstore-python/README.md @@ -44,8 +44,9 @@ Our Makefile handles much of this for you as long as you're running it inside of ```sh $ make test [... magically installs dependencies and runs tests on your virtualenv] -Ran 182 tests in 1.633s -OK (SKIP=6) +Ran 7 tests in 19.289s + +OK ``` You can test in various python versions using: @@ -53,6 +54,8 @@ You can test in various python versions using: ```sh $ make test-all [... tox creates a virtualenv for every platform and runs tests inside of each] -py27: commands succeeded -py34: commands succeeded + py27: commands succeeded + py34: commands succeeded + congratulations :) ``` + From c06cb38d6459ad08bcb833acb4a759046d6b43db Mon Sep 17 00:00:00 2001 From: geekerzp Date: Fri, 15 May 2015 17:49:56 +0800 Subject: [PATCH 28/75] updated objc client to support iso8601 datetime format --- .../codegen/languages/ObjcClientCodegen.java | 4 +- .../objc/JSONValueTransformer+ISO8601.h | 6 +++ .../objc/JSONValueTransformer+ISO8601.m | 10 +++++ .../src/main/resources/objc/Podfile.mustache | 1 + .../src/main/resources/objc/SWGDate.h | 12 ------ .../src/main/resources/objc/SWGDate.m | 34 ----------------- .../PetstoreClient.xcodeproj/project.pbxproj | 14 ++++--- samples/client/petstore/objc/Podfile | 1 + samples/client/petstore/objc/Podfile.lock | 37 ++++++++++--------- .../client/JSONValueTransformer+ISO8601.h | 6 +++ .../client/JSONValueTransformer+ISO8601.m | 10 +++++ samples/client/petstore/objc/client/SWGDate.h | 12 ------ samples/client/petstore/objc/client/SWGDate.m | 34 ----------------- .../client/petstore/objc/client/SWGObject.h | 1 + 14 files changed, 65 insertions(+), 117 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h create mode 100644 modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m delete mode 100644 modules/swagger-codegen/src/main/resources/objc/SWGDate.h delete mode 100644 modules/swagger-codegen/src/main/resources/objc/SWGDate.m create mode 100644 samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h create mode 100644 samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m delete mode 100644 samples/client/petstore/objc/client/SWGDate.h delete mode 100644 samples/client/petstore/objc/client/SWGDate.m 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 b7c38c703ca..d1e227ce744 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 @@ -120,8 +120,8 @@ public class ObjcClientCodegen extends DefaultCodegen implements CodegenConfig { supportingFiles.add(new SupportingFile("SWGApiClient.m", sourceFolder, "SWGApiClient.m")); supportingFiles.add(new SupportingFile("SWGFile.h", sourceFolder, "SWGFile.h")); supportingFiles.add(new SupportingFile("SWGFile.m", sourceFolder, "SWGFile.m")); - supportingFiles.add(new SupportingFile("SWGDate.h", sourceFolder, "SWGDate.h")); - supportingFiles.add(new SupportingFile("SWGDate.m", sourceFolder, "SWGDate.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.m", sourceFolder, "JSONValueTransformer+ISO8601.m")); + supportingFiles.add(new SupportingFile("JSONValueTransformer+ISO8601.h", sourceFolder, "JSONValueTransformer+ISO8601.h")); supportingFiles.add(new SupportingFile("Podfile.mustache", "", "Podfile")); } diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..832f485f4f0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.h @@ -0,0 +1,6 @@ +#import +#import +#import + +@interface JSONValueTransformer (ISO8601) +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..cec8bdeea27 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/objc/JSONValueTransformer+ISO8601.m @@ -0,0 +1,10 @@ +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache b/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache index 1a9d463c86a..c61ab59dd8f 100644 --- a/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/Podfile.mustache @@ -2,3 +2,4 @@ platform :ios, '6.0' xcodeproj '{{projectName}}/{{projectName}}.xcodeproj' pod 'AFNetworking', '~> 2.1' pod 'JSONModel', '~> 1.0' +pod 'ISO8601' diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGDate.h b/modules/swagger-codegen/src/main/resources/objc/SWGDate.h deleted file mode 100644 index 2c6c7cfe01b..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/SWGDate.h +++ /dev/null @@ -1,12 +0,0 @@ -#import -#import "SWGObject.h" - -@interface SWGDate : SWGObject { -@private - NSDate *_date; -} -@property(nonatomic, readonly) NSDate* date; - -- (id) initWithValues: (NSString*)input; --(NSString*) toString; -@end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/objc/SWGDate.m b/modules/swagger-codegen/src/main/resources/objc/SWGDate.m deleted file mode 100644 index 07a1405626b..00000000000 --- a/modules/swagger-codegen/src/main/resources/objc/SWGDate.m +++ /dev/null @@ -1,34 +0,0 @@ -#import "SWGDate.h" - -@implementation SWGDate - -@synthesize date = _date; - -- (id) initWithValues:(NSString*)input { - if([input isKindOfClass:[NSString class]]){ - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - _date = [df dateFromString:input]; - } - else if([input isKindOfClass:[NSNumber class]]) { - NSTimeInterval interval = [input doubleValue]; - _date = [[NSDate alloc] initWithTimeIntervalSince1970:interval]; - } - return self; -} - --(NSString*) toString { - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - return [df stringFromDate:_date]; -} - -@end \ No newline at end of file diff --git a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj index c22d57fa0ac..a3f7b4cae6b 100644 --- a/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj +++ b/samples/client/petstore/objc/PetstoreClient/PetstoreClient.xcodeproj/project.pbxproj @@ -8,6 +8,8 @@ /* Begin PBXBuildFile section */ BA525648922D4C0E9F44D4F1 /* libPods.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 73DA4F1067C343C3962F1542 /* libPods.a */; }; + CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; + CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */ = {isa = PBXBuildFile; fileRef = CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */; }; EA66999A1811D2FA00A70D03 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA6699991811D2FA00A70D03 /* Foundation.framework */; }; EA66999C1811D2FA00A70D03 /* CoreGraphics.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999B1811D2FA00A70D03 /* CoreGraphics.framework */; }; EA66999E1811D2FA00A70D03 /* UIKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EA66999D1811D2FA00A70D03 /* UIKit.framework */; }; @@ -28,7 +30,6 @@ EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */ = {isa = PBXBuildFile; fileRef = EA6699C71811D2FB00A70D03 /* PetApiTest.m */; }; 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 */; }; EAEA85E71811D3AE00F06E69 /* SWGFile.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D31811D3AE00F06E69 /* SWGFile.m */; }; EAEA85E81811D3AE00F06E69 /* SWGObject.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D51811D3AE00F06E69 /* SWGObject.m */; }; EAEA85E91811D3AE00F06E69 /* SWGOrder.m in Sources */ = {isa = PBXBuildFile; fileRef = EAEA85D71811D3AE00F06E69 /* SWGOrder.m */; }; @@ -54,6 +55,8 @@ /* Begin PBXFileReference section */ 73DA4F1067C343C3962F1542 /* libPods.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = libPods.a; sourceTree = BUILT_PRODUCTS_DIR; }; A425648B5C0A4849C7668069 /* Pods.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.release.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.release.xcconfig"; sourceTree = ""; }; + CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "JSONValueTransformer+ISO8601.h"; sourceTree = ""; }; + CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "JSONValueTransformer+ISO8601.m"; sourceTree = ""; }; E2B6DA00BE52336E23783686 /* Pods.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = Pods.debug.xcconfig; path = "../Pods/Target Support Files/Pods/Pods.debug.xcconfig"; sourceTree = ""; }; EA6699961811D2FA00A70D03 /* PetstoreClient.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = PetstoreClient.app; sourceTree = BUILT_PRODUCTS_DIR; }; EA6699991811D2FA00A70D03 /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; }; @@ -84,8 +87,6 @@ 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 = ""; }; EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGCategory.m; sourceTree = ""; }; - EAEA85D01811D3AE00F06E69 /* SWGDate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGDate.h; sourceTree = ""; }; - EAEA85D11811D3AE00F06E69 /* SWGDate.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGDate.m; sourceTree = ""; }; EAEA85D21811D3AE00F06E69 /* SWGFile.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGFile.h; sourceTree = ""; }; EAEA85D31811D3AE00F06E69 /* SWGFile.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = SWGFile.m; sourceTree = ""; }; EAEA85D41811D3AE00F06E69 /* SWGObject.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SWGObject.h; sourceTree = ""; }; @@ -224,14 +225,14 @@ EAEA85CB1811D3AE00F06E69 /* client */ = { isa = PBXGroup; children = ( + CFD1B66E1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.h */, + CFD1B66F1B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m */, EA8B8AA21AC6683700638FBB /* SWGQueryParamCollection.h */, EA8B8AA31AC6683700638FBB /* SWGQueryParamCollection.m */, EAEA85CC1811D3AE00F06E69 /* SWGApiClient.h */, EAEA85CD1811D3AE00F06E69 /* SWGApiClient.m */, EAEA85CE1811D3AE00F06E69 /* SWGCategory.h */, EAEA85CF1811D3AE00F06E69 /* SWGCategory.m */, - EAEA85D01811D3AE00F06E69 /* SWGDate.h */, - EAEA85D11811D3AE00F06E69 /* SWGDate.m */, EAEA85D21811D3AE00F06E69 /* SWGFile.h */, EAEA85D31811D3AE00F06E69 /* SWGFile.m */, EAEA85D41811D3AE00F06E69 /* SWGObject.h */, @@ -397,8 +398,8 @@ EAEA85EE1811D3AE00F06E69 /* SWGUser.m in Sources */, EAEA85EF1811D3AE00F06E69 /* SWGUserApi.m in Sources */, EAEA85EB1811D3AE00F06E69 /* SWGPetApi.m in Sources */, - EAEA85E61811D3AE00F06E69 /* SWGDate.m in Sources */, EA6699A61811D2FA00A70D03 /* main.m in Sources */, + CFD1B6701B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAEA85EA1811D3AE00F06E69 /* SWGPet.m in Sources */, EAEA85E41811D3AE00F06E69 /* SWGApiClient.m in Sources */, EAEA85EC1811D3AE00F06E69 /* SWGStoreApi.m in Sources */, @@ -414,6 +415,7 @@ buildActionMask = 2147483647; files = ( EAB26B0C1AC8DF78002F5C7A /* PetApiTest.h in Sources */, + CFD1B6711B05EC7D00DCCD51 /* JSONValueTransformer+ISO8601.m in Sources */, EAB26B0D1AC8DF78002F5C7A /* PetApiTest.m in Sources */, ); runOnlyForDeploymentPostprocessing = 0; diff --git a/samples/client/petstore/objc/Podfile b/samples/client/petstore/objc/Podfile index 925e26812b9..9a1ad058940 100644 --- a/samples/client/petstore/objc/Podfile +++ b/samples/client/petstore/objc/Podfile @@ -2,3 +2,4 @@ platform :ios, '6.0' xcodeproj 'PetstoreClient/PetstoreClient.xcodeproj' pod 'AFNetworking', '~> 2.1' pod 'JSONModel', '~> 1.0' +pod 'ISO8601' diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index de949a0e238..e9e593cf299 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -1,33 +1,36 @@ PODS: - - AFNetworking (2.5.1): - - AFNetworking/NSURLConnection (= 2.5.1) - - AFNetworking/NSURLSession (= 2.5.1) - - AFNetworking/Reachability (= 2.5.1) - - AFNetworking/Security (= 2.5.1) - - AFNetworking/Serialization (= 2.5.1) - - AFNetworking/UIKit (= 2.5.1) - - AFNetworking/NSURLConnection (2.5.1): + - AFNetworking (2.5.3): + - AFNetworking/NSURLConnection (= 2.5.3) + - AFNetworking/NSURLSession (= 2.5.3) + - AFNetworking/Reachability (= 2.5.3) + - AFNetworking/Security (= 2.5.3) + - AFNetworking/Serialization (= 2.5.3) + - AFNetworking/UIKit (= 2.5.3) + - AFNetworking/NSURLConnection (2.5.3): - AFNetworking/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/NSURLSession (2.5.1): + - AFNetworking/NSURLSession (2.5.3): - AFNetworking/Reachability - AFNetworking/Security - AFNetworking/Serialization - - AFNetworking/Reachability (2.5.1) - - AFNetworking/Security (2.5.1) - - AFNetworking/Serialization (2.5.1) - - AFNetworking/UIKit (2.5.1): + - AFNetworking/Reachability (2.5.3) + - AFNetworking/Security (2.5.3) + - AFNetworking/Serialization (2.5.3) + - AFNetworking/UIKit (2.5.3): - AFNetworking/NSURLConnection - AFNetworking/NSURLSession - - JSONModel (1.0.2) + - ISO8601 (0.2.0) + - JSONModel (1.1.0) DEPENDENCIES: - AFNetworking (~> 2.1) + - ISO8601 - JSONModel (~> 1.0) SPEC CHECKSUMS: - AFNetworking: 10e85a00bb0f475124e4ff2677bf15693b2c1523 - JSONModel: 6ffcb4ffa3659c9e9a2e5d45d6c7705bab187c03 + AFNetworking: e1d86c2a96bb5d2e7408da36149806706ee122fe + ISO8601: 962282de75074c38bbfaa7b133b0e743ed6deb8d + JSONModel: ec77e9865236a7a09d9cf7668df6b4b328d9ec1d -COCOAPODS: 0.36.0 +COCOAPODS: 0.37.1 diff --git a/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h new file mode 100644 index 00000000000..832f485f4f0 --- /dev/null +++ b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.h @@ -0,0 +1,6 @@ +#import +#import +#import + +@interface JSONValueTransformer (ISO8601) +@end diff --git a/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m new file mode 100644 index 00000000000..cec8bdeea27 --- /dev/null +++ b/samples/client/petstore/objc/client/JSONValueTransformer+ISO8601.m @@ -0,0 +1,10 @@ +#import "JSONValueTransformer+ISO8601.h" + +@implementation JSONValueTransformer (ISO8601) + +- (NSDate *) NSDateFromNSString:(NSString *)string +{ + return [NSDate dateWithISO8601String:string]; +} + +@end diff --git a/samples/client/petstore/objc/client/SWGDate.h b/samples/client/petstore/objc/client/SWGDate.h deleted file mode 100644 index 2c6c7cfe01b..00000000000 --- a/samples/client/petstore/objc/client/SWGDate.h +++ /dev/null @@ -1,12 +0,0 @@ -#import -#import "SWGObject.h" - -@interface SWGDate : SWGObject { -@private - NSDate *_date; -} -@property(nonatomic, readonly) NSDate* date; - -- (id) initWithValues: (NSString*)input; --(NSString*) toString; -@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGDate.m b/samples/client/petstore/objc/client/SWGDate.m deleted file mode 100644 index 07a1405626b..00000000000 --- a/samples/client/petstore/objc/client/SWGDate.m +++ /dev/null @@ -1,34 +0,0 @@ -#import "SWGDate.h" - -@implementation SWGDate - -@synthesize date = _date; - -- (id) initWithValues:(NSString*)input { - if([input isKindOfClass:[NSString class]]){ - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - _date = [df dateFromString:input]; - } - else if([input isKindOfClass:[NSNumber class]]) { - NSTimeInterval interval = [input doubleValue]; - _date = [[NSDate alloc] initWithTimeIntervalSince1970:interval]; - } - return self; -} - --(NSString*) toString { - NSDateFormatter* df = [NSDateFormatter new]; - NSLocale *locale = [[NSLocale new] - initWithLocaleIdentifier:@"en_US_POSIX"]; - [df setLocale:locale]; - [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"]; - - return [df stringFromDate:_date]; -} - -@end \ No newline at end of file diff --git a/samples/client/petstore/objc/client/SWGObject.h b/samples/client/petstore/objc/client/SWGObject.h index ccec208abc0..006701cde01 100644 --- a/samples/client/petstore/objc/client/SWGObject.h +++ b/samples/client/petstore/objc/client/SWGObject.h @@ -1,5 +1,6 @@ #import #import "JSONModel.h" +#import "JSONValueTransformer+ISO8601.h" @interface SWGObject : JSONModel @end From 33138c139f3195065b62e348d94a80b45f44c658 Mon Sep 17 00:00:00 2001 From: Fake Bob Dobbs Date: Fri, 15 May 2015 16:55:49 -0400 Subject: [PATCH 29/75] A parameter's default value is not flowing from the swagger definition to the actual API implementation. This change makes the property from the swagger def json available to the templates. --- .../java/com/wordnik/swagger/codegen/CodegenParameter.java | 5 +++-- .../java/com/wordnik/swagger/codegen/DefaultCodegen.java | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java index 04cecabad90..8dc9991daed 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenParameter.java @@ -3,7 +3,7 @@ package com.wordnik.swagger.codegen; public class CodegenParameter { public Boolean isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isFile, notFile, hasMore, isContainer, secondaryParam; - public String baseName, paramName, dataType, collectionFormat, description, baseType; + public String baseName, paramName, dataType, collectionFormat, description, baseType, defaultValue; public String jsonSchema; /** @@ -34,7 +34,8 @@ public class CodegenParameter { output.isBodyParam = this.isBodyParam; output.required = this.required; output.jsonSchema = this.jsonSchema; + output.defaultValue = this.defaultValue; return output; } -} \ No newline at end of file +} 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 6f51374c536..966cc817863 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 @@ -904,6 +904,10 @@ public class DefaultCodegen { p.required = param.getRequired(); p.jsonSchema = Json.pretty(param); + if(param instanceof QueryParameter) { + p.defaultValue = ((QueryParameter)param).getDefaultValue(); + } + if(param instanceof SerializableParameter) { SerializableParameter qp = (SerializableParameter) param; Property property = null; From e4f5243e54f806762809681bd1251f2eb22558b5 Mon Sep 17 00:00:00 2001 From: Fake Bob Dobbs Date: Fri, 15 May 2015 17:17:46 -0400 Subject: [PATCH 30/75] add defaultValues value to the SpringMVC RequestParam annotation --- .../src/main/resources/JavaSpringMVC/queryParams.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache index 313289d9eaf..3bb2afcb6cd 100755 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/queryParams.mustache @@ -1 +1 @@ -{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} \ No newline at end of file +{{#isQueryParam}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{defaultValue}}}"{{/defaultValue}}) @RequestParam(value = "{{paramName}}"{{#required}}, required = true{{/required}}{{^required}}, required = false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isQueryParam}} From 9809ce1d18bc4fecde1a2399702caa99e0b3cf2c Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 16 May 2015 17:30:42 +0800 Subject: [PATCH 31/75] updated python unittests --- .../petstore/python/SwaggerPetstore-python/Makefile | 12 +++++++----- .../petstore/python/SwaggerPetstore-python/pom.xml | 2 +- .../SwaggerPetstore-python/tests/test_pet_api.py | 4 ++-- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/Makefile b/samples/client/petstore/python/SwaggerPetstore-python/Makefile index 8acdd7cc5ac..e829f17159e 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/Makefile +++ b/samples/client/petstore/python/SwaggerPetstore-python/Makefile @@ -8,7 +8,7 @@ ifndef VIRTUAL_ENV http://docs.python-guide.org/en/latest/dev/virtualenvs/) endif -setup: virtualenv $(SETUP_OUT) +setup: $(SETUP_OUT) $(SETUP_OUT): setup.py setup.cfg python setup.py develop @@ -19,17 +19,19 @@ $(REQUIREMENTS_OUT): $(REQUIREMENTS_FILE) python setup.py develop clean: + rm -rf $(REQUIREMENTS_OUT) + rm -rf $(SETUP_OUT) + rm -rf .tox + rm -rf .coverage find . -name "*.py[oc]" -delete find . -name "__pycache__" -delete - rm -f $(REQUIREMENTS_OUT) - rm -rf $(SETUP_OUT) requirements: setup $(REQUIREMENTS_OUT) -test: requirements +test: clean requirements nosetests -test-all: requirements +test-all: virtualenv clean requirements tox diff --git a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml b/samples/client/petstore/python/SwaggerPetstore-python/pom.xml index 3ff908ed770..e21eb2f5a96 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/pom.xml +++ b/samples/client/petstore/python/SwaggerPetstore-python/pom.xml @@ -35,7 +35,7 @@ make - test-all + test diff --git a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py index 88a19f61d3c..f0b8ab03d81 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/tests/test_pet_api.py @@ -94,8 +94,8 @@ class PetApiTests(unittest.TestCase): fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) self.assertEqual(self.pet.id, fetched.id) - self.assertEqual(self.pet.name, fetched.name) - self.assertEqual(self.pet.status, fetched.status) + self.assertEqual(name, fetched.name) + self.assertEqual(status, fetched.status) def test_upload_file(self): try: From 68b0259c473772f181851c3fd721db419ba89b54 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Sat, 16 May 2015 18:05:06 +0800 Subject: [PATCH 32/75] updated readme.md of python --- .../src/main/resources/python/README.mustache | 18 +++++++++++++++--- .../python/SwaggerPetstore-python/README.md | 18 +++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index 2c5c75fc764..a3e4325cc81 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -38,8 +38,7 @@ TODO ## Tests -We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. -Our Makefile handles much of this for you as long as you're running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): +You can run the tests in the current python platform: ```sh $ make test @@ -48,8 +47,21 @@ Ran 7 tests in 19.289s OK ``` +or -You can test in various python versions using: +``` +$ mvn integration-test -rf :PythonPetstoreClientTests +Using 2195432783 as seed +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 37.594 s +[INFO] Finished at: 2015-05-16T18:00:35+08:00 +[INFO] Final Memory: 11M/156M +[INFO] ------------------------------------------------------------------------ +``` +If you want to run the tests in all the python platforms, +make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): ```sh $ make test-all diff --git a/samples/client/petstore/python/SwaggerPetstore-python/README.md b/samples/client/petstore/python/SwaggerPetstore-python/README.md index 2c5c75fc764..a3e4325cc81 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/README.md +++ b/samples/client/petstore/python/SwaggerPetstore-python/README.md @@ -38,8 +38,7 @@ TODO ## Tests -We use some external dependencies, multiple interpreters and code coverage analysis while running test suite. -Our Makefile handles much of this for you as long as you're running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): +You can run the tests in the current python platform: ```sh $ make test @@ -48,8 +47,21 @@ Ran 7 tests in 19.289s OK ``` +or -You can test in various python versions using: +``` +$ mvn integration-test -rf :PythonPetstoreClientTests +Using 2195432783 as seed +[INFO] ------------------------------------------------------------------------ +[INFO] BUILD SUCCESS +[INFO] ------------------------------------------------------------------------ +[INFO] Total time: 37.594 s +[INFO] Finished at: 2015-05-16T18:00:35+08:00 +[INFO] Final Memory: 11M/156M +[INFO] ------------------------------------------------------------------------ +``` +If you want to run the tests in all the python platforms, +make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): ```sh $ make test-all From 41e178e26807a171ca641b85630457fef9f7360f Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 18 May 2015 22:16:54 +0800 Subject: [PATCH 33/75] better accept and content-type for php, added test cases --- .../src/main/resources/php/APIClient.mustache | 33 ++++++++++- .../src/main/resources/php/api.mustache | 7 +-- .../php/SwaggerClient-php/lib/APIClient.php | 44 +++++++++++++-- .../php/SwaggerClient-php/lib/PetApi.php | 56 ++++++++----------- .../php/SwaggerClient-php/lib/StoreApi.php | 28 ++++------ .../php/SwaggerClient-php/lib/UserApi.php | 56 ++++++++----------- .../SwaggerClient-php/tests/PetApiTest.php | 16 ++++++ 7 files changed, 149 insertions(+), 91 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index a750daff12d..c239dfb26f3 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -261,7 +261,6 @@ class APIClient { * @param string $class class name is passed as a string * @return object an instance of $class */ - public static function deserialize($data, $class) { if (null === $data) { @@ -304,5 +303,37 @@ class APIClient { return $deserialized; } + /* + * return the header 'Accept' based on an array of Accept provided + * + * @param array[string] $accept Array of header + * @return string Accept (e.g. application/json) + */ + public static function selectHeaderAccept($accept) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + return NULL; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } + } + + /* + * return the content type based on an array of content-type provided + * + * @param array[string] content_type_array Array fo content-type + * @return string Content-Type (e.g. application/json) + */ + public static function selectHeaderContentType($content_type) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $content_type)) { + return 'application/json'; + } else { + return implode(',', $content_type); + } + } + } diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 7759af5004d..80273db553f 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -54,12 +54,11 @@ class {{classname}} { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = '{{#produces}}{{mediaType}}{{#hasMore}}, {{/hasMore}}{{/produces}}'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array({{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}})); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}}); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array({{#consumes}}'{{mediaType}}'{{#hasMore}},{{/hasMore}}{{/consumes}})); {{#queryParams}}// query params if(${{paramName}} !== null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d6d14c72527..e57b726e66f 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -142,20 +142,21 @@ class APIClient { $response_info = curl_getinfo($curl); // Handle the response - if ($response === false) { // error, likely in the client side - throw new APIClientException("API Error ($url): ".curl_error($curl), 0, $response_info, $response); + if ($response_info['http_code'] == 0) { + throw new APIClientException("TIMEOUT: api call to " . $url . + " took more than 5s to return", 0, $response_info, $response); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { $data = json_decode($response); if (json_last_error() > 0) { // if response is a string $data = $response; } - } else if ($response_info['http_code'] == 401) { // server returns 401 + } else if ($response_info['http_code'] == 401) { throw new APIClientException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { // server returns 404 + } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new APIClientException("Can't connect to the API: " . $url . + throw new APIClientException("Can't connect to the api: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } @@ -260,7 +261,6 @@ class APIClient { * @param string $class class name is passed as a string * @return object an instance of $class */ - public static function deserialize($data, $class) { if (null === $data) { @@ -303,5 +303,37 @@ class APIClient { return $deserialized; } + /* + * return the header 'Accept' based on an array of Accept provided + * + * @param array[string] $accept Array of header + * @return string Accept (e.g. application/json) + */ + public static function selectHeaderAccept($accept) { + if (count($accept) === 0 or (count($accept) === 1 and $accept[0] === '')) { + return NULL; + } elseif (preg_grep("/application\/json/i", $accept)) { + return 'application/json'; + } else { + return implode(',', $accept); + } + } + + /* + * return the content type based on an array of content-type provided + * + * @param array[string] content_type_array Array fo content-type + * @return string Content-Type (e.g. application/json) + */ + public static function selectHeaderContentType($content_type) { + if (count($content_type) === 0 or (count($content_type) === 1 and $content_type[0] === '')) { + return 'application/json'; + } elseif (preg_grep("/application\/json/i", $content_type)) { + return 'application/json'; + } else { + return implode(',', $content_type); + } + } + } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 07f6181a730..fad8d1b6987 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -48,12 +48,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/json','application/xml',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml',)); @@ -100,12 +99,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/json','application/xml',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/json','application/xml',)); @@ -152,12 +150,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params if($status !== null) { @@ -209,12 +206,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params if($tags !== null) { @@ -271,12 +267,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -336,12 +331,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/x-www-form-urlencoded',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('application/x-www-form-urlencoded',)); @@ -400,12 +394,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // header params @@ -462,12 +455,11 @@ class PetApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('multipart/form-data',); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array('multipart/form-data',)); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 78e23ec9034..3bc60c2e4f5 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -47,12 +47,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -101,12 +100,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -164,12 +162,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -227,12 +224,11 @@ class StoreApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index a3ed8a8ab25..5048ba88b57 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -48,12 +48,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -100,12 +99,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -152,12 +150,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -205,12 +202,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); // query params if($username !== null) { @@ -264,12 +260,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -317,12 +312,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -381,12 +375,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); @@ -442,12 +435,11 @@ class UserApi { $queryParams = array(); $headerParams = array(); $formParams = array(); - $_header_accept = 'application/json, application/xml'; - if ($_header_accept !== '') { + $_header_accept = $this->apiClient->selectHeaderAccept(array('application/json', 'application/xml')); + if (!is_null($_header_accept)) { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array(); - $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; + $headerParams['Content-Type'] = $this->apiClient->selectHeaderContentType(array()); diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index d2d398ae140..cdae17f19d0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -31,6 +31,22 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $add_response = $pet_api->addPet($new_pet); } + // test static functions defined in APIClient + public function testAPIClient() + { + # test selectHeaderAccept + $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderAccept(array('application/xml','application/json'))); + $this->assertSame(NULL, SwaggerClient\APIClient::selectHeaderAccept(array())); + $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderAccept(array('application/yaml','application/xml'))); + + # test selectHeaderContentType + $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array('application/xml','application/json'))); + $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array())); + $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderContentType(array('application/yaml','application/xml'))); + + + } + // test getPetById with a Pet object (id 10005) public function testGetPetById() { From 5aad44e62871657f6cbf954992079c588357b9fc Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 May 2015 10:15:36 +0800 Subject: [PATCH 34/75] added back test case for updatePetWithForm --- .../php/SwaggerClient-php/tests/PetApiTest.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index cdae17f19d0..0d015ec47b2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -93,7 +93,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // create updated pet object $updated_pet = new SwaggerClient\models\Pet; $updated_pet->id = $pet_id; - $updated_pet->status = "pending"; // new status + $updated_pet->name = 'updatePet'; // new name + $updated_pet->status = 'pending'; // new status // update Pet (model/json) $update_response = $pet_api->updatePet($updated_pet); // return nothing (void) @@ -102,6 +103,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $response = $pet_api->getPetById($pet_id); $this->assertSame($response->id, $pet_id); $this->assertSame($response->status, 'pending'); + $this->assertSame($response->name, 'updatePet'); } // test updatePet and verify by the "id" of the response @@ -112,15 +114,13 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $pet_id = 10001; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // update Pet (form) - $update_response = $pet_api->updatePetWithForm($pet_id, null, 'sold'); + $update_response = $pet_api->updatePetWithForm($pet_id, 'update pet with form', 'sold'); // return nothing (void) $this->assertSame($update_response, NULL); - // TODO commented out for the time being since it's broken - // https://github.com/swagger-api/swagger-codegen/issues/656 - // verify updated Pet - //$response = $pet_api->getPetById($pet_id); - //$this->assertSame($response->id, $pet_id); - //$this->assertSame($response->status, 'sold'); + $response = $pet_api->getPetById($pet_id); + $this->assertSame($response->id, $pet_id); + $this->assertSame($response->name, 'update pet with form'); + $this->assertSame($response->status, 'sold'); } // test addPet and verify by the "id" and "name" of the response From a77ae51318d18c8affa657b421606042cd311154 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 19 May 2015 15:21:09 +0800 Subject: [PATCH 35/75] update python tests --- .../src/main/resources/python/README.mustache | 5 +++-- .../client/petstore/python/SwaggerPetstore-python/Makefile | 4 ++-- .../client/petstore/python/SwaggerPetstore-python/README.md | 5 +++-- .../client/petstore/python/SwaggerPetstore-python/setup.cfg | 1 + 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/python/README.mustache b/modules/swagger-codegen/src/main/resources/python/README.mustache index a3e4325cc81..9c590a9a508 100644 --- a/modules/swagger-codegen/src/main/resources/python/README.mustache +++ b/modules/swagger-codegen/src/main/resources/python/README.mustache @@ -38,6 +38,8 @@ TODO ## Tests +(Make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/)) + You can run the tests in the current python platform: ```sh @@ -60,8 +62,7 @@ Using 2195432783 as seed [INFO] Final Memory: 11M/156M [INFO] ------------------------------------------------------------------------ ``` -If you want to run the tests in all the python platforms, -make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): +If you want to run the tests in all the python platforms: ```sh $ make test-all diff --git a/samples/client/petstore/python/SwaggerPetstore-python/Makefile b/samples/client/petstore/python/SwaggerPetstore-python/Makefile index e829f17159e..2811b735b54 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/Makefile +++ b/samples/client/petstore/python/SwaggerPetstore-python/Makefile @@ -8,7 +8,7 @@ ifndef VIRTUAL_ENV http://docs.python-guide.org/en/latest/dev/virtualenvs/) endif -setup: $(SETUP_OUT) +setup: virtualenv $(SETUP_OUT) $(SETUP_OUT): setup.py setup.cfg python setup.py develop @@ -31,7 +31,7 @@ requirements: setup $(REQUIREMENTS_OUT) test: clean requirements nosetests -test-all: virtualenv clean requirements +test-all: clean requirements tox diff --git a/samples/client/petstore/python/SwaggerPetstore-python/README.md b/samples/client/petstore/python/SwaggerPetstore-python/README.md index a3e4325cc81..9c590a9a508 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/README.md +++ b/samples/client/petstore/python/SwaggerPetstore-python/README.md @@ -38,6 +38,8 @@ TODO ## Tests +(Make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/)) + You can run the tests in the current python platform: ```sh @@ -60,8 +62,7 @@ Using 2195432783 as seed [INFO] Final Memory: 11M/156M [INFO] ------------------------------------------------------------------------ ``` -If you want to run the tests in all the python platforms, -make sure you are running it inside of a [virtualenv](http://docs.python-guide.org/en/latest/dev/virtualenvs/): +If you want to run the tests in all the python platforms: ```sh $ make test-all diff --git a/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg b/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg index f1ef0cc4d0f..e62af080034 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg +++ b/samples/client/petstore/python/SwaggerPetstore-python/setup.cfg @@ -2,6 +2,7 @@ logging-clear-handlers=true verbosity=2 randomize=true +exe=true with-coverage=true cover-package=SwaggerPetstore cover-erase=true From af260cba41df5c30d8a1c696902a62508a2df63b Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 May 2015 15:33:03 +0800 Subject: [PATCH 36/75] update api client to support default header --- .../src/main/resources/php/APIClient.mustache | 53 ++++++++++++++++--- .../php/SwaggerClient-php/lib/APIClient.php | 53 ++++++++++++++++--- .../SwaggerClient-php/tests/PetApiTest.php | 10 +++- samples/client/petstore/php/test.php | 2 + 4 files changed, 101 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index c239dfb26f3..e6f08d4b5aa 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -24,6 +24,8 @@ class APIClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; + + private static $default_header = array(); /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout @@ -46,24 +48,55 @@ class APIClient { } /** - * Set the user agent of the API client + * add default header * - * @param string $user_agent The user agent of the API client + * @param string $header_name header name (e.g. Token) + * @param string $header_value header value (e.g. 1z8wp3) + */ + public function addDefaultHeader($header_name, $header_value) { + if (!is_string($header_name)) + throw new exception('heaer name must be a string.'); + + self::$default_header[$header_name] = $header_value; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeader() { + return self::$default_header; + } + + /** + * delete the default header based on header name + * + * @param string $header_name header name (e.g. Token) + */ + public function deleteDefaultHeader($header_name) { + unset(self::$default_header[$header_name]); + } + + /** + * set the user agent of the api client + * + * @param string $user_agent the user agent of the api client */ public function setUserAgent($user_agent) { - if (!is_string($user_agent)) { - throw new Exception('User-agent must be a string.'); - } + if (!is_string($user_agent)) + throw new exception('user-agent must be a string.'); + $this->user_agent= $user_agent; } /** * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ + */ public function setTimeout($seconds) { - if (!is_numeric($seconds)) { + if (!is_numeric($seconds)) throw new Exception('Timeout variable must be numeric.'); - } + $this->curl_timeout = $seconds; } @@ -83,6 +116,9 @@ class APIClient { # Allow API key from $headerParams to override default $added_api_key = False; if ($headerParams != null) { + # add default header + $headerParams = array_merge((array)self::$default_header, $headerParams); + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; if ($key == $this->headerName) { @@ -111,6 +147,7 @@ class APIClient { } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (! empty($queryParams)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index e57b726e66f..d4b7d8f7f63 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -24,6 +24,8 @@ class APIClient { public static $GET = "GET"; public static $PUT = "PUT"; public static $DELETE = "DELETE"; + + private static $default_header = array(); /* * @var string timeout (second) of the HTTP request, by default set to 0, no timeout @@ -46,24 +48,55 @@ class APIClient { } /** - * Set the user agent of the API client + * add default header * - * @param string $user_agent The user agent of the API client + * @param string $header_name header name (e.g. Token) + * @param string $header_value header value (e.g. 1z8wp3) + */ + public function addDefaultHeader($header_name, $header_value) { + if (!is_string($header_name)) + throw new exception('heaer name must be a string.'); + + self::$default_header[$header_name] = $header_value; + } + + /** + * get the default header + * + * @return array default header + */ + public function getDefaultHeader() { + return self::$default_header; + } + + /** + * delete the default header based on header name + * + * @param string $header_name header name (e.g. Token) + */ + public function deleteDefaultHeader($header_name) { + unset(self::$default_header[$header_name]); + } + + /** + * set the user agent of the api client + * + * @param string $user_agent the user agent of the api client */ public function setUserAgent($user_agent) { - if (!is_string($user_agent)) { - throw new Exception('User-agent must be a string.'); - } + if (!is_string($user_agent)) + throw new exception('user-agent must be a string.'); + $this->user_agent= $user_agent; } /** * @param integer $seconds Number of seconds before timing out [set to 0 for no timeout] - */ + */ public function setTimeout($seconds) { - if (!is_numeric($seconds)) { + if (!is_numeric($seconds)) throw new Exception('Timeout variable must be numeric.'); - } + $this->curl_timeout = $seconds; } @@ -83,6 +116,9 @@ class APIClient { # Allow API key from $headerParams to override default $added_api_key = False; if ($headerParams != null) { + # add default header + $headerParams = array_merge((array)self::$default_header, $headerParams); + foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; if ($key == $this->headerName) { @@ -111,6 +147,7 @@ class APIClient { } // return the result on success, rather than just TRUE curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); + curl_setopt($curl, CURLOPT_HTTPHEADER, $headers); if (! empty($queryParams)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 0d015ec47b2..4751c29dd78 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -43,8 +43,16 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array('application/xml','application/json'))); $this->assertSame('application/json', SwaggerClient\APIClient::selectHeaderContentType(array())); $this->assertSame('application/yaml,application/xml', SwaggerClient\APIClient::selectHeaderContentType(array('application/yaml','application/xml'))); - + # test addDefaultHeader and getDefaultHeader + SwaggerClient\APIClient::addDefaultHeader('test1', 'value1'); + SwaggerClient\APIClient::addDefaultHeader('test2', 200); + $this->assertSame('value1', SwaggerClient\APIClient::getDefaultHeader()['test1']); + $this->assertSame(200, SwaggerClient\APIClient::getDefaultHeader()['test2']); + + # test deleteDefaultHeader + SwaggerClient\APIClient::deleteDefaultHeader('test2'); + $this->assertFalse(isset(SwaggerClient\APIClient::getDefaultHeader()['test2'])); } // test getPetById with a Pet object (id 10005) diff --git a/samples/client/petstore/php/test.php b/samples/client/petstore/php/test.php index 7cbbfce3cbb..7d46d8b5821 100644 --- a/samples/client/petstore/php/test.php +++ b/samples/client/petstore/php/test.php @@ -4,6 +4,8 @@ require_once('SwaggerClient-php/SwaggerClient.php'); // initialize the API client $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); +$api_client->addDefaultHeader("test1", "value1"); + $petId = 10005; // ID of pet that needs to be fetched try { $pet_api = new SwaggerClient\PetAPI($api_client); From db9ca1a485df92d4fa094c0f22c4813888c0e2cb Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 19 May 2015 15:42:29 +0800 Subject: [PATCH 37/75] Fix test of updatePetWithForm for Android Petstore sample --- .../test/java/io/swagger/petstore/test/PetApiTest.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java index 97f3b5f8006..e7fd31f2996 100644 --- a/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java +++ b/samples/client/petstore/android-java/src/test/java/io/swagger/petstore/test/PetApiTest.java @@ -100,11 +100,11 @@ public class PetApiTest { api.addPet(pet); Pet fetched = api.getPetById(pet.getId()); - + assertEquals("frank", fetched.getName()); + api.updatePetWithForm(String.valueOf(fetched.getId()), "furt", null); Pet updated = api.getPetById(fetched.getId()); - - assertEquals(updated.getName(), fetched.getName()); + assertEquals("furt", updated.getName()); } @Test @@ -152,4 +152,4 @@ public class PetApiTest { return pet; } -} \ No newline at end of file +} From 5744bd013856879b6bbb8ec8f153f6378596e2c8 Mon Sep 17 00:00:00 2001 From: wing328 Date: Tue, 19 May 2015 16:21:06 +0800 Subject: [PATCH 38/75] better exception using InvalidArgumentException --- .../src/main/resources/php/APIClient.mustache | 8 ++++---- .../swagger-codegen/src/main/resources/php/api.mustache | 2 +- .../petstore/php/SwaggerClient-php/lib/APIClient.php | 8 ++++---- .../client/petstore/php/SwaggerClient-php/lib/PetApi.php | 8 ++++---- .../petstore/php/SwaggerClient-php/lib/StoreApi.php | 4 ++-- .../client/petstore/php/SwaggerClient-php/lib/UserApi.php | 6 +++--- 6 files changed, 18 insertions(+), 18 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index e6f08d4b5aa..cf3d1fb9372 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -55,7 +55,7 @@ class APIClient { */ public function addDefaultHeader($header_name, $header_value) { if (!is_string($header_name)) - throw new exception('heaer name must be a string.'); + throw new \InvalidArgumentException('Header name must be a string.'); self::$default_header[$header_name] = $header_value; } @@ -85,7 +85,7 @@ class APIClient { */ public function setUserAgent($user_agent) { if (!is_string($user_agent)) - throw new exception('user-agent must be a string.'); + throw new \InvalidArgumentException('User-agent must be a string.'); $this->user_agent= $user_agent; } @@ -95,7 +95,7 @@ class APIClient { */ public function setTimeout($seconds) { if (!is_numeric($seconds)) - throw new Exception('Timeout variable must be numeric.'); + throw new \InvalidArgumentException('Timeout variable must be numeric.'); $this->curl_timeout = $seconds; } @@ -167,7 +167,7 @@ class APIClient { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); + throw new APIClientException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 80273db553f..f0100defffe 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -42,7 +42,7 @@ class {{classname}} { {{#allParams}}{{#required}} // verify the required parameter '{{paramName}}' is set if (${{paramName}} === null) { - throw new \Exception("Missing the required parameter ${{paramName}} when calling {{nickname}}"); + throw new \InvalidArgumentException('Missing the required parameter ${{paramName}} when calling {{nickname}}'); } {{/required}}{{/allParams}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d4b7d8f7f63..ace6bd78a11 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -55,7 +55,7 @@ class APIClient { */ public function addDefaultHeader($header_name, $header_value) { if (!is_string($header_name)) - throw new exception('heaer name must be a string.'); + throw new \InvalidArgumentException('Header name must be a string.'); self::$default_header[$header_name] = $header_value; } @@ -85,7 +85,7 @@ class APIClient { */ public function setUserAgent($user_agent) { if (!is_string($user_agent)) - throw new exception('user-agent must be a string.'); + throw new \InvalidArgumentException('User-agent must be a string.'); $this->user_agent= $user_agent; } @@ -95,7 +95,7 @@ class APIClient { */ public function setTimeout($seconds) { if (!is_numeric($seconds)) - throw new Exception('Timeout variable must be numeric.'); + throw new \InvalidArgumentException('Timeout variable must be numeric.'); $this->curl_timeout = $seconds; } @@ -167,7 +167,7 @@ class APIClient { curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); curl_setopt($curl, CURLOPT_POSTFIELDS, $postData); } else if ($method != self::$GET) { - throw new Exception('Method ' . $method . ' is not recognized.'); + throw new APIClientException('Method ' . $method . ' is not recognized.'); } curl_setopt($curl, CURLOPT_URL, $url); diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index fad8d1b6987..9e75df102fc 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -255,7 +255,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling getPetById"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling getPetById'); } @@ -319,7 +319,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling updatePetWithForm"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling updatePetWithForm'); } @@ -382,7 +382,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling deletePet"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling deletePet'); } @@ -443,7 +443,7 @@ class PetApi { // verify the required parameter 'pet_id' is set if ($pet_id === null) { - throw new \Exception("Missing the required parameter $pet_id when calling uploadFile"); + throw new \InvalidArgumentException('Missing the required parameter $pet_id when calling uploadFile'); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 3bc60c2e4f5..ab43d730f6a 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -150,7 +150,7 @@ class StoreApi { // verify the required parameter 'order_id' is set if ($order_id === null) { - throw new \Exception("Missing the required parameter $order_id when calling getOrderById"); + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling getOrderById'); } @@ -212,7 +212,7 @@ class StoreApi { // verify the required parameter 'order_id' is set if ($order_id === null) { - throw new \Exception("Missing the required parameter $order_id when calling deleteOrder"); + throw new \InvalidArgumentException('Missing the required parameter $order_id when calling deleteOrder'); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index 5048ba88b57..90e35bca4ad 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -300,7 +300,7 @@ class UserApi { // verify the required parameter 'username' is set if ($username === null) { - throw new \Exception("Missing the required parameter $username when calling getUserByName"); + throw new \InvalidArgumentException('Missing the required parameter $username when calling getUserByName'); } @@ -363,7 +363,7 @@ class UserApi { // verify the required parameter 'username' is set if ($username === null) { - throw new \Exception("Missing the required parameter $username when calling updateUser"); + throw new \InvalidArgumentException('Missing the required parameter $username when calling updateUser'); } @@ -423,7 +423,7 @@ class UserApi { // verify the required parameter 'username' is set if ($username === null) { - throw new \Exception("Missing the required parameter $username when calling deleteUser"); + throw new \InvalidArgumentException('Missing the required parameter $username when calling deleteUser'); } From a0abea4b724c1a6a30b4e2a05a812564a8da6e27 Mon Sep 17 00:00:00 2001 From: geekerzp Date: Tue, 19 May 2015 17:12:46 +0800 Subject: [PATCH 39/75] added required parameters check for objc --- .../src/main/resources/objc/api-body.mustache | 5 ++++ .../client/petstore/objc/client/SWGPetApi.m | 28 +++++++++++++++++++ .../client/petstore/objc/client/SWGStoreApi.m | 14 ++++++++++ .../client/petstore/objc/client/SWGUserApi.m | 25 +++++++++++++++++ 4 files changed, 72 insertions(+) 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 53e6895fe33..e4c85166b8b 100644 --- a/modules/swagger-codegen/src/main/resources/objc/api-body.mustache +++ b/modules/swagger-codegen/src/main/resources/objc/api-body.mustache @@ -69,6 +69,11 @@ static NSString * basePath = @"{{basePath}}"; {{#returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)({{{returnType}}} output, NSError* error))completionBlock{{/returnBaseType}} {{^returnBaseType}}{{#hasParams}}completionHandler: {{/hasParams}}(void (^)(NSError* error))completionBlock{{/returnBaseType}} { + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + NSAssert({{paramName}} != nil, @"Missing the required parameter `{{paramName}}` when calling {{nickname}}"); + {{/required}}{{/allParams}} + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@{{path}}", basePath]; // remove format in URL if needed diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 62bc34acbee..d73018edf97 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -67,6 +67,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; // remove format in URL if needed @@ -158,6 +160,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet", basePath]; // remove format in URL if needed @@ -249,6 +253,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByStatus", basePath]; // remove format in URL if needed @@ -336,6 +342,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSArray* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/findByTags", basePath]; // remove format in URL if needed @@ -423,6 +431,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGPet* output, NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling getPetById"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; // remove format in URL if needed @@ -510,6 +523,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling updatePetWithForm"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; // remove format in URL if needed @@ -597,6 +615,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling deletePet"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}", basePath]; // remove format in URL if needed @@ -672,6 +695,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'petId' is set + NSAssert(petId != nil, @"Missing the required parameter `petId` when calling uploadFile"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/pet/{petId}/uploadImage", basePath]; // remove format in URL if needed diff --git a/samples/client/petstore/objc/client/SWGStoreApi.m b/samples/client/petstore/objc/client/SWGStoreApi.m index c50cf67c5dc..752fc64d601 100644 --- a/samples/client/petstore/objc/client/SWGStoreApi.m +++ b/samples/client/petstore/objc/client/SWGStoreApi.m @@ -64,6 +64,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; (void (^)(NSDictionary* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/inventory", basePath]; // remove format in URL if needed @@ -138,6 +140,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order", basePath]; // remove format in URL if needed @@ -243,6 +247,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGOrder* output, NSError* error))completionBlock { + + // verify the required parameter 'orderId' is set + NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling getOrderById"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; // remove format in URL if needed @@ -326,6 +335,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'orderId' is set + NSAssert(orderId != nil, @"Missing the required parameter `orderId` when calling deleteOrder"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/store/order/{orderId}", basePath]; // remove format in URL if needed diff --git a/samples/client/petstore/objc/client/SWGUserApi.m b/samples/client/petstore/objc/client/SWGUserApi.m index 1316cebd07c..faa086c5d35 100644 --- a/samples/client/petstore/objc/client/SWGUserApi.m +++ b/samples/client/petstore/objc/client/SWGUserApi.m @@ -66,6 +66,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user", basePath]; // remove format in URL if needed @@ -157,6 +159,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithArray", basePath]; // remove format in URL if needed @@ -248,6 +252,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/createWithList", basePath]; // remove format in URL if needed @@ -341,6 +347,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSString* output, NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/login", basePath]; // remove format in URL if needed @@ -427,6 +435,8 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; (void (^)(NSError* error))completionBlock { + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/logout", basePath]; // remove format in URL if needed @@ -495,6 +505,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(SWGUser* output, NSError* error))completionBlock { + + // verify the required parameter 'username' is set + NSAssert(username != nil, @"Missing the required parameter `username` when calling getUserByName"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; // remove format in URL if needed @@ -580,6 +595,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'username' is set + NSAssert(username != nil, @"Missing the required parameter `username` when calling updateUser"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; // remove format in URL if needed @@ -672,6 +692,11 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; completionHandler: (void (^)(NSError* error))completionBlock { + + // verify the required parameter 'username' is set + NSAssert(username != nil, @"Missing the required parameter `username` when calling deleteUser"); + + NSMutableString* requestUrl = [NSMutableString stringWithFormat:@"%@/user/{username}", basePath]; // remove format in URL if needed From 3dde19bb5967c0ae5e2fc3b1607f545124f1c117 Mon Sep 17 00:00:00 2001 From: Nadezhda Makarkina Date: Thu, 14 May 2015 14:28:43 +0300 Subject: [PATCH 40/75] Fixed #593: Python code failure caused by Model IDs with dots has been fixed --- .../languages/PythonClientCodegen.java | 16 +- .../src/test/resources/2_0/v1beta3.json | 316 ++++++++++++++++++ .../src/test/scala/python/PythonTest.scala | 34 ++ 3 files changed, 360 insertions(+), 6 deletions(-) create mode 100644 modules/swagger-codegen/src/test/resources/2_0/v1beta3.json create mode 100644 modules/swagger-codegen/src/test/scala/python/PythonTest.scala diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java index bbb07b1592a..88da6938951 100755 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PythonClientCodegen.java @@ -113,9 +113,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig if(languageSpecificPrimitives.contains(type)) { return type; } + } else { + type = toModelName(swaggerType); } - else - type = swaggerType; return type; } @@ -133,9 +133,9 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig if (name.matches("^[A-Z_]*$")) name = name.toLowerCase(); - // camelize (lower first character) the variable name + // underscore the variable name // petId => pet_id - name = underscore(name); + name = underscore(dropDots(name)); // for reserved word or word starting with number, append _ if(reservedWords.contains(name) || name.matches("^\\d.*")) @@ -144,6 +144,10 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig return name; } + private static String dropDots(String str) { + return str.replaceAll("\\.", "_"); + } + @Override public String toParamName(String name) { // should be the same as variable name @@ -168,8 +172,8 @@ public class PythonClientCodegen extends DefaultCodegen implements CodegenConfig 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); + // PhoneNumber => phone_number + return underscore(dropDots(name)); } @Override diff --git a/modules/swagger-codegen/src/test/resources/2_0/v1beta3.json b/modules/swagger-codegen/src/test/resources/2_0/v1beta3.json new file mode 100644 index 00000000000..c5e7d8d5986 --- /dev/null +++ b/modules/swagger-codegen/src/test/resources/2_0/v1beta3.json @@ -0,0 +1,316 @@ +{ + "swaggerVersion": "1.2", + "apiVersion": "v1beta3", + "basePath": "https://127.0.0.1:6443", + "resourcePath": "/api/v1beta3", + "apis": [ + { + "path": "/api/v1beta3/namespaces/{namespaces}/bindings", + "description": "API at /api/v1beta3 version v1beta3", + "operations": [ + { + "type": "v1beta3.Binding", + "method": "POST", + "summary": "create a Binding", + "nickname": "createBinding", + "parameters": [ + { + "type": "string", + "paramType": "path", + "name": "namespaces", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "allowMultiple": false + }, + { + "type": "v1beta3.Binding", + "paramType": "body", + "name": "body", + "description": "", + "required": true, + "allowMultiple": false + } + ], + "responseMessages": [ + { + "code": 200, + "message": "OK", + "responseModel": "v1beta3.Binding" + } + ], + "produces": [ + "application/json" + ], + "consumes": [ + "*/*" + ] + } + ] + }, + { + "path": "/api/v1beta3/namespaces/{namespaces}/componentstatuses", + "description": "API at /api/v1beta3 version v1beta3", + "operations": [ + { + "type": "v1beta3.ComponentStatusList", + "method": "GET", + "summary": "list objects of kind ComponentStatus", + "nickname": "listComponentStatus", + "parameters": [ + { + "type": "string", + "paramType": "path", + "name": "namespaces", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "query", + "name": "fieldSelector", + "description": "a selector to restrict the list of returned objects by their fields; defaults to everything", + "required": false, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "query", + "name": "labelSelector", + "description": "a selector to restrict the list of returned objects by their labels; defaults to everything", + "required": false, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "query", + "name": "resourceVersion", + "description": "when specified with a watch call, shows changes that occur after that particular version of a resource; defaults to changes from the beginning of history", + "required": false, + "allowMultiple": false + }, + { + "type": "boolean", + "paramType": "query", + "name": "watch", + "description": "watch for changes to the described resources and return them as a stream of add, update, and remove notifications; specify resourceVersion", + "required": false, + "allowMultiple": false + } + ], + "responseMessages": [ + { + "code": 200, + "message": "OK", + "responseModel": "v1beta3.ComponentStatusList" + } + ], + "produces": [ + "application/json" + ], + "consumes": [ + "*/*" + ] + } + ] + }, + { + "path": "/api/v1beta3/namespaces/{namespaces}/componentstatuses/{name}", + "description": "API at /api/v1beta3 version v1beta3", + "operations": [ + { + "type": "v1beta3.ComponentStatus", + "method": "GET", + "summary": "read the specified ComponentStatus", + "nickname": "readComponentStatus", + "parameters": [ + { + "type": "string", + "paramType": "path", + "name": "name", + "description": "name of the ComponentStatus", + "required": true, + "allowMultiple": false + }, + { + "type": "string", + "paramType": "path", + "name": "namespaces", + "description": "object name and auth scope, such as for teams and projects", + "required": true, + "allowMultiple": false + } + ], + "responseMessages": [ + { + "code": 200, + "message": "OK", + "responseModel": "v1beta3.ComponentStatus" + } + ], + "produces": [ + "application/json" + ], + "consumes": [ + "*/*" + ] + } + ] + } + ], + "models": { + "v1beta3.ComponentStatus": { + "id": "v1beta3.ComponentStatus", + "properties": { + "apiVersion": { + "type": "string", + "description": "version of the schema the object should have" + }, + "conditions": { + "type": "array", + "items": { + "$ref": "v1beta3.ObjectReference" + }, + "description": "list of component conditions observed" + }, + "kind": { + "type": "string", + "description": "kind of object, in CamelCase; cannot be updated" + }, + "metadata": { + "$ref": "v1beta3.ObjectMeta", + "description": "standard object metadata; see http://docs.k8s.io/api-conventions.md#metadata" + } + } + }, + "v1beta3.ComponentStatusList": { + "id": "v1beta3.ComponentStatusList", + "required": [ + "items" + ], + "properties": { + "apiVersion": { + "type": "string", + "description": "version of the schema the object should have" + }, + "items": { + "type": "array", + "items": { + "$ref": "v1beta3.ComponentStatus" + }, + "description": "list of component status objects" + }, + "kind": { + "type": "string", + "description": "kind of object, in CamelCase; cannot be updated" + }, + "metadata": { + "$ref": "v1beta3.ObjectMeta", + "description": "standard list metadata; see http://docs.k8s.io/api-conventions.md#metadata" + } + } + }, + "v1beta3.Binding": { + "id": "v1beta3.Binding", + "required": [ + "target" + ], + "properties": { + "apiVersion": { + "type": "string", + "description": "version of the schema the object should have" + }, + "kind": { + "type": "string", + "description": "kind of object, in CamelCase; cannot be updated" + }, + "metadata": { + "$ref": "v1beta3.ObjectMeta", + "description": "standard object metadata; see http://docs.k8s.io/api-conventions.md#metadata" + }, + "target": { + "$ref": "v1beta3.ObjectReference", + "description": "an object to bind to" + } + } + }, + "v1beta3.ObjectReference": { + "id": "v1beta3.ObjectReference", + "properties": { + "apiVersion": { + "type": "string", + "description": "API version of the referent" + }, + "fieldPath": { + "type": "string", + "description": "if referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]" + }, + "kind": { + "type": "string", + "description": "kind of the referent" + }, + "name": { + "type": "string", + "description": "name of the referent" + }, + "namespace": { + "type": "string", + "description": "namespace of the referent" + }, + "resourceVersion": { + "type": "string", + "description": "specific resourceVersion to which this reference is made, if any: http://docs.k8s.io/api-conventions.md#concurrency-control-and-consistency" + }, + "uid": { + "type": "string", + "description": "uid of the referent" + } + } + }, + "v1beta3.ObjectMeta": { + "id": "v1beta3.ObjectMeta", + "properties": { + "annotations": { + "type": "any", + "description": "map of string keys and values that can be used by external tooling to store and retrieve arbitrary metadata about objects" + }, + "creationTimestamp": { + "type": "string", + "description": "RFC 3339 date and time at which the object was created; populated by the system, read-only; null for lists" + }, + "deletionTimestamp": { + "type": "string", + "description": "RFC 3339 date and time at which the object will be deleted; populated by the system when a graceful deletion is requested, read-only; if not set, graceful deletion of the object has not been requested" + }, + "generateName": { + "type": "string", + "description": "an optional prefix to use to generate a unique name; has the same validation rules as name; optional, and is applied only name if is not specified" + }, + "labels": { + "type": "any", + "description": "map of string keys and values that can be used to organize and categorize objects; may match selectors of replication controllers and services" + }, + "name": { + "type": "string", + "description": "string that identifies an object. Must be unique within a namespace; cannot be updated" + }, + "namespace": { + "type": "string", + "description": "namespace of the object; cannot be updated" + }, + "resourceVersion": { + "type": "string", + "description": "string that identifies the internal version of this object that can be used by clients to determine when objects have changed; populated by the system, read-only; value must be treated as opaque by clients and passed unmodified back to the server: http://docs.k8s.io/api-conventions.md#concurrency-control-and-consistency" + }, + "selfLink": { + "type": "string", + "description": "URL for the object; populated by the system, read-only" + }, + "uid": { + "type": "string", + "description": "unique UUID across space and time; populated by the system; read-only" + } + } + } + } +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/test/scala/python/PythonTest.scala b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala new file mode 100644 index 00000000000..ec42985586c --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/python/PythonTest.scala @@ -0,0 +1,34 @@ +package python + +import com.wordnik.swagger.codegen.languages.{PythonClientCodegen} +import io.swagger.parser.SwaggerParser +import org.junit.runner.RunWith + +import org.scalatest.junit.JUnitRunner +import org.scalatest.FlatSpec +import org.scalatest.Matchers + +@RunWith(classOf[JUnitRunner]) +class PythonTest extends FlatSpec with Matchers { + it should "convert a python model with dots" in { + val swagger = new SwaggerParser() + .read("src/test/resources/2_0/v1beta3.json") + + val codegen = new PythonClientCodegen() + val simpleName = codegen.fromModel("v1beta3.Binding", swagger.getDefinitions().get("v1beta3.Binding")) + simpleName.name should be("v1beta3.Binding") + simpleName.classname should be("V1beta3Binding") + simpleName.classVarName should be("v1beta3_binding") + + val compoundName = codegen.fromModel("v1beta3.ComponentStatus", swagger.getDefinitions().get("v1beta3.ComponentStatus")) + compoundName.name should be("v1beta3.ComponentStatus") + compoundName.classname should be("V1beta3ComponentStatus") + compoundName.classVarName should be("v1beta3_component_status") + + val path = "/api/v1beta3/namespaces/{namespaces}/bindings" + val operation = swagger.getPaths().get(path).getPost() + val codegenOperation = codegen.fromOperation(path, "get", operation, swagger.getDefinitions()) + codegenOperation.returnType should be("V1beta3Binding") + codegenOperation.returnBaseType should be("V1beta3Binding") + } +} From e717f74a0a022b48ebfa12667666c89e5323f2e5 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 19 May 2015 21:15:09 +0800 Subject: [PATCH 41/75] update readme with new generators --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 0687abed1ee..cb649e07da5 100644 --- a/README.md +++ b/README.md @@ -150,8 +150,11 @@ JavaClientCodegen.java JaxRSServerCodegen.java NodeJSServerCodegen.java ObjcClientCodegen.java +PerlClientCodegen.java PhpClientCodegen.java +Python3ClientCodegen.java PythonClientCodegen.java +Qt5CPPGenerator.java RubyClientCodegen.java ScalaClientCodegen.java ScalatraServerCodegen.java From f0e4ea178036e0a5f69b9e39ea451553702c6a82 Mon Sep 17 00:00:00 2001 From: Alexey Nechaev Date: Tue, 19 May 2015 18:36:03 +0300 Subject: [PATCH 42/75] Fixed #728: Handling of recursive model definitions has been improved. --- .../codegen/examples/XmlExampleGenerator.java | 44 ++++++++---- .../src/test/scala/ExampleGeneratorTest.scala | 67 +++++++++++++++++++ 2 files changed, 98 insertions(+), 13 deletions(-) create mode 100644 modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java index 40df89507e3..b1896605cdf 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/examples/XmlExampleGenerator.java @@ -8,6 +8,8 @@ import com.wordnik.swagger.models.properties.*; import java.text.SimpleDateFormat; import java.util.*; +import org.codehaus.plexus.util.StringUtils; + public class XmlExampleGenerator { public static String NEWLINE = "\n"; public static String TAG_START = "<"; @@ -16,6 +18,7 @@ public class XmlExampleGenerator { protected Map examples; protected SimpleDateFormat dtFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); protected SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); + private static String EMPTY = ""; public XmlExampleGenerator(Map examples) { this.examples = examples; @@ -24,29 +27,36 @@ public class XmlExampleGenerator { } public String toXml(Property property) { - return toXml(null, property, 0); + return toXml(null, property, 0, Collections.emptySet()); } - protected String toXml(Model model, int indent) { + protected String toXml(Model model, int indent, Collection path) { if(model instanceof RefModel) { RefModel ref = (RefModel) model; Model actualModel = examples.get(ref.getSimpleRef()); if(actualModel instanceof ModelImpl) - return modelImplToXml((ModelImpl)actualModel, indent); + return modelImplToXml((ModelImpl) actualModel, indent, path); } else if(model instanceof ModelImpl) { - return modelImplToXml((ModelImpl)model, indent); + return modelImplToXml((ModelImpl) model, indent, path); } return null; } - protected String modelImplToXml(ModelImpl model, int indent) { + protected String modelImplToXml(ModelImpl model, int indent, Collection path) { + final String modelName = model.getName(); + if (path.contains(modelName)) { + return EMPTY; + } + final Set selfPath = new HashSet(path); + selfPath.add(modelName); + StringBuilder sb = new StringBuilder(); // attributes Map attributes = new LinkedHashMap(); Map elements = new LinkedHashMap(); - String name = model.getName(); + String name = modelName; String namespace; String prefix; Boolean wrapped; @@ -67,13 +77,17 @@ public class XmlExampleGenerator { sb.append(name); for(String pName : attributes.keySet()) { Property p = attributes.get(pName); - sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0))); + sb.append(" ").append(pName).append("=").append(quote(toXml(null, p, 0, selfPath))); } sb.append(CLOSE_TAG); sb.append(NEWLINE); for(String pName : elements.keySet()) { Property p = elements.get(pName); - sb.append(toXml(pName, p, indent + 1)); + final String asXml = toXml(pName, p, indent + 1, selfPath); + if (StringUtils.isEmpty(asXml)) { + continue; + } + sb.append(asXml); sb.append(NEWLINE); } sb.append(indent(indent)).append(TAG_END).append(name).append(CLOSE_TAG); @@ -85,7 +99,7 @@ public class XmlExampleGenerator { return "\"" + string + "\""; } - protected String toXml(String name, Property property, int indent) { + protected String toXml(String name, Property property, int indent, Collection path) { if(property == null) { return ""; } @@ -98,12 +112,16 @@ public class XmlExampleGenerator { if(property.getXml() != null && property.getXml().getWrapped()) wrapped = true; if(wrapped) { + String prefix = EMPTY; if(name != null) { sb.append(indent(indent)); sb.append(openTag(name)); - sb.append(NEWLINE); + prefix = NEWLINE; + } + final String asXml = toXml(name, inner, indent + 1, path); + if (StringUtils.isNotEmpty(asXml)) { + sb.append(prefix).append(asXml); } - sb.append(toXml(name, inner, indent + 1)); if(name != null) { sb.append(NEWLINE); sb.append(indent(indent)); @@ -111,12 +129,12 @@ public class XmlExampleGenerator { } } else - sb.append(toXml(name, inner, indent)); + sb.append(toXml(name, inner, indent, path)); } else if(property instanceof RefProperty) { RefProperty ref = (RefProperty) property; Model actualModel = examples.get(ref.getSimpleRef()); - sb.append(toXml(actualModel, indent)); + sb.append(toXml(actualModel, indent, path)); } else { if(name != null) { diff --git a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala new file mode 100644 index 00000000000..5407202c5d3 --- /dev/null +++ b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala @@ -0,0 +1,67 @@ +import scala.collection.JavaConverters.asScalaBufferConverter +import scala.collection.JavaConverters.mapAsJavaMapConverter +import scala.collection.JavaConverters.seqAsJavaListConverter + +import org.junit.runner.RunWith +import org.scalatest.FlatSpec +import org.scalatest.Matchers +import org.scalatest.junit.JUnitRunner + +import com.wordnik.swagger.codegen.examples.ExampleGenerator +import com.wordnik.swagger.models.Model +import com.wordnik.swagger.models.ModelImpl +import com.wordnik.swagger.models.Xml +import com.wordnik.swagger.models.properties.ArrayProperty +import com.wordnik.swagger.models.properties.RefProperty +import com.wordnik.swagger.models.properties.StringProperty + +@RunWith(classOf[JUnitRunner]) +class ExampleGeneratorTest extends FlatSpec with Matchers { + val json = "application/json" + val xml = "application/xml" + + it should "check handling of recursive models" in { + val nodeType = "Node" + val ref = new RefProperty(nodeType) + val node = new ModelImpl().name(nodeType).property("name", new StringProperty()) + node.property("parent", ref) + node.property("children", new ArrayProperty(ref)) + node.property("wrappedChildren", new ArrayProperty(ref).xml(new Xml().wrapped(true))) + val pairType = "Pair" + val pair = new ModelImpl().name(pairType) + for (item <- Map("first" -> "First", "second" -> "Second")) { + val property = new RefProperty(nodeType) + property.setXml(new Xml().name(item._2)) + pair.property(item._1, property); + } + val types = scala.collection.mutable.Buffer[String]() + val expectedTypes = List(json, xml) + val eg = new ExampleGenerator(Map[String, Model](nodeType -> node, pairType -> pair).asJava) + for (item <- eg.generate(null, expectedTypes.asJava, new RefProperty(pairType)).asScala) { + val example = item.get("example") + item.get("contentType") match { + case `xml` => { + types += xml + example should be ("\\n" + + " \\n" + + " string\\n" + + " \\n" + + " \\n" + + " \\n" + + " \\n" + + " string\\n" + + " \\n" + + " \\n" + + " \\n" + + "") + } + case `json` => { + types += json + // TODO - add JSON validation + example should not be (null) + } + } + } + types should be (expectedTypes) + } +} From b783363c56a0297cec92eda86aeb86277ed9272b Mon Sep 17 00:00:00 2001 From: Fake Bob Dobbs Date: Tue, 19 May 2015 11:45:48 -0400 Subject: [PATCH 43/75] move the defaultValues for Forms and Headers as well --- .../java/com/wordnik/swagger/codegen/DefaultCodegen.java | 5 +++++ 1 file changed, 5 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 966cc817863..d6906187c3b 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 @@ -904,8 +904,13 @@ public class DefaultCodegen { p.required = param.getRequired(); p.jsonSchema = Json.pretty(param); + // move the defaultValue for headers, forms and params if(param instanceof QueryParameter) { p.defaultValue = ((QueryParameter)param).getDefaultValue(); + } else if(param instanceof HeaderParameter) { + p.defaultValue = ((HeaderParameter)param).getDefaultValue(); + } else if(param instanceof FormParameter) { + p.defaultValue = ((FormParameter)param).getDefaultValue(); } if(param instanceof SerializableParameter) { From a55c03013d5658a5c28aa6f1fdf5cbe85d56cb0d Mon Sep 17 00:00:00 2001 From: Fake Bob Dobbs Date: Tue, 19 May 2015 11:47:34 -0400 Subject: [PATCH 44/75] use the defaultValue for spring mvc RequestHeader annotations; carry over the required value if set for RequestPart annotations --- .../src/main/resources/JavaSpringMVC/formParams.mustache | 2 +- .../src/main/resources/JavaSpringMVC/headerParams.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache index 83c928ea92e..402a684f86a 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/formParams.mustache @@ -1,2 +1,2 @@ {{#isFormParam}}{{#notFile}} -@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestPart("{{paramName}}") {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file +@ApiParam(value = "{{{description}}}"{{#required}}, required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestPart(value="{{paramName}}"{{#required}}, required=true{{/required}}{{^required}}, required=false{{/required}}) {{{dataType}}} {{paramName}}{{/notFile}}{{#isFile}}@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache index dd0ea1ad4ce..7e500ac33cb 100644 --- a/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaSpringMVC/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}})@RequestHeader("{{paramName}}") {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}@ApiParam(value = "{{{description}}}" {{#required}},required=true{{/required}} {{#allowableValues}}, allowableValues="{{{allowableValues}}}"{{/allowableValues}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) @RequestHeader(value="{{paramName}}", required={{#required}}true{{/required}}{{^required}}false{{/required}}{{#defaultValue}}, defaultValue="{{{defaultValue}}}"{{/defaultValue}}) {{{dataType}}} {{paramName}}{{/isHeaderParam}} \ No newline at end of file From 104bcc1f89a5b086e820fd9fec9f267136eefb6e Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:35:58 +0800 Subject: [PATCH 45/75] Organize generated Ruby code into a module --- .../wordnik/swagger/codegen/CodegenModel.java | 4 +- .../swagger/codegen/DefaultCodegen.java | 1 + .../swagger/codegen/DefaultGenerator.java | 1 + .../codegen/languages/RubyClientCodegen.java | 75 +-- .../src/main/resources/ruby/api.mustache | 84 ++-- .../src/main/resources/ruby/model.mustache | 71 +-- .../ruby/swagger-client.gemspec.mustache | 8 +- .../resources/ruby/swagger-client.mustache | 29 +- .../src/main/resources/ruby/swagger.mustache | 134 +++-- .../ruby/swagger/configuration.mustache | 33 +- .../resources/ruby/swagger/request.mustache | 466 +++++++++--------- .../resources/ruby/swagger/response.mustache | 124 ++--- .../resources/ruby/swagger/version.mustache | 7 +- 13 files changed, 531 insertions(+), 506 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 169886da22e..274b77b4e9d 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -7,10 +7,10 @@ import java.util.*; public class CodegenModel { public String parent; - public String name, classname, description, classVarName, modelJson; + public String name, classname, importPath, description, classVarName, modelJson; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); public Boolean hasVars, emptyVars, hasMoreModels; public ExternalDocs externalDocs; -} \ No newline at end of file +} 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 6f51374c536..3642e8de1b6 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 @@ -428,6 +428,7 @@ public class DefaultCodegen { m.name = name; m.description = escapeText(model.getDescription()); m.classname = toModelName(name); + m.importPath = toModelImport(name); m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); m.externalDocs = model.getExternalDocs(); 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 17509973215..395f298eb07 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 @@ -165,6 +165,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { operation.putAll(config.additionalProperties()); operation.put("classname", config.toApiName(tag)); operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); allOperations.add(new HashMap(operation)); for (int i = 0; i < allOperations.size(); i++) { 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 99f56bf5d41..5fb8ee5eb8f 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 @@ -8,10 +8,9 @@ import java.util.*; import java.io.File; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String invokerPackage = "com.wordnik.client"; - protected String groupId = "com.wordnik"; - protected String artifactId = "swagger-client"; - protected String artifactVersion = "1.0.0"; + protected String gemName = "swagger-client"; + protected String moduleName = null; + protected String libFolder = "lib"; public CodegenType getTag() { return CodegenType.CLIENT; @@ -25,10 +24,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { return "Generates a Ruby client library."; } + /** + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger-client". + */ + public String generateModuleName() { + return camelize(gemName.replaceAll("[^\\w]+", "_")); + } + public RubyClientCodegen() { super(); - modelPackage = "models"; - apiPackage = "lib"; + moduleName = generateModuleName(); + modelPackage = gemName + "/models"; + apiPackage = gemName + "/api"; outputFolder = "generated-code/ruby"; modelTemplateFiles.put("model.mustache", ".rb"); apiTemplateFiles.put("api.mustache", ".rb"); @@ -39,17 +46,15 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { reservedWords = new HashSet ( Arrays.asList( - "__FILE__", "and", "def", "end", "in", "or", "self", "unless", "__LINE__", + "__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", + "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); - additionalProperties.put("groupId", groupId); - additionalProperties.put("artifactId", artifactId); - additionalProperties.put("artifactVersion", artifactVersion); + additionalProperties.put("gemName", gemName); + additionalProperties.put("moduleName", moduleName); languageSpecificPrimitives.add("int"); languageSpecificPrimitives.add("array"); @@ -64,15 +69,18 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("List", "array"); typeMapping.put("map", "map"); - supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", "swagger-client.gemspec")); - supportingFiles.add(new SupportingFile("swagger-client.mustache", "", "lib/swagger-client.rb")); - supportingFiles.add(new SupportingFile("swagger.mustache", "", "lib/swagger.rb")); - supportingFiles.add(new SupportingFile("monkey.mustache", "", "lib/monkey.rb")); - supportingFiles.add(new SupportingFile("swagger/request.mustache", "", "lib/swagger/request.rb")); - supportingFiles.add(new SupportingFile("swagger/response.mustache", "", "lib/swagger/response.rb")); - supportingFiles.add(new SupportingFile("swagger/version.mustache", "", "lib/swagger/version.rb")); - supportingFiles.add(new SupportingFile("swagger/configuration.mustache", "", "lib/swagger/configuration.rb")); - supportingFiles.add(new SupportingFile("base_object.mustache", "", "models/base_object.rb")); + String baseFolder = "lib/" + gemName; + String swaggerFolder = baseFolder + "/swagger"; + String modelFolder = baseFolder + "/models"; + supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("swagger-client.mustache", "lib", gemName + ".rb")); + supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); + supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); + supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb")); + supportingFiles.add(new SupportingFile("swagger/response.mustache", swaggerFolder, "response.rb")); + supportingFiles.add(new SupportingFile("swagger/version.mustache", swaggerFolder, "version.rb")); + supportingFiles.add(new SupportingFile("swagger/configuration.mustache", swaggerFolder, "configuration.rb")); + supportingFiles.add(new SupportingFile("base_object.mustache", modelFolder, "base_object.rb")); } @Override @@ -82,11 +90,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { @Override public String apiFileFolder() { - return outputFolder + "/" + apiPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "api"; } public String modelFileFolder() { - return outputFolder + "/" + modelPackage().replace('.', File.separatorChar); + return outputFolder + File.separatorChar + "lib" + File.separatorChar + gemName + File.separatorChar + "models"; } @Override @@ -150,13 +158,13 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // 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); @@ -167,11 +175,11 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { // 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) { @@ -186,7 +194,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { public String toApiName(String name) { if(name.length() == 0) return "DefaultApi"; - // e.g. phone_number_api => PhoneNumberApi + // e.g. phone_number_api => PhoneNumberApi return camelize(name) + "Api"; } @@ -196,8 +204,17 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { if(reservedWords.contains(operationId)) throw new RuntimeException(operationId + " (reserved word) cannot be used as method name"); - return underscore(operationId); + return underscore(operationId); } + @Override + public String toModelImport(String name) { + return modelPackage() + "/" + toModelFilename(name); + } + + @Override + public String toApiImport(String name) { + return apiPackage() + "/" + toApiFilename(name); + } } diff --git a/modules/swagger-codegen/src/main/resources/ruby/api.mustache b/modules/swagger-codegen/src/main/resources/ruby/api.mustache index 038a40f66ea..ba38a8157b5 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/api.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/api.mustache @@ -1,57 +1,59 @@ require "uri" +module {{moduleName}} {{#operations}} -class {{classname}} - basePath = "{{basePath}}" - # apiInvoker = APIInvoker + class {{classname}} + basePath = "{{basePath}}" + # apiInvoker = APIInvoker {{#operation}} {{newline}} - # {{summary}} - # {{notes}} -{{#allParams}}{{#required}} # @param {{paramName}} {{description}} -{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters -{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} -{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} - def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) - {{#allParams}}{{#required}} - # verify the required parameter '{{paramName}}' is set - raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? - {{/required}}{{/allParams}} + # {{summary}} + # {{notes}} +{{#allParams}}{{#required}} # @param {{paramName}} {{description}} +{{/required}}{{/allParams}} # @param [Hash] opts the optional parameters +{{#allParams}}{{^required}} # @option opts [{{dataType}}] :{{paramName}} {{description}} +{{/required}}{{/allParams}} # @return {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} + def self.{{nickname}}({{#allParams}}{{#required}}{{paramName}}, {{/required}}{{/allParams}}opts = {}) + {{#allParams}}{{#required}} + # verify the required parameter '{{paramName}}' is set + raise "Missing the required parameter '{{paramName}}' when calling {{nickname}}" if {{{paramName}}}.nil? + {{/required}}{{/allParams}} - # resource path - path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} + # resource path + path = "{{path}}".sub('{format}','json'){{#pathParams}}.sub('{' + '{{baseName}}' + '}', {{paramName}}.to_s){{/pathParams}} - # query parameters - query_params = {}{{#queryParams}}{{#required}} - query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} - query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} + # query parameters + query_params = {}{{#queryParams}}{{#required}} + query_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/queryParams}}{{#queryParams}}{{^required}} + query_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/queryParams}} - # header parameters - header_params = {} + # header parameters + header_params = {} - # HTTP header 'Accept' (if needed) - _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Accept' (if needed) + _header_accept = [{{#produces}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/produces}}] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - # HTTP header 'Content-Type' - _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} - header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} - header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} + # HTTP header 'Content-Type' + _header_content_type = [{{#consumes}}'{{mediaType}}'{{#hasMore}}, {{/hasMore}}{{/consumes}}] + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type){{#headerParams}}{{#required}} + header_params[:'{{{baseName}}}'] = {{{paramName}}}{{/required}}{{/headerParams}}{{#headerParams}}{{^required}} + header_params[:'{{{baseName}}}'] = opts[:'{{{paramName}}}'] if opts[:'{{{paramName}}}']{{/required}}{{/headerParams}} - # form parameters - form_params = {}{{#formParams}}{{#required}} - form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} - form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} + # form parameters + form_params = {}{{#formParams}}{{#required}} + form_params["{{baseName}}"] = {{paramName}}{{/required}}{{/formParams}}{{#formParams}}{{^required}} + form_params["{{baseName}}"] = opts[:'{{paramName}}'] if opts[:'{{paramName}}']{{/required}}{{/formParams}} - # http body (model) - {{^bodyParam}}post_body = nil - {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) - {{/bodyParam}} + # http body (model) + {{^bodyParam}}post_body = nil + {{/bodyParam}}{{#bodyParam}}post_body = Swagger::Request.object_to_http_body({{#required}}{{{paramName}}}{{/required}}{{^required}}opts[:'{{{paramName}}}']{{/required}}) + {{/bodyParam}} - {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} + {{#returnType}}response = Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + {{#returnContainer}}response.map {|response| {{/returnContainer}}obj = {{returnBaseType}}.new() and obj.build_from_hash(response){{#returnContainer}} }{{/returnContainer}}{{/returnType}}{{^returnType}} Swagger::Request.new(:{{httpMethod}}, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make{{/returnType}} end {{/operation}} -end + end {{/operations}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 362664aa2b7..23e589b0862 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,41 +1,42 @@ require_relative 'base_object' -{{#models}}#{{description}} -{{#model}}class {{classname}} < BaseObject - attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - {{#vars}} - # {{description}} - :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - # attribute type - def self.swagger_types - { - {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} - {{/vars}} - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - {{#vars}} - if attributes[:'{{{baseName}}}'] - {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) - @{{{name}}} = value - end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} +module {{moduleName}} +{{#models}} # {{description}} +{{#model}} class {{classname}} < BaseObject + attr_accessor {{#vars}}:{{{name}}}{{#hasMore}}, {{/hasMore}}{{/vars}}{{newline}} + # attribute mapping from ruby-style variable name to JSON key + def self.attribute_map + { + {{#vars}} + # {{description}} + :'{{{name}}}' => :'{{{baseName}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } end - {{/vars}} - end -end + # attribute type + def self.swagger_types + { + {{#vars}}:'{{{name}}}' => :'{{{datatype}}}'{{#hasMore}},{{/hasMore}} + {{/vars}} + } + end + + def initialize(attributes = {}) + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + {{#vars}} + if attributes[:'{{{baseName}}}'] + {{#isContainer}}if (value = attributes[:'{{{baseName}}}']).is_a?(Array) + @{{{name}}} = value + end{{/isContainer}}{{^isContainer}}@{{{name}}} = attributes[:'{{{baseName}}}']{{/isContainer}} + end + {{/vars}} + end + end {{/model}} {{/models}} +end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache index c002e581b8b..d23c4851b24 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger/version" +require "{{gemName}}/swagger/version" Gem::Specification.new do |s| - s.name = "{{artifactId}}" - s.version = Swagger::VERSION + s.name = "{{gemName}}" + s.version = {{moduleName}}::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "tony@wordnik.com"] @@ -12,8 +12,6 @@ Gem::Specification.new do |s| s.summary = %q{A ruby wrapper for the swagger APIs} s.description = %q{This gem maps to a swagger API} - s.rubyforge_project = "{{artifactId}}" - s.add_dependency 'typhoeus', '>=0.2.1' s.add_dependency 'addressable', '>=2.2.4' s.add_dependency 'json', '>=1.4.6' diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache index b13f83b1dbc..78d45438825 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache @@ -1,5 +1,26 @@ -require 'monkey' -require 'swagger' +# Swagger common files +require '{{gemName}}/monkey' +require '{{gemName}}/swagger' +require '{{gemName}}/swagger/configuration' +require '{{gemName}}/swagger/request' +require '{{gemName}}/swagger/response' +require '{{gemName}}/swagger/version' -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } +# Models +{{#models}} +{{#model}} +require '{{importPath}}' +{{/model}} +{{/models}} + +# APIs +{{#apiInfo}} +{{#apis}} +require '{{importPath}}' +{{/apis}} +{{/apiInfo}} + +module {{moduleName}} + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache index f393330b148..750e6ac5155 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger.mustache @@ -1,86 +1,78 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' require 'logger' require 'json' -module Swagger - - @configuration = Configuration.new +module {{moduleName}} + module Swagger + class << self + attr_accessor :logger - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? + attr_accessor :resources - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] end - end - -end -class ServerError < StandardError -end + class ServerError < StandardError + end -class ClientError < StandardError + class ClientError < StandardError + end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache index d27109aa445..e780a9c8e7d 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/configuration.mustache @@ -1,22 +1,19 @@ -module Swagger - - class Configuration - require 'swagger/version' +module {{moduleName}} + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = '{{scheme}}' - @host = '{{host}}' - @base_path = '{{contextPath}}' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = '{{scheme}}' + @host = '{{host}}' + @base_path = '{{contextPath}}' + @user_agent = "ruby-swagger-#{Swagger::VERSION}" + @inject_format = false + @force_ending_format = false + @camelize_params = true + end end - end - end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache index 4ec071b93d5..14718bb6b3c 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/request.mustache @@ -1,263 +1,257 @@ -module Swagger +module {{moduleName}} + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + end - # Iterate over the params hash, injecting any path values into the path string - # - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) end end - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') + end + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if @body.nil? && @form_params && !@form_params.empty? + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json end end - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') end end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one end - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json end - end - - # Construct a query string from the query-string-type params - def query_string - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) end - query_values[key] = value.to_s + _body.to_json end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache index 641b7ccc756..e7bb482fb66 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/response.mustache @@ -1,70 +1,70 @@ -module Swagger +module {{moduleName}} + module Swagger + class Response + require 'json' - class Response - require 'json' + attr_accessor :raw - attr_accessor :raw + def initialize(raw) + self.raw = raw - def initialize(raw) - self.raw = raw + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse(raw.body, :symbolize_names => true) + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') end end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache index 39357c0ed6d..332a5e66f45 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache @@ -1,4 +1,5 @@ -module Swagger - VERSION = "4.06.08" +module {{moduleName}} + module Swagger + VERSION = "{{appVersion}}" + end end - From 8dd7d3aacd69d50c42c417e8252ccb4aec36a193 Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:41:39 +0800 Subject: [PATCH 46/75] Regenerate ruby petstore sample code --- samples/client/petstore/ruby/Gemfile.lock | 2 +- .../petstore/ruby/lib/swagger-client.rb | 27 +- .../ruby/lib/swagger-client/api/pet_api.rb | 323 ++++++++++++++++ .../ruby/lib/swagger-client/api/store_api.rb | 160 ++++++++ .../ruby/lib/swagger-client/api/user_api.rb | 352 ++++++++++++++++++ .../lib/swagger-client/models/category.rb | 35 ++ .../ruby/lib/swagger-client/models/order.rb | 55 +++ .../ruby/lib/swagger-client/models/pet.rb | 59 +++ .../ruby/lib/swagger-client/models/tag.rb | 35 ++ .../ruby/lib/swagger-client/models/user.rb | 65 ++++ .../ruby/lib/{ => swagger-client}/monkey.rb | 0 .../ruby/lib/swagger-client/swagger.rb | 77 ++++ .../swagger-client/swagger/configuration.rb | 19 + .../lib/swagger-client/swagger/request.rb | 205 ++++++++++ .../lib/swagger-client/swagger/response.rb | 70 ++++ .../lib/swagger-client/swagger/version.rb | 5 + .../ruby/lib/swagger/configuration.rb | 22 -- .../petstore/ruby/lib/swagger/version.rb | 4 - .../petstore/ruby/swagger-client.gemspec | 6 +- 19 files changed, 1486 insertions(+), 35 deletions(-) create mode 100644 samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/category.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/order.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/pet.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/tag.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/models/user.rb rename samples/client/petstore/ruby/lib/{ => swagger-client}/monkey.rb (100%) create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb create mode 100644 samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/configuration.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/version.rb diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 232facf4677..028579303ec 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - swagger-client (4.06.08) + swagger-client (1.0.0) addressable (>= 2.2.4) json (>= 1.4.6) typhoeus (>= 0.2.1) diff --git a/samples/client/petstore/ruby/lib/swagger-client.rb b/samples/client/petstore/ruby/lib/swagger-client.rb index b13f83b1dbc..05867456a68 100644 --- a/samples/client/petstore/ruby/lib/swagger-client.rb +++ b/samples/client/petstore/ruby/lib/swagger-client.rb @@ -1,5 +1,24 @@ -require 'monkey' -require 'swagger' +# Swagger common files +require 'swagger-client/monkey' +require 'swagger-client/swagger' +require 'swagger-client/swagger/configuration' +require 'swagger-client/swagger/request' +require 'swagger-client/swagger/response' +require 'swagger-client/swagger/version' -Dir[File.join(File.dirname(__FILE__), "../lib/*.rb")].each {|file| require file if file !~ /swagger-client\.rb\z/ } -Dir[File.join(File.dirname(__FILE__), "../models/*.rb")].each {|file| require file } +# Models +require 'swagger-client/models/user' +require 'swagger-client/models/category' +require 'swagger-client/models/pet' +require 'swagger-client/models/tag' +require 'swagger-client/models/order' + +# APIs +require 'swagger-client/api/user_api' +require 'swagger-client/api/pet_api' +require 'swagger-client/api/store_api' + +module SwaggerClient + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb b/samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb new file mode 100644 index 00000000000..25a1a8f8bf4 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb @@ -0,0 +1,323 @@ +require "uri" + +module SwaggerClient + class PetApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Update an existing pet + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return void + def self.update_pet(opts = {}) + # verify existence of params + + # resource path + path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = ['application/json', 'application/xml', ] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Add a new pet to the store + # + # @param [Hash] opts the optional parameters + # @option opts [Pet] :body Pet object that needs to be added to the store + # @return void + def self.add_pet(opts = {}) + # verify existence of params + + # resource path + path = "/pet".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = ['application/json', 'application/xml', ] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Finds Pets by status + # Multiple status values can be provided with comma seperated strings + # @param [Hash] opts the optional parameters + # @option opts [array[string]] :status Status values that need to be considered for filter + # @return array[Pet] + def self.find_pets_by_status(opts = {}) + # verify existence of params + + # resource path + path = "/pet/findByStatus".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'status'] = opts[:'status'] if opts[:'status'] + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + response.map {|response| Pet.new(response) } + end + + # Finds Pets by tags + # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. + # @param [Hash] opts the optional parameters + # @option opts [array[string]] :tags Tags to filter by + # @return array[Pet] + def self.find_pets_by_tags(opts = {}) + # verify existence of params + + # resource path + path = "/pet/findByTags".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + response.map {|response| Pet.new(response) } + end + + # Find pet by ID + # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions + # @param pet_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return Pet + def self.get_pet_by_id(pet_id, opts = {}) + # verify existence of params + raise "pet_id is required" if pet_id.nil? + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + Pet.new(response) + end + + # Updates a pet in the store with form data + # + # @param pet_id ID of pet that needs to be updated + # @param [Hash] opts the optional parameters + # @option opts [string] :name Updated name of the pet + # @option opts [string] :status Updated status of the pet + # @return void + def self.update_pet_with_form(pet_id, opts = {}) + # verify existence of params + raise "pet_id is required" if pet_id.nil? + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = ['application/x-www-form-urlencoded', ] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + form_params["name"] = opts[:'name'] if opts[:'name'] + form_params["status"] = opts[:'status'] if opts[:'status'] + + # http body (model) + post_body = nil + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Deletes a pet + # + # @param pet_id Pet id to delete + # @param [Hash] opts the optional parameters + # @option opts [string] :api_key + # @return void + def self.delete_pet(pet_id, opts = {}) + # verify existence of params + raise "pet_id is required" if pet_id.nil? + + # resource path + path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # uploads an image + # + # @param pet_id ID of pet to update + # @param [Hash] opts the optional parameters + # @option opts [string] :additional_metadata Additional data to pass to server + # @option opts [file] :file file to upload + # @return void + def self.upload_file(pet_id, opts = {}) + # verify existence of params + raise "pet_id is required" if pet_id.nil? + + # resource path + path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = ['multipart/form-data', ] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata'] + form_params["file"] = opts[:'file'] if opts[:'file'] + + # http body (model) + post_body = nil + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb b/samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb new file mode 100644 index 00000000000..40a0d63c7ab --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb @@ -0,0 +1,160 @@ +require "uri" + +module SwaggerClient + class StoreApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Returns pet inventories by status + # Returns a map of status codes to quantities + # @param [Hash] opts the optional parameters + # @return map[string,int] + def self.get_inventory(opts = {}) + # verify existence of params + + # resource path + path = "/store/inventory".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + response.map {|response| map.new(response) } + end + + # Place an order for a pet + # + # @param [Hash] opts the optional parameters + # @option opts [Order] :body order placed for purchasing the pet + # @return Order + def self.place_order(opts = {}) + # verify existence of params + + # resource path + path = "/store/order".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + Order.new(response) + end + + # Find purchase order by ID + # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + # @param order_id ID of pet that needs to be fetched + # @param [Hash] opts the optional parameters + # @return Order + def self.get_order_by_id(order_id, opts = {}) + # verify existence of params + raise "order_id is required" if order_id.nil? + + # resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + Order.new(response) + end + + # Delete purchase order by ID + # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + # @param order_id ID of the order that needs to be deleted + # @param [Hash] opts the optional parameters + # @return void + def self.delete_order(order_id, opts = {}) + # verify existence of params + raise "order_id is required" if order_id.nil? + + # resource path + path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb b/samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb new file mode 100644 index 00000000000..0df9d287199 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb @@ -0,0 +1,352 @@ +require "uri" + +module SwaggerClient + class UserApi + basePath = "http://petstore.swagger.io/v2" + # apiInvoker = APIInvoker + + # Create user + # This can only be done by the logged in user. + # @param [Hash] opts the optional parameters + # @option opts [User] :body Created user object + # @return void + def self.create_user(opts = {}) + # verify existence of params + + # resource path + path = "/user".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Creates list of users with given input array + # + # @param [Hash] opts the optional parameters + # @option opts [array[User]] :body List of user object + # @return void + def self.create_users_with_array_input(opts = {}) + # verify existence of params + + # resource path + path = "/user/createWithArray".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Creates list of users with given input array + # + # @param [Hash] opts the optional parameters + # @option opts [array[User]] :body List of user object + # @return void + def self.create_users_with_list_input(opts = {}) + # verify existence of params + + # resource path + path = "/user/createWithList".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Logs user into the system + # + # @param [Hash] opts the optional parameters + # @option opts [string] :username The user name for login + # @option opts [string] :password The password for login in clear text + # @return string + def self.login_user(opts = {}) + # verify existence of params + + # resource path + path = "/user/login".sub('{format}','json') + + # query parameters + query_params = {} + query_params[:'username'] = opts[:'username'] if opts[:'username'] + query_params[:'password'] = opts[:'password'] if opts[:'password'] + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + string.new(response) + end + + # Logs out current logged in user session + # + # @param [Hash] opts the optional parameters + # @return void + def self.logout_user(opts = {}) + # verify existence of params + + # resource path + path = "/user/logout".sub('{format}','json') + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Get user by user name + # + # @param username The name that needs to be fetched. Use user1 for testing. + # @param [Hash] opts the optional parameters + # @return User + def self.get_user_by_name(username, opts = {}) + # verify existence of params + raise "username is required" if username.nil? + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body + User.new(response) + end + + # Updated user + # This can only be done by the logged in user. + # @param username name that need to be deleted + # @param [Hash] opts the optional parameters + # @option opts [User] :body Updated user object + # @return void + def self.update_user(username, opts = {}) + # verify existence of params + raise "username is required" if username.nil? + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + _body_param = opts[:'body'] + if _body_param != nil + if _body_param.is_a?(Array) + _array = Array.new + _body_param.each do |item| + if item.respond_to?(:to_body) + _array.push item.to_body + else + _array.push item + end + end + post_body = _array + else + if _body_param.respond_to?(:to_body) + post_body = _body_param.to_body + else + post_body = _body_param + end + end + end + + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + + # Delete user + # This can only be done by the logged in user. + # @param username The name that needs to be deleted + # @param [Hash] opts the optional parameters + # @return void + def self.delete_user(username, opts = {}) + # verify existence of params + raise "username is required" if username.nil? + + # resource path + path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) + + # query parameters + query_params = {} + + # header parameters + header_params = {} + + _header_accept = 'application/json, application/xml' + header_params['Accept'] = _header_accept if _header_accept != '' + + _header_content_type = [] + header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + + # form parameters + form_params = {} + + # http body (model) + post_body = nil + + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/category.rb b/samples/client/petstore/ruby/lib/swagger-client/models/category.rb new file mode 100644 index 00000000000..87e41aad6fd --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/category.rb @@ -0,0 +1,35 @@ +module SwaggerClient + class Category + attr_accessor :id, :name + # :internal => :external + def self.attribute_map + { + :id => :'id', + :name => :'name' + + } + end + + def initialize(attributes = {}) + return if attributes.empty? + # Morph attribute keys into undescored rubyish style + + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + + if self.class.attribute_map[:"name"] + @name = attributes["name"] + end + + end + + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/order.rb b/samples/client/petstore/ruby/lib/swagger-client/models/order.rb new file mode 100644 index 00000000000..9adad6920ad --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/order.rb @@ -0,0 +1,55 @@ +module SwaggerClient + class Order + attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete + # :internal => :external + def self.attribute_map + { + :id => :'id', + :pet_id => :'petId', + :quantity => :'quantity', + :ship_date => :'shipDate', + :status => :'status', + :complete => :'complete' + + } + end + + def initialize(attributes = {}) + return if attributes.empty? + # Morph attribute keys into undescored rubyish style + + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + + 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[:"ship_date"] + @ship_date = attributes["shipDate"] + end + + if self.class.attribute_map[:"status"] + @status = attributes["status"] + end + + if self.class.attribute_map[:"complete"] + @complete = attributes["complete"] + end + + end + + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger-client/models/pet.rb new file mode 100644 index 00000000000..18e2be1dae0 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/pet.rb @@ -0,0 +1,59 @@ +module SwaggerClient + class Pet + attr_accessor :id, :category, :name, :photo_urls, :tags, :status + # :internal => :external + def self.attribute_map + { + :id => :'id', + :category => :'category', + :name => :'name', + :photo_urls => :'photoUrls', + :tags => :'tags', + :status => :'status' + + } + end + + def initialize(attributes = {}) + return if attributes.empty? + # Morph attribute keys into undescored rubyish style + + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + + if self.class.attribute_map[:"category"] + @category = attributes["category"] + end + + if self.class.attribute_map[:"name"] + @name = attributes["name"] + end + + if self.class.attribute_map[:"photo_urls"] + if (value = attributes["photoUrls"]).is_a?(Array) + @photo_urls = value + end + end + + if self.class.attribute_map[:"tags"] + if (value = attributes["tags"]).is_a?(Array) + @tags = value.map{ |v| Tag.new(v) } + end + end + + if self.class.attribute_map[:"status"] + @status = attributes["status"] + end + + end + + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger-client/models/tag.rb new file mode 100644 index 00000000000..41477ac7353 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/tag.rb @@ -0,0 +1,35 @@ +module SwaggerClient + class Tag + attr_accessor :id, :name + # :internal => :external + def self.attribute_map + { + :id => :'id', + :name => :'name' + + } + end + + def initialize(attributes = {}) + return if attributes.empty? + # Morph attribute keys into undescored rubyish style + + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + + if self.class.attribute_map[:"name"] + @name = attributes["name"] + end + + end + + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/user.rb b/samples/client/petstore/ruby/lib/swagger-client/models/user.rb new file mode 100644 index 00000000000..042d589726b --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/models/user.rb @@ -0,0 +1,65 @@ +module SwaggerClient + class User + attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status + # :internal => :external + def self.attribute_map + { + :id => :'id', + :username => :'username', + :first_name => :'firstName', + :last_name => :'lastName', + :email => :'email', + :password => :'password', + :phone => :'phone', + :user_status => :'userStatus' + + } + end + + def initialize(attributes = {}) + return if attributes.empty? + # Morph attribute keys into undescored rubyish style + + if self.class.attribute_map[:"id"] + @id = attributes["id"] + end + + if self.class.attribute_map[:"username"] + @username = attributes["username"] + end + + if self.class.attribute_map[:"first_name"] + @first_name = attributes["firstName"] + end + + if self.class.attribute_map[:"last_name"] + @last_name = attributes["lastName"] + end + + if self.class.attribute_map[:"email"] + @email = attributes["email"] + end + + if self.class.attribute_map[:"password"] + @password = attributes["password"] + end + + if self.class.attribute_map[:"phone"] + @phone = attributes["phone"] + end + + if self.class.attribute_map[:"user_status"] + @user_status = attributes["userStatus"] + end + + end + + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + end +end diff --git a/samples/client/petstore/ruby/lib/monkey.rb b/samples/client/petstore/ruby/lib/swagger-client/monkey.rb similarity index 100% rename from samples/client/petstore/ruby/lib/monkey.rb rename to samples/client/petstore/ruby/lib/swagger-client/monkey.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger.rb b/samples/client/petstore/ruby/lib/swagger-client/swagger.rb new file mode 100644 index 00000000000..925382cf94e --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger.rb @@ -0,0 +1,77 @@ +require 'logger' + +module SwaggerClient + module Swagger + class << self + attr_accessor :logger + + # A Swagger configuration object. Must act like a hash and return sensible + # values for all Swagger configuration options. See Swagger::Configuration. + attr_accessor :configuration + + attr_accessor :resources + + # Call this method to modify defaults in your initializers. + # + # @example + # Swagger.configure do |config| + # config.api_key = '1234567890abcdef' # required + # config.username = 'wordlover' # optional, but needed for user-related functions + # config.password = 'i<3words' # optional, but needed for user-related functions + # config.format = 'json' # optional, defaults to 'json' + # end + # + def configure + yield(configuration) if block_given? + + # Configure logger. Default to use Rails + self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) + + # remove :// from scheme + configuration.scheme.sub!(/:\/\//, '') + + # remove http(s):// and anything after a slash + configuration.host.sub!(/https?:\/\//, '') + configuration.host = configuration.host.split('/').first + + # Add leading and trailing slashes to base_path + configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') + configuration.base_path = "" if configuration.base_path == "/" + end + + def authenticated? + Swagger.configuration.auth_token.present? + end + + def de_authenticate + Swagger.configuration.auth_token = nil + end + + def authenticate + return if Swagger.authenticated? + + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? + raise ClientError, "Username and password are required to authenticate." + end + + request = Swagger::Request.new( + :get, + "account/authenticate/{username}", + :params => { + :username => Swagger.configuration.username, + :password => Swagger.configuration.password + } + ) + + response_body = request.response.body + Swagger.configuration.auth_token = response_body['token'] + end + end + end + + class ServerError < StandardError + end + + class ClientError < StandardError + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb new file mode 100644 index 00000000000..51f9539a9ab --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb @@ -0,0 +1,19 @@ +module SwaggerClient + module Swagger + class Configuration + attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent + + # Defaults go in here.. + def initialize + @format = 'json' + @scheme = 'http' + @host = 'petstore.swagger.io' + @base_path = '/v2' + @user_agent = "ruby-swagger-#{Swagger::VERSION}" + @inject_format = false + @force_ending_format = false + @camelize_params = true + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb new file mode 100644 index 00000000000..8a605784a3a --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb @@ -0,0 +1,205 @@ +module SwaggerClient + module Swagger + class Request + require 'uri' + require 'addressable/uri' + require 'typhoeus' + + attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params + + # All requests must have an HTTP method and a path + # Optionals parameters are :params, :headers, :body, :format, :host + def initialize(http_method, path, attributes={}) + attributes[:format] ||= Swagger.configuration.format + attributes[:params] ||= {} + + # Set default headers + default_headers = { + 'Content-Type' => "application/#{attributes[:format].downcase}", + :api_key => Swagger.configuration.api_key, + 'User-Agent' => Swagger.configuration.user_agent + } + + # api_key from headers hash trumps the default, even if its value is blank + if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) + default_headers.delete(:api_key) + end + + # api_key from params hash trumps all others (headers and default_headers) + if attributes[:params].present? && attributes[:params].has_key?(:api_key) + default_headers.delete(:api_key) + attributes[:headers].delete(:api_key) if attributes[:headers].present? + end + + # Merge argument headers into defaults + attributes[:headers] = default_headers.merge(attributes[:headers] || {}) + + # Stick in the auth token if there is one + if Swagger.authenticated? + attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) + end + + self.http_method = http_method.to_sym + self.path = path + attributes.each do |name, value| + send("#{name.to_s.underscore.to_sym}=", value) + end + end + + # Construct a base URL + def url(options = {}) + u = Addressable::URI.new( + :scheme => Swagger.configuration.scheme, + :host => Swagger.configuration.host, + :path => self.interpreted_path, + :query => self.query_string.sub(/\?/, '') + ).to_s + + # Drop trailing question mark, if present + u.sub! /\?$/, '' + + # Obfuscate API key? + u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] + + u + end + + # Iterate over the params hash, injecting any path values into the path string + # e.g. /word.{format}/{word}/entries => /word.json/cat/entries + def interpreted_path + p = self.path.dup + + # Stick a .{format} placeholder into the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words.{format}/blah + if Swagger.configuration.inject_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = p.sub(/^(\/?\w+)/, "\\1.#{format}") + end + end + + # Stick a .{format} placeholder on the end of the path if there isn't + # one already or an actual format like json or xml + # e.g. /words/blah => /words/blah.{format} + if Swagger.configuration.force_ending_format + unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } + p = "#{p}.#{format}" + end + end + + p = p.sub("{format}", self.format.to_s) + + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') + end + + # Massage the request body into a state of readiness + # If body is a hash, camelize all keys then convert to a json string + def body=(value) + if value.is_a?(Hash) + value = value.inject({}) do |memo, (k,v)| + memo[k.to_s.camelize(:lower).to_sym] = v + memo + end + end + @body = value + end + + # If body is an object, JSONify it before making the actual request. + # For form parameters, remove empty value + def outgoing_body + # http form + if @body.nil? && @form_params && !@form_params.empty? + data = form_params.dup + data.each do |key, value| + data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter + end + data + else # http body is JSON + @body.is_a?(String) ? @body : @body.to_json + end + end + + # Construct a query string from the query-string-type params + def query_string + # Iterate over all params, + # .. removing the ones that are part of the path itself. + # .. stringifying values so Addressable doesn't blow up. + query_values = {} + self.params.each_pair do |key, value| + next if self.path.include? "{#{key}}" # skip path params + next if value.blank? && value.class != FalseClass # skip empties + if Swagger.configuration.camelize_params + key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param + end + query_values[key] = value.to_s + end + + # We don't want to end up with '?' as our query string + # if there aren't really any params + return "" if query_values.blank? + + # Addressable requires query_values to be set after initialization.. + qs = Addressable::URI.new + qs.query_values = query_values + qs.to_s + end + + def make + #TODO use configuration setting to determine if debugging + #logger = Logger.new STDOUT + #logger.debug self.url + response = case self.http_method.to_sym + when :get,:GET + Typhoeus::Request.get( + self.url, + :headers => self.headers.stringify_keys, + ) + + when :post,:POST + Typhoeus::Request.post( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :patch,:PATCH + Typhoeus::Request.patch( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :put,:PUT + Typhoeus::Request.put( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + + when :delete,:DELETE + Typhoeus::Request.delete( + self.url, + :body => self.outgoing_body, + :headers => self.headers.stringify_keys, + ) + end + Response.new(response) + end + + def response + self.make + end + + def response_code_pretty + return unless @response.present? + @response.code.to_s + end + + def response_headers_pretty + return unless @response.present? + # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient + @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus + end + end + end +end diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb new file mode 100644 index 00000000000..b0870d2f220 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb @@ -0,0 +1,70 @@ +module SwaggerClient + module Swagger + class Response + require 'json' + + attr_accessor :raw + + def initialize(raw) + self.raw = raw + + case self.code + when 500..510 then raise(ServerError, self.error_message) + when 299..426 then raise(ClientError, self.error_message) + end + end + + def code + raw.code + end + + # Account for error messages that take different forms... + def error_message + body['message'] + rescue + body + end + + # If body is JSON, parse it + # Otherwise return raw string + def body + JSON.parse raw.body + rescue + raw.body + end + + # `headers_hash` is a Typhoeus-specific extension of Hash, + # so simplify it back into a regular old Hash. + def headers + h = {} + raw.headers_hash.each {|k,v| h[k] = v } + h + end + + # Extract the response format from the header hash + # e.g. {'Content-Type' => 'application/json'} + def format + headers['Content-Type'].split("/").last.downcase + end + + def json? + format == 'json' + end + + def xml? + format == 'xml' + end + + def pretty_body + return unless body.present? + case format + when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') + end + end + + def pretty_headers + JSON.pretty_generate(headers).gsub(/\n/, '
') + end + end + end +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb new file mode 100644 index 00000000000..c6e8d5aee53 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb @@ -0,0 +1,5 @@ +module SwaggerClient + module Swagger + VERSION = "1.0.0" + end +end diff --git a/samples/client/petstore/ruby/lib/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger/configuration.rb deleted file mode 100644 index 2a3728483f5..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/configuration.rb +++ /dev/null @@ -1,22 +0,0 @@ -module Swagger - - class Configuration - require 'swagger/version' - - attr_accessor :format, :api_key, :username, :password, :auth_token, :scheme, :host, :base_path, :user_agent, :logger, :inject_format, :force_ending_format, :camelize_params, :user_agent - - # Defaults go in here.. - def initialize - @format = 'json' - @scheme = 'http' - @host = 'petstore.swagger.io' - @base_path = '/v2' - @user_agent = "ruby-swagger-#{Swagger::VERSION}" - @inject_format = false - @force_ending_format = false - @camelize_params = true - end - - end - -end diff --git a/samples/client/petstore/ruby/lib/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger/version.rb deleted file mode 100644 index 39357c0ed6d..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/version.rb +++ /dev/null @@ -1,4 +0,0 @@ -module Swagger - VERSION = "4.06.08" -end - diff --git a/samples/client/petstore/ruby/swagger-client.gemspec b/samples/client/petstore/ruby/swagger-client.gemspec index bbff5f95f6b..11434631fe9 100644 --- a/samples/client/petstore/ruby/swagger-client.gemspec +++ b/samples/client/petstore/ruby/swagger-client.gemspec @@ -1,10 +1,10 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger/version" +require "swagger-client/swagger/version" Gem::Specification.new do |s| s.name = "swagger-client" - s.version = Swagger::VERSION + s.version = SwaggerClient::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] s.email = ["zeke@wordnik.com", "tony@wordnik.com"] @@ -12,8 +12,6 @@ Gem::Specification.new do |s| s.summary = %q{A ruby wrapper for the swagger APIs} s.description = %q{This gem maps to a swagger API} - s.rubyforge_project = "swagger-client" - s.add_dependency 'typhoeus', '>=0.2.1' s.add_dependency 'addressable', '>=2.2.4' s.add_dependency 'json', '>=1.4.6' From 194e9e6f055efc914ec3d9f68c75f8cf2f16f201 Mon Sep 17 00:00:00 2001 From: xhh Date: Sun, 19 Apr 2015 00:42:55 +0800 Subject: [PATCH 47/75] Make petstore tests pass --- samples/client/petstore/ruby/spec/pet_spec.rb | 22 ++++----- .../client/petstore/ruby/spec/request_spec.rb | 48 +++++++++---------- .../petstore/ruby/spec/response_spec.rb | 6 +-- .../client/petstore/ruby/spec/spec_helper.rb | 12 ++--- .../client/petstore/ruby/spec/store_spec.rb | 2 +- .../client/petstore/ruby/spec/swagger_spec.rb | 28 +++++------ 6 files changed, 59 insertions(+), 59 deletions(-) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index 90df1cd821b..fce80afb3bc 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -37,8 +37,8 @@ describe "Pet" do end it "should fetch a pet object" do - pet = PetApi.get_pet_by_id(10002) - pet.should be_a(Pet) + pet = SwaggerClient::PetApi.get_pet_by_id(10002) + pet.should be_a(SwaggerClient::Pet) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" pet.tags[0].name.should == "tag test" @@ -46,17 +46,17 @@ describe "Pet" do end it "should find pets by status" do - pets = PetApi.find_pets_by_status(:status => 'available') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available') pets.length.should >= 3 end it "should not find a pet with invalid status" do - pets = PetApi.find_pets_by_status(:status => 'invalid-status') + pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 end it "should find a pet by status" do - pets = PetApi.find_pets_by_status(:status => "available,sold") + pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold") pets.map {|pet| if(pet.status != 'available' && pet.status != 'sold') raise "pet status wasn't right" @@ -65,19 +65,19 @@ describe "Pet" do end it "should update a pet" do - pet = Pet.new({'id' => 10002, 'status' => 'sold'}) - PetApi.add_pet(:body => pet) + pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'}) + SwaggerClient::PetApi.add_pet(:body => pet) - fetched = PetApi.get_pet_by_id(10002) + fetched = SwaggerClient::PetApi.get_pet_by_id(10002) fetched.id.should == 10002 fetched.status.should == 'sold' end it "should create a pet" do - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") - PetApi.add_pet(:body => pet) + pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") + SwaggerClient::PetApi.add_pet(:body => pet) - pet = PetApi.get_pet_by_id(10002) + pet = SwaggerClient::PetApi.get_pet_by_id(10002) pet.id.should == 10002 pet.name.should == "RUBY UNIT TESTING" end diff --git a/samples/client/petstore/ruby/spec/request_spec.rb b/samples/client/petstore/ruby/spec/request_spec.rb index 61389eddc9c..8856a0cf315 100644 --- a/samples/client/petstore/ruby/spec/request_spec.rb +++ b/samples/client/petstore/ruby/spec/request_spec.rb @@ -1,9 +1,9 @@ require 'spec_helper' -describe Swagger::Request do +describe SwaggerClient::Swagger::Request do before(:each) do - Swagger.configure do |config| + SwaggerClient::Swagger.configure do |config| inject_format = true config.api_key = 'special-key' config.host = 'petstore.swagger.io' @@ -15,7 +15,7 @@ describe Swagger::Request do @default_params = { :params => {:foo => "1", :bar => "2"} } - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params) + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params) end describe "initialization" do @@ -24,7 +24,7 @@ describe Swagger::Request do end it "allows params to be nil" do - @request = Swagger::Request.new(@default_http_method, @default_path, :params => nil) + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, :params => nil) @request.query_string.should == "" end @@ -59,7 +59,7 @@ describe Swagger::Request do describe "body" do it "camelCases parameters" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :body => { :bad_dog => 'bud', :goodDog => "dud" @@ -73,7 +73,7 @@ describe Swagger::Request do describe "path" do it "accounts for a total absence of format in the path string" do - @request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -82,7 +82,7 @@ describe Swagger::Request do end it "does string substitution (format) on path params" do - @request = Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/cat/entries", @default_params.merge({ :format => "xml", :params => { } @@ -91,7 +91,7 @@ describe Swagger::Request do end it "leaves path-bound params out of the query string" do - @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ :params => { :word => "cat", :limit => 20 @@ -101,7 +101,7 @@ describe Swagger::Request do end it "returns a question-mark free (blank) query string if no query params are present" do - @request = Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "/word.{format}/{word}/entries", @default_params.merge({ :params => { :word => "cat", } @@ -110,7 +110,7 @@ describe Swagger::Request do end it "removes blank params" do - @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({ :params => { :word => "dog", :limit => "", @@ -121,7 +121,7 @@ describe Swagger::Request do end it "URI encodes the path" do - @request = Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "word.{format}/bill gates/definitions", @default_params.merge({ :params => { :word => "bill gates" } @@ -130,7 +130,7 @@ describe Swagger::Request do end it "converts numeric params to strings" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :params => { :limit => 100 } @@ -142,7 +142,7 @@ describe Swagger::Request do end it "camelCases parameters" do - @request = Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(@default_http_method, @default_path, @default_params.merge({ :params => { :bad_dog => 'bud', :goodDog => "dud" @@ -153,7 +153,7 @@ describe Swagger::Request do it "converts boolean values to their string representation" do params = {:stringy => "fish", :truthy => true, :falsey => false} - @request = Swagger::Request.new(:get, 'fakeMethod', :params => params) + @request = SwaggerClient::Swagger::Request.new(:get, 'fakeMethod', :params => params) @request.query_string.should == "?falsey=false&stringy=fish&truthy=true" end @@ -162,12 +162,12 @@ describe Swagger::Request do describe "API key" do it "is inferred from the Swagger base configuration by default" do - Swagger.configure {|c| c.api_key = "xyz" } - Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" + SwaggerClient::Swagger.configure {|c| c.api_key = "xyz" } + SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "xyz" end it "can be obfuscated for public display" do - @request = Swagger::Request.new(:get, "words/fancy", @default_params.merge({ + @request = SwaggerClient::Swagger::Request.new(:get, "words/fancy", @default_params.merge({ :params => { :word => "dog", :api_key => "123456" @@ -179,21 +179,21 @@ describe Swagger::Request do end it "allows a key in the params to override the configuration-level key, even if it's blank" do - Swagger.configure {|c| c.api_key = "abc" } - @request_with_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) + SwaggerClient::Swagger.configure {|c| c.api_key = "abc" } + @request_with_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => "jkl"}) @request_with_key.headers[:api_key].should be_nil @request_with_key.params[:api_key].should == "jkl" - @request_without_key = Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) + @request_without_key = SwaggerClient::Swagger::Request.new(:get, "word/json", :params => {:api_key => nil}) @request_without_key.headers[:api_key].should be_nil @request_without_key.params[:api_key].should be_nil end it "allows a key in the headers to override the configuration-level key, even if it's blank" do - Swagger.configure {|c| c.api_key = "hij" } - Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" - Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" - Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil + SwaggerClient::Swagger.configure {|c| c.api_key = "hij" } + SwaggerClient::Swagger::Request.new(:get, "word/json").headers[:api_key].should == "hij" + SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => "jkl"}).headers[:api_key].should == "jkl" + SwaggerClient::Swagger::Request.new(:get, "word/json", :headers => {:api_key => nil}).headers[:api_key].should be_nil end end diff --git a/samples/client/petstore/ruby/spec/response_spec.rb b/samples/client/petstore/ruby/spec/response_spec.rb index f29a0d2a62f..528b67e1fa7 100644 --- a/samples/client/petstore/ruby/spec/response_spec.rb +++ b/samples/client/petstore/ruby/spec/response_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -describe Swagger::Response do +describe SwaggerClient::Swagger::Response do before do configure_swagger @@ -13,7 +13,7 @@ describe Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002") end - @response = Swagger::Response.new(@raw) + @response = SwaggerClient::Swagger::Response.new(@raw) end describe "initialization" do @@ -43,7 +43,7 @@ describe Swagger::Response do @raw = Typhoeus::Request.get("http://petstore.swagger.io/v2/pet/10002", :headers => {'Accept'=> "application/xml"}) end - @response = Swagger::Response.new(@raw) + @response = SwaggerClient::Swagger::Response.new(@raw) @response.format.should == 'xml' @response.xml?.should == true end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index d247ba5cbec..5e9b30c9a2e 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -37,7 +37,7 @@ end #end def configure_swagger - Swagger.configure do |config| + SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' config.host = 'petstore.swagger.io' config.base_path = '/v2' @@ -47,7 +47,7 @@ end # always delete and then re-create the pet object with 10002 def prepare_pet # remove the pet - PetApi.delete_pet(10002) + SwaggerClient::PetApi.delete_pet(10002) # recreate the pet category = Category.new('id' => 20002, 'name' => 'category test') tag = Tag.new('id' => 30002, 'name' => 'tag test') @@ -57,19 +57,19 @@ def prepare_pet PetApi.add_pet(:'body'=> pet) end -# always delete and then re-create the store order +# always delete and then re-create the store order def prepare_store - order = Order.new("id" => 10002, + order = SwaggerClient::Order.new("id" => 10002, "petId" => 10002, "quantity" => 789, "shipDate" => "2015-04-06T23:42:01.678Z", "status" => "placed", "complete" => false) - StoreApi.place_order(:body => order) + SwaggerClient::StoreApi.place_order(:body => order) end configure_swagger -# A random string to tack onto stuff to ensure we're not seeing +# A random string to tack onto stuff to ensure we're not seeing # data from a previous test run RAND = ("a".."z").to_a.sample(8).join diff --git a/samples/client/petstore/ruby/spec/store_spec.rb b/samples/client/petstore/ruby/spec/store_spec.rb index a1e2bd3193f..1b37400bc5c 100644 --- a/samples/client/petstore/ruby/spec/store_spec.rb +++ b/samples/client/petstore/ruby/spec/store_spec.rb @@ -7,7 +7,7 @@ describe "Store" do end it "should fetch an order" do - item = StoreApi.get_order_by_id(10002) + item = SwaggerClient::StoreApi.get_order_by_id(10002) item.id.should == 10002 end end diff --git a/samples/client/petstore/ruby/spec/swagger_spec.rb b/samples/client/petstore/ruby/spec/swagger_spec.rb index 4aedc85382c..38b4a850ae9 100644 --- a/samples/client/petstore/ruby/spec/swagger_spec.rb +++ b/samples/client/petstore/ruby/spec/swagger_spec.rb @@ -1,7 +1,7 @@ # require 'spec_helper' require File.dirname(__FILE__) + '/spec_helper' -describe Swagger do +describe SwaggerClient::Swagger do before(:each) do configure_swagger @@ -16,35 +16,35 @@ describe Swagger do context 'host' do it 'removes http from host' do - Swagger.configure {|c| c.host = 'http://example.com' } - Swagger.configuration.host.should == 'example.com' + SwaggerClient::Swagger.configure {|c| c.host = 'http://example.com' } + SwaggerClient::Swagger.configuration.host.should == 'example.com' end it 'removes https from host' do - Swagger.configure {|c| c.host = 'https://wookiee.com' } - Swagger.configuration.host.should == 'wookiee.com' + SwaggerClient::Swagger.configure {|c| c.host = 'https://wookiee.com' } + SwaggerClient::Swagger.configuration.host.should == 'wookiee.com' end it 'removes trailing path from host' do - Swagger.configure {|c| c.host = 'hobo.com/v4' } - Swagger.configuration.host.should == 'hobo.com' + SwaggerClient::Swagger.configure {|c| c.host = 'hobo.com/v4' } + SwaggerClient::Swagger.configuration.host.should == 'hobo.com' end end context 'base_path' do it "prepends a slash to base_path" do - Swagger.configure {|c| c.base_path = 'v4/dog' } - Swagger.configuration.base_path.should == '/v4/dog' + SwaggerClient::Swagger.configure {|c| c.base_path = 'v4/dog' } + SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog' end it "doesn't prepend a slash if one is already there" do - Swagger.configure {|c| c.base_path = '/v4/dog' } - Swagger.configuration.base_path.should == '/v4/dog' + SwaggerClient::Swagger.configure {|c| c.base_path = '/v4/dog' } + SwaggerClient::Swagger.configuration.base_path.should == '/v4/dog' end it "ends up as a blank string if nil" do - Swagger.configure {|c| c.base_path = nil } - Swagger.configuration.base_path.should == '' + SwaggerClient::Swagger.configure {|c| c.base_path = nil } + SwaggerClient::Swagger.configuration.base_path.should == '' end end @@ -53,4 +53,4 @@ describe Swagger do end -end \ No newline at end of file +end From 87904e8b69b471bd51ee4537dce72ef4d98587f5 Mon Sep 17 00:00:00 2001 From: xhh Date: Fri, 17 Apr 2015 09:33:49 +0800 Subject: [PATCH 48/75] Set version dynamically in ruby codegen Conflicts: modules/swagger-codegen/src/main/resources/ruby/swagger/version.mustache samples/client/petstore/ruby/lib/swagger/version.rb --- samples/client/petstore/ruby/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 29a7ce844ce..86b17e06236 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -11,14 +11,14 @@ gem build swagger-client.gemspec Then you can either install the gem: ```shell -gem install ./swagger-client-4.06.08.gem +gem install ./swagger-client-1.0.0.gem ``` or publish the gem to a gem server like [RubyGems](https://rubygems.org/). Finally add this to your Gemfile: - gem 'swagger-client', '~> 4.06.08' + gem 'swagger-client', '~> 1.0.0' ### Host as a git repository From b140f1f152425d2f9799888a19c8e49c9878cf4e Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 20 Apr 2015 10:12:02 +0800 Subject: [PATCH 49/75] Fix example code in README.md of Ruby petstore sample --- samples/client/petstore/ruby/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 86b17e06236..a05c91317b6 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -42,7 +42,7 @@ ruby -Ilib script.rb ```ruby require 'swagger-client' -Swagger.configure do |config| +SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' config.host = 'petstore.swagger.io' config.base_path = '/v2' @@ -52,6 +52,6 @@ end ## Getting Started ```ruby -pet = PetApi.getPetById(5) +pet = SwaggerClient::PetApi.get_pet_by_id(5) puts pet.to_body ``` From fcf1327c1f5b04024224e1c4bba6a8e051ba6ac2 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 20 Apr 2015 10:46:55 +0800 Subject: [PATCH 50/75] Rename swagger-client to swagger_client according to guides from rubygems: http://guides.rubygems.org/name-your-gem/ --- .../codegen/languages/RubyClientCodegen.java | 8 +++---- ...stache => swagger_client.gemspec.mustache} | 0 ...lient.mustache => swagger_client.mustache} | 0 samples/client/petstore/ruby/Gemfile.lock | 4 ++-- samples/client/petstore/ruby/README.md | 10 ++++---- .../petstore/ruby/lib/swagger-client.rb | 24 ------------------- .../petstore/ruby/lib/swagger_client.rb | 24 +++++++++++++++++++ .../api/pet_api.rb | 0 .../api/store_api.rb | 0 .../api/user_api.rb | 0 .../models/category.rb | 0 .../models/order.rb | 0 .../models/pet.rb | 0 .../models/tag.rb | 0 .../models/user.rb | 0 .../monkey.rb | 0 .../swagger.rb | 0 .../swagger/configuration.rb | 0 .../swagger/request.rb | 0 .../swagger/response.rb | 0 .../swagger/version.rb | 0 .../client/petstore/ruby/spec/spec_helper.rb | 2 +- ...-client.gemspec => swagger_client.gemspec} | 4 ++-- 23 files changed, 38 insertions(+), 38 deletions(-) rename modules/swagger-codegen/src/main/resources/ruby/{swagger-client.gemspec.mustache => swagger_client.gemspec.mustache} (100%) rename modules/swagger-codegen/src/main/resources/ruby/{swagger-client.mustache => swagger_client.mustache} (100%) delete mode 100644 samples/client/petstore/ruby/lib/swagger-client.rb create mode 100644 samples/client/petstore/ruby/lib/swagger_client.rb rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/api/pet_api.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/api/store_api.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/api/user_api.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/category.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/order.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/pet.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/tag.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/models/user.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/monkey.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/configuration.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/request.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/response.rb (100%) rename samples/client/petstore/ruby/lib/{swagger-client => swagger_client}/swagger/version.rb (100%) rename samples/client/petstore/ruby/{swagger-client.gemspec => swagger_client.gemspec} (93%) 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 5fb8ee5eb8f..939c0eb0e0a 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 @@ -8,7 +8,7 @@ import java.util.*; import java.io.File; public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { - protected String gemName = "swagger-client"; + protected String gemName = "swagger_client"; protected String moduleName = null; protected String libFolder = "lib"; @@ -25,7 +25,7 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { } /** - * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger-client". + * Generate Ruby module name from the gem name, e.g. use "SwaggerClient" for "swagger_client". */ public String generateModuleName() { return camelize(gemName.replaceAll("[^\\w]+", "_")); @@ -72,8 +72,8 @@ public class RubyClientCodegen extends DefaultCodegen implements CodegenConfig { String baseFolder = "lib/" + gemName; String swaggerFolder = baseFolder + "/swagger"; String modelFolder = baseFolder + "/models"; - supportingFiles.add(new SupportingFile("swagger-client.gemspec.mustache", "", gemName + ".gemspec")); - supportingFiles.add(new SupportingFile("swagger-client.mustache", "lib", gemName + ".rb")); + supportingFiles.add(new SupportingFile("swagger_client.gemspec.mustache", "", gemName + ".gemspec")); + supportingFiles.add(new SupportingFile("swagger_client.mustache", "lib", gemName + ".rb")); supportingFiles.add(new SupportingFile("monkey.mustache", baseFolder, "monkey.rb")); supportingFiles.add(new SupportingFile("swagger.mustache", baseFolder, "swagger.rb")); supportingFiles.add(new SupportingFile("swagger/request.mustache", swaggerFolder, "request.rb")); diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger-client.gemspec.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache similarity index 100% rename from modules/swagger-codegen/src/main/resources/ruby/swagger-client.mustache rename to modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index 028579303ec..c2f0a21b3fc 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -1,7 +1,7 @@ PATH remote: . specs: - swagger-client (1.0.0) + swagger_client (1.0.0) addressable (>= 2.2.4) json (>= 1.4.6) typhoeus (>= 0.2.1) @@ -56,6 +56,6 @@ DEPENDENCIES autotest-growl autotest-rails-pure rspec (>= 2.5.0) - swagger-client! + swagger_client! vcr (>= 1.5.1) webmock (>= 1.6.2) diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index a05c91317b6..2a15c1661cc 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -5,20 +5,20 @@ You can build the generated client into a gem: ```shell -gem build swagger-client.gemspec +gem build swagger_client.gemspec ``` Then you can either install the gem: ```shell -gem install ./swagger-client-1.0.0.gem +gem install ./swagger_client-1.0.0.gem ``` or publish the gem to a gem server like [RubyGems](https://rubygems.org/). Finally add this to your Gemfile: - gem 'swagger-client', '~> 1.0.0' + gem 'swagger_client', '~> 1.0.0' ### Host as a git repository @@ -27,7 +27,7 @@ https://github.com/xhh/swagger-petstore-ruby Then you can reference it in Gemfile: - gem 'swagger-client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' + gem 'swagger_client', :git => 'https://github.com/xhh/swagger-petstore-ruby.git' ### Use without installation @@ -40,7 +40,7 @@ ruby -Ilib script.rb ## Configuration ```ruby -require 'swagger-client' +require 'swagger_client' SwaggerClient::Swagger.configure do |config| config.api_key = 'special-key' diff --git a/samples/client/petstore/ruby/lib/swagger-client.rb b/samples/client/petstore/ruby/lib/swagger-client.rb deleted file mode 100644 index 05867456a68..00000000000 --- a/samples/client/petstore/ruby/lib/swagger-client.rb +++ /dev/null @@ -1,24 +0,0 @@ -# Swagger common files -require 'swagger-client/monkey' -require 'swagger-client/swagger' -require 'swagger-client/swagger/configuration' -require 'swagger-client/swagger/request' -require 'swagger-client/swagger/response' -require 'swagger-client/swagger/version' - -# Models -require 'swagger-client/models/user' -require 'swagger-client/models/category' -require 'swagger-client/models/pet' -require 'swagger-client/models/tag' -require 'swagger-client/models/order' - -# APIs -require 'swagger-client/api/user_api' -require 'swagger-client/api/pet_api' -require 'swagger-client/api/store_api' - -module SwaggerClient - # Initialize the default configuration - Swagger.configuration ||= Swagger::Configuration.new -end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb new file mode 100644 index 00000000000..33922da4c73 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -0,0 +1,24 @@ +# Swagger common files +require 'swagger_client/monkey' +require 'swagger_client/swagger' +require 'swagger_client/swagger/configuration' +require 'swagger_client/swagger/request' +require 'swagger_client/swagger/response' +require 'swagger_client/swagger/version' + +# Models +require 'swagger_client/models/user' +require 'swagger_client/models/category' +require 'swagger_client/models/pet' +require 'swagger_client/models/tag' +require 'swagger_client/models/order' + +# APIs +require 'swagger_client/api/user_api' +require 'swagger_client/api/pet_api' +require 'swagger_client/api/store_api' + +module SwaggerClient + # Initialize the default configuration + Swagger.configuration ||= Swagger::Configuration.new +end \ No newline at end of file diff --git a/samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/api/pet_api.rb rename to samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/api/store_api.rb rename to samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/api/user_api.rb rename to samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/category.rb b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/category.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/category.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/order.rb b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/order.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/order.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/pet.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/pet.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/tag.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/tag.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/models/user.rb b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/models/user.rb rename to samples/client/petstore/ruby/lib/swagger_client/models/user.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/monkey.rb b/samples/client/petstore/ruby/lib/swagger_client/monkey.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/monkey.rb rename to samples/client/petstore/ruby/lib/swagger_client/monkey.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/configuration.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/configuration.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/request.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/response.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb diff --git a/samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb similarity index 100% rename from samples/client/petstore/ruby/lib/swagger-client/swagger/version.rb rename to samples/client/petstore/ruby/lib/swagger_client/swagger/version.rb diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 5e9b30c9a2e..12d51679fc8 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -1,6 +1,6 @@ require 'rubygems' require 'bundler/setup' -require 'swagger-client' +require 'swagger_client' require 'vcr' require 'typhoeus' require 'json' diff --git a/samples/client/petstore/ruby/swagger-client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec similarity index 93% rename from samples/client/petstore/ruby/swagger-client.gemspec rename to samples/client/petstore/ruby/swagger_client.gemspec index 11434631fe9..dc3cd8350bd 100644 --- a/samples/client/petstore/ruby/swagger-client.gemspec +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -1,9 +1,9 @@ # -*- encoding: utf-8 -*- $:.push File.expand_path("../lib", __FILE__) -require "swagger-client/swagger/version" +require "swagger_client/swagger/version" Gem::Specification.new do |s| - s.name = "swagger-client" + s.name = "swagger_client" s.version = SwaggerClient::Swagger::VERSION s.platform = Gem::Platform::RUBY s.authors = ["Zeke Sikelianos", "Tony Tam"] From f766614b4d67f955e6a01ce5332a4140f02bfbd8 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:42:38 +0800 Subject: [PATCH 51/75] Clean old files generated --- samples/client/petstore/ruby/lib/pet_api.rb | 313 ------------------ samples/client/petstore/ruby/lib/store_api.rb | 154 --------- samples/client/petstore/ruby/lib/swagger.rb | 86 ----- .../petstore/ruby/lib/swagger/request.rb | 263 --------------- .../petstore/ruby/lib/swagger/response.rb | 70 ---- samples/client/petstore/ruby/lib/user_api.rb | 300 ----------------- .../petstore/ruby/models/base_object.rb | 83 ----- .../client/petstore/ruby/models/category.rb | 45 --- samples/client/petstore/ruby/models/order.rb | 77 ----- samples/client/petstore/ruby/models/pet.rb | 81 ----- samples/client/petstore/ruby/models/tag.rb | 45 --- samples/client/petstore/ruby/models/user.rb | 93 ------ 12 files changed, 1610 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/swagger.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/request.rb delete mode 100644 samples/client/petstore/ruby/lib/swagger/response.rb delete mode 100644 samples/client/petstore/ruby/lib/user_api.rb delete mode 100644 samples/client/petstore/ruby/models/base_object.rb delete mode 100644 samples/client/petstore/ruby/models/category.rb delete mode 100644 samples/client/petstore/ruby/models/order.rb delete mode 100644 samples/client/petstore/ruby/models/pet.rb delete mode 100644 samples/client/petstore/ruby/models/tag.rb delete mode 100644 samples/client/petstore/ruby/models/user.rb 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 b15198588aa..00000000000 --- a/samples/client/petstore/ruby/lib/pet_api.rb +++ /dev/null @@ -1,313 +0,0 @@ -require "uri" - -class PetApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Update an existing pet - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void - def self.update_pet(opts = {}) - - - # resource path - path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Add a new pet to the store - # - # @param [Hash] opts the optional parameters - # @option opts [Pet] :body Pet object that needs to be added to the store - # @return void - def self.add_pet(opts = {}) - - - # resource path - path = "/pet".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Finds Pets by status - # Multiple status values can be provided with comma seperated strings - # @param [Hash] opts the optional parameters - # @option opts [array[string]] :status Status values that need to be considered for filter - # @return array[Pet] - def self.find_pets_by_status(opts = {}) - - - # resource path - path = "/pet/findByStatus".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'status'] = opts[:'status'] if opts[:'status'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } - end - - # Finds Pets by tags - # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. - # @param [Hash] opts the optional parameters - # @option opts [array[string]] :tags Tags to filter by - # @return array[Pet] - def self.find_pets_by_tags(opts = {}) - - - # resource path - path = "/pet/findByTags".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'tags'] = opts[:'tags'] if opts[:'tags'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } - end - - # Find pet by ID - # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions - # @param pet_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return Pet - def self.get_pet_by_id(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil? - - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - obj = Pet.new() and obj.build_from_hash(response) - end - - # Updates a pet in the store with form data - # - # @param pet_id ID of pet that needs to be updated - # @param [Hash] opts the optional parameters - # @option opts [string] :name Updated name of the pet - # @option opts [string] :status Updated status of the pet - # @return void - def self.update_pet_with_form(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil? - - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['application/x-www-form-urlencoded', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - form_params["name"] = opts[:'name'] if opts[:'name'] - form_params["status"] = opts[:'status'] if opts[:'status'] - - # http body (model) - post_body = nil - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Deletes a pet - # - # @param pet_id Pet id to delete - # @param [Hash] opts the optional parameters - # @option opts [string] :api_key - # @return void - def self.delete_pet(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? - - - # resource path - path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # uploads an image - # - # @param pet_id ID of pet to update - # @param [Hash] opts the optional parameters - # @option opts [string] :additional_metadata Additional data to pass to server - # @option opts [file] :file file to upload - # @return void - def self.upload_file(pet_id, opts = {}) - - # verify the required parameter 'pet_id' is set - raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil? - - - # resource path - path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = ['multipart/form-data', ] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - form_params["additionalMetadata"] = opts[:'additional_metadata'] if opts[:'additional_metadata'] - form_params["file"] = opts[:'file'] if opts[:'file'] - - # http body (model) - post_body = nil - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - 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 c6d670cd8c0..00000000000 --- a/samples/client/petstore/ruby/lib/store_api.rb +++ /dev/null @@ -1,154 +0,0 @@ -require "uri" - -class StoreApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Returns pet inventories by status - # Returns a map of status codes to quantities - # @param [Hash] opts the optional parameters - # @return map[string,int] - def self.get_inventory(opts = {}) - - - # resource path - path = "/store/inventory".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| obj = map.new() and obj.build_from_hash(response) } - end - - # Place an order for a pet - # - # @param [Hash] opts the optional parameters - # @option opts [Order] :body order placed for purchasing the pet - # @return Order - def self.place_order(opts = {}) - - - # resource path - path = "/store/order".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - obj = Order.new() and obj.build_from_hash(response) - end - - # Find purchase order by ID - # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions - # @param order_id ID of pet that needs to be fetched - # @param [Hash] opts the optional parameters - # @return Order - def self.get_order_by_id(order_id, opts = {}) - - # verify the required parameter 'order_id' is set - raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? - - - # resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - obj = Order.new() and obj.build_from_hash(response) - end - - # Delete purchase order by ID - # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors - # @param order_id ID of the order that needs to be deleted - # @param [Hash] opts the optional parameters - # @return void - def self.delete_order(order_id, opts = {}) - - # verify the required parameter 'order_id' is set - raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil? - - - # resource path - path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/lib/swagger.rb b/samples/client/petstore/ruby/lib/swagger.rb deleted file mode 100644 index f393330b148..00000000000 --- a/samples/client/petstore/ruby/lib/swagger.rb +++ /dev/null @@ -1,86 +0,0 @@ -require 'monkey' -require 'swagger/configuration' -require 'swagger/request' -require 'swagger/response' -require 'swagger/version' -require 'logger' -require 'json' - -module Swagger - - @configuration = Configuration.new - - class << self - attr_accessor :logger - - # A Swagger configuration object. Must act like a hash and return sensible - # values for all Swagger configuration options. See Swagger::Configuration. - attr_accessor :configuration - - attr_accessor :resources - - # Call this method to modify defaults in your initializers. - # - # @example - # Swagger.configure do |config| - # config.api_key = '1234567890abcdef' # required - # config.username = 'wordlover' # optional, but needed for user-related functions - # config.password = 'i<3words' # optional, but needed for user-related functions - # config.format = 'json' # optional, defaults to 'json' - # end - # - def configure - yield(configuration) if block_given? - - # Configure logger. Default to use Rails - self.logger ||= configuration.logger || (defined?(Rails) ? Rails.logger : Logger.new(STDOUT)) - - # remove :// from scheme - configuration.scheme.sub!(/:\/\//, '') - - # remove http(s):// and anything after a slash - configuration.host.sub!(/https?:\/\//, '') - configuration.host = configuration.host.split('/').first - - # Add leading and trailing slashes to base_path - configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') - configuration.base_path = "" if configuration.base_path == "/" - end - - def authenticated? - Swagger.configuration.auth_token.present? - end - - def de_authenticate - Swagger.configuration.auth_token = nil - end - - def authenticate - return if Swagger.authenticated? - - if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? - raise ClientError, "Username and password are required to authenticate." - end - - request = Swagger::Request.new( - :get, - "account/authenticate/{username}", - :params => { - :username => Swagger.configuration.username, - :password => Swagger.configuration.password - } - ) - - response_body = request.response.body - Swagger.configuration.auth_token = response_body['token'] - end - - end - -end - -class ServerError < StandardError -end - -class ClientError < StandardError -end diff --git a/samples/client/petstore/ruby/lib/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger/request.rb deleted file mode 100644 index 4ec071b93d5..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/request.rb +++ /dev/null @@ -1,263 +0,0 @@ -module Swagger - - class Request - require 'uri' - require 'addressable/uri' - require 'typhoeus' - require "swagger/version" - - attr_accessor :host, :path, :format, :params, :body, :http_method, :headers, :form_params - - - # All requests must have an HTTP method and a path - # Optionals parameters are :params, :headers, :body, :format, :host - # - def initialize(http_method, path, attributes={}) - attributes[:format] ||= Swagger.configuration.format - attributes[:params] ||= {} - - # Set default headers - default_headers = { - 'Content-Type' => "application/#{attributes[:format].downcase}", - :api_key => Swagger.configuration.api_key, - 'User-Agent' => Swagger.configuration.user_agent - } - - # api_key from headers hash trumps the default, even if its value is blank - if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) - default_headers.delete(:api_key) - end - - # api_key from params hash trumps all others (headers and default_headers) - if attributes[:params].present? && attributes[:params].has_key?(:api_key) - default_headers.delete(:api_key) - attributes[:headers].delete(:api_key) if attributes[:headers].present? - end - - # Merge argument headers into defaults - attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - - # Stick in the auth token if there is one - if Swagger.authenticated? - attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) - end - - self.http_method = http_method.to_sym - self.path = path - attributes.each do |name, value| - send("#{name.to_s.underscore.to_sym}=", value) - end - end - - # Construct a base URL - # - def url(options = {}) - u = Addressable::URI.new( - :scheme => Swagger.configuration.scheme, - :host => Swagger.configuration.host, - :path => self.interpreted_path, - :query => self.query_string.sub(/\?/, '') - ).to_s - - # Drop trailing question mark, if present - u.sub! /\?$/, '' - - # Obfuscate API key? - u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - - u - end - - # Iterate over the params hash, injecting any path values into the path string - # - # e.g. /word.{format}/{word}/entries => /word.json/cat/entries - def interpreted_path - p = self.path.dup - - # Stick a .{format} placeholder into the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words.{format}/blah - if Swagger.configuration.inject_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = p.sub(/^(\/?\w+)/, "\\1.#{format}") - end - end - - # Stick a .{format} placeholder on the end of the path if there isn't - # one already or an actual format like json or xml - # e.g. /words/blah => /words/blah.{format} - if Swagger.configuration.force_ending_format - unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" - end - end - - p = p.sub("{format}", self.format.to_s) - - URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') - end - - # Massage the request body into a state of readiness - # If body is a hash, camelize all keys then convert to a json string - # - def body=(value) - if value.is_a?(Hash) - value = value.inject({}) do |memo, (k,v)| - memo[k.to_s.camelize(:lower).to_sym] = v - memo - end - end - @body = value - end - - # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value - def outgoing_body - # http form - if @body.nil? && @form_params && !@form_params.empty? - data = form_params.dup - data.each do |key, value| - data[key] = value.to_s if value && !value.is_a?(File) # remove emtpy form parameter - end - data - else # http body is JSON - @body.is_a?(String) ? @body : @body.to_json - end - end - - # Construct a query string from the query-string-type params - def query_string - - # Iterate over all params, - # .. removing the ones that are part of the path itself. - # .. stringifying values so Addressable doesn't blow up. - query_values = {} - self.params.each_pair do |key, value| - next if self.path.include? "{#{key}}" # skip path params - next if value.blank? && value.class != FalseClass # skip empties - if Swagger.configuration.camelize_params - key = key.to_s.camelize(:lower).to_sym unless key.to_sym == :api_key # api_key is not a camelCased param - end - query_values[key] = value.to_s - end - - # We don't want to end up with '?' as our query string - # if there aren't really any params - return "" if query_values.blank? - - # Addressable requires query_values to be set after initialization.. - qs = Addressable::URI.new - qs.query_values = query_values - qs.to_s - end - - def make - #TODO use configuration setting to determine if debugging - #logger = Logger.new STDOUT - #logger.debug self.url - response = case self.http_method.to_sym - when :get,:GET - Typhoeus::Request.get( - self.url, - :headers => self.headers.stringify_keys, - ) - - when :post,:POST - Typhoeus::Request.post( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :patch,:PATCH - Typhoeus::Request.patch( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :put,:PUT - Typhoeus::Request.put( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - - when :delete,:DELETE - Typhoeus::Request.delete( - self.url, - :body => self.outgoing_body, - :headers => self.headers.stringify_keys, - ) - end - Response.new(response) - end - - def response - self.make - end - - def response_code_pretty - return unless @response.present? - @response.code.to_s - end - - def response_headers_pretty - return unless @response.present? - # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient - @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus - end - - # return 'Accept' based on an array of accept provided - # @param [Array] header_accept_array Array fo 'Accept' - # @return String Accept (e.g. application/json) - def self.select_header_accept header_accept_array - if header_accept_array.empty? - return - elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # look for json data by default - else - header_accept_array.join(',') - end - end - - # return the content type based on an array of content-type provided - # @param [Array] content_type_array Array fo content-type - # @return String Content-Type (e.g. application/json) - def self.select_header_content_type content_type_array - if content_type_array.empty? - 'application/json' # use application/json by default - elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } - 'application/json' # use application/json if it's included - else - content_type_array[0]; # otherwise, use the first one - end - end - - # static method to convert object (array, hash, object, etc) to JSON string - # @param model object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_http_body model - return if model.nil? - _body = nil - if model.is_a?(Array) - _body = model.map{|m| object_to_hash(m) } - else - _body = object_to_hash(model) - end - _body.to_json - end - - # static method to convert object(non-array) to hash - # @param obj object to be converted into JSON string - # @return string JSON string representation of the object - def self.object_to_hash obj - if obj.respond_to?(:to_hash) - obj.to_hash - else - obj - end - end - - end -end diff --git a/samples/client/petstore/ruby/lib/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger/response.rb deleted file mode 100644 index 641b7ccc756..00000000000 --- a/samples/client/petstore/ruby/lib/swagger/response.rb +++ /dev/null @@ -1,70 +0,0 @@ -module Swagger - - class Response - require 'json' - - attr_accessor :raw - - def initialize(raw) - self.raw = raw - - case self.code - when 500..510 then raise(ServerError, self.error_message) - when 299..426 then raise(ClientError, self.error_message) - end - end - - def code - raw.code - end - - # Account for error messages that take different forms... - def error_message - body['message'] - rescue - body - end - - # If body is JSON, parse it - # Otherwise return raw string - def body - JSON.parse(raw.body, :symbolize_names => true) - rescue - raw.body - end - - # `headers_hash` is a Typhoeus-specific extension of Hash, - # so simplify it back into a regular old Hash. - def headers - h = {} - raw.headers_hash.each {|k,v| h[k] = v } - h - end - - # Extract the response format from the header hash - # e.g. {'Content-Type' => 'application/json'} - def format - headers['Content-Type'].split("/").last.downcase - end - - def json? - format == 'json' - end - - def xml? - format == 'xml' - end - - def pretty_body - return unless body.present? - case format - when 'json' then JSON.pretty_generate(body).gsub(/\n/, '
') - end - end - - def pretty_headers - JSON.pretty_generate(headers).gsub(/\n/, '
') - end - - 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 e7d0644d320..00000000000 --- a/samples/client/petstore/ruby/lib/user_api.rb +++ /dev/null @@ -1,300 +0,0 @@ -require "uri" - -class UserApi - basePath = "http://petstore.swagger.io/v2" - # apiInvoker = APIInvoker - - # Create user - # This can only be done by the logged in user. - # @param [Hash] opts the optional parameters - # @option opts [User] :body Created user object - # @return void - def self.create_user(opts = {}) - - - # resource path - path = "/user".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Creates list of users with given input array - # - # @param [Hash] opts the optional parameters - # @option opts [array[User]] :body List of user object - # @return void - def self.create_users_with_array_input(opts = {}) - - - # resource path - path = "/user/createWithArray".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Creates list of users with given input array - # - # @param [Hash] opts the optional parameters - # @option opts [array[User]] :body List of user object - # @return void - def self.create_users_with_list_input(opts = {}) - - - # resource path - path = "/user/createWithList".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Logs user into the system - # - # @param [Hash] opts the optional parameters - # @option opts [string] :username The user name for login - # @option opts [string] :password The password for login in clear text - # @return string - def self.login_user(opts = {}) - - - # resource path - path = "/user/login".sub('{format}','json') - - # query parameters - query_params = {} - query_params[:'username'] = opts[:'username'] if opts[:'username'] - query_params[:'password'] = opts[:'password'] if opts[:'password'] - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - obj = string.new() and obj.build_from_hash(response) - end - - # Logs out current logged in user session - # - # @param [Hash] opts the optional parameters - # @return void - def self.logout_user(opts = {}) - - - # resource path - path = "/user/logout".sub('{format}','json') - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Get user by user name - # - # @param username The name that needs to be fetched. Use user1 for testing. - # @param [Hash] opts the optional parameters - # @return User - def self.get_user_by_name(username, opts = {}) - - # verify the required parameter 'username' is set - raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? - - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - obj = User.new() and obj.build_from_hash(response) - end - - # Updated user - # This can only be done by the logged in user. - # @param username name that need to be deleted - # @param [Hash] opts the optional parameters - # @option opts [User] :body Updated user object - # @return void - def self.update_user(username, opts = {}) - - # verify the required parameter 'username' is set - raise "Missing the required parameter 'username' when calling update_user" if username.nil? - - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = Swagger::Request.object_to_http_body(opts[:'body']) - - - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end - - # Delete user - # This can only be done by the logged in user. - # @param username The name that needs to be deleted - # @param [Hash] opts the optional parameters - # @return void - def self.delete_user(username, opts = {}) - - # verify the required parameter 'username' is set - raise "Missing the required parameter 'username' when calling delete_user" if username.nil? - - - # resource path - path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) - - # query parameters - query_params = {} - - # header parameters - header_params = {} - - # HTTP header 'Accept' (if needed) - _header_accept = ['application/json', 'application/xml'] - _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result - - # HTTP header 'Content-Type' - _header_content_type = [] - header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) - - # form parameters - form_params = {} - - # http body (model) - post_body = nil - - - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end -end diff --git a/samples/client/petstore/ruby/models/base_object.rb b/samples/client/petstore/ruby/models/base_object.rb deleted file mode 100644 index ecad551c77b..00000000000 --- a/samples/client/petstore/ruby/models/base_object.rb +++ /dev/null @@ -1,83 +0,0 @@ -# base class containing fundamental method such as to_hash, build_from_hash and more -class BaseObject - - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end - - # build the object from hash - def build_from_hash(attributes) - return nil unless attributes.is_a?(Hash) - self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i - if attributes[self.class.attribute_map[key]].is_a?(Array) - self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) - else - #TODO show warning in debug mode - end - elsif !attributes[self.class.attribute_map[key]].nil? - self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end - end - - self - end - - def _deserialize(type, value) - case type.to_sym - when :DateTime - DateTime.parse(value) - when :string - value.to_s - when :int - value.to_i - when :double - value.to_f - when :boolean - if value =~ /^(true|t|yes|y|1)$/i - true - else - false - end - else # model - _model = Object.const_get(type).new - _model.build_from_hash(value) - end - end - - - - # to_body is an alias to to_body (backward compatibility) - def to_hash - hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? - else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value - end - end - end - hash - end - - # Method to output non-array value in the form of hash - # For object, use to_hash. Otherwise, just return the value - def _to_hash(value) - if value.respond_to? :to_hash - value.to_hash - else - value - end - end - -end diff --git a/samples/client/petstore/ruby/models/category.rb b/samples/client/petstore/ruby/models/category.rb deleted file mode 100644 index c1da69482e0..00000000000 --- a/samples/client/petstore/ruby/models/category.rb +++ /dev/null @@ -1,45 +0,0 @@ -require_relative 'base_object' - -# -class Category < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'name' => :'name' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'name' => :'string' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'name'] - @name = attributes[:'name'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/order.rb b/samples/client/petstore/ruby/models/order.rb deleted file mode 100644 index 6347167c860..00000000000 --- a/samples/client/petstore/ruby/models/order.rb +++ /dev/null @@ -1,77 +0,0 @@ -require_relative 'base_object' - -# -class Order < BaseObject - attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'pet_id' => :'petId', - - # - :'quantity' => :'quantity', - - # - :'ship_date' => :'shipDate', - - # Order Status - :'status' => :'status', - - # - :'complete' => :'complete' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'pet_id' => :'int', - :'quantity' => :'int', - :'ship_date' => :'DateTime', - :'status' => :'string', - :'complete' => :'boolean' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'petId'] - @pet_id = attributes[:'petId'] - end - - if attributes[:'quantity'] - @quantity = attributes[:'quantity'] - end - - if attributes[:'shipDate'] - @ship_date = attributes[:'shipDate'] - end - - if attributes[:'status'] - @status = attributes[:'status'] - end - - if attributes[:'complete'] - @complete = attributes[:'complete'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/pet.rb b/samples/client/petstore/ruby/models/pet.rb deleted file mode 100644 index 9accf4d1c81..00000000000 --- a/samples/client/petstore/ruby/models/pet.rb +++ /dev/null @@ -1,81 +0,0 @@ -require_relative 'base_object' - -# -class Pet < BaseObject - attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'category' => :'category', - - # - :'name' => :'name', - - # - :'photo_urls' => :'photoUrls', - - # - :'tags' => :'tags', - - # pet status in the store - :'status' => :'status' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'category' => :'Category', - :'name' => :'string', - :'photo_urls' => :'array[string]', - :'tags' => :'array[Tag]', - :'status' => :'string' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'category'] - @category = attributes[:'category'] - end - - if attributes[:'name'] - @name = attributes[:'name'] - end - - if attributes[:'photoUrls'] - if (value = attributes[:'photoUrls']).is_a?(Array) - @photo_urls = value - end - end - - if attributes[:'tags'] - if (value = attributes[:'tags']).is_a?(Array) - @tags = value - end - end - - if attributes[:'status'] - @status = attributes[:'status'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/tag.rb b/samples/client/petstore/ruby/models/tag.rb deleted file mode 100644 index 7eb332a3218..00000000000 --- a/samples/client/petstore/ruby/models/tag.rb +++ /dev/null @@ -1,45 +0,0 @@ -require_relative 'base_object' - -# -class Tag < BaseObject - attr_accessor :id, :name - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'name' => :'name' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'name' => :'string' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'name'] - @name = attributes[:'name'] - end - - end - -end diff --git a/samples/client/petstore/ruby/models/user.rb b/samples/client/petstore/ruby/models/user.rb deleted file mode 100644 index 20420e1c69b..00000000000 --- a/samples/client/petstore/ruby/models/user.rb +++ /dev/null @@ -1,93 +0,0 @@ -require_relative 'base_object' - -# -class User < BaseObject - attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # attribute mapping from ruby-style variable name to JSON key - def self.attribute_map - { - - # - :'id' => :'id', - - # - :'username' => :'username', - - # - :'first_name' => :'firstName', - - # - :'last_name' => :'lastName', - - # - :'email' => :'email', - - # - :'password' => :'password', - - # - :'phone' => :'phone', - - # User Status - :'user_status' => :'userStatus' - - } - end - - # attribute type - def self.swagger_types - { - :'id' => :'int', - :'username' => :'string', - :'first_name' => :'string', - :'last_name' => :'string', - :'email' => :'string', - :'password' => :'string', - :'phone' => :'string', - :'user_status' => :'int' - - } - end - - def initialize(attributes = {}) - return if !attributes.is_a?(Hash) || attributes.empty? - - # convert string to symbol for hash key - attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} - - - if attributes[:'id'] - @id = attributes[:'id'] - end - - if attributes[:'username'] - @username = attributes[:'username'] - end - - if attributes[:'firstName'] - @first_name = attributes[:'firstName'] - end - - if attributes[:'lastName'] - @last_name = attributes[:'lastName'] - end - - if attributes[:'email'] - @email = attributes[:'email'] - end - - if attributes[:'password'] - @password = attributes[:'password'] - end - - if attributes[:'phone'] - @phone = attributes[:'phone'] - end - - if attributes[:'userStatus'] - @user_status = attributes[:'userStatus'] - end - - end - -end From 6eaaa5cc6962f2ba2d63bb138c7a121d741a49f6 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:44:10 +0800 Subject: [PATCH 52/75] Include base_object model into module structure --- .../main/resources/ruby/base_object.mustache | 146 +++++++++--------- .../src/main/resources/ruby/model.mustache | 2 - .../resources/ruby/swagger_client.mustache | 3 +- 3 files changed, 75 insertions(+), 76 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache index ecad551c77b..c0e563a0bb7 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/base_object.mustache @@ -1,83 +1,83 @@ -# base class containing fundamental method such as to_hash, build_from_hash and more -class BaseObject +module {{moduleName}} + # base class containing fundamental method such as to_hash, build_from_hash and more + class BaseObject - # return the object in the form of hash - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # return the object in the form of hash + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body end - body - end - # build the object from hash - def build_from_hash(attributes) - return nil unless attributes.is_a?(Hash) - self.class.swagger_types.each_pair do |key, type| - if type =~ /^array\[(.*)\]/i - if attributes[self.class.attribute_map[key]].is_a?(Array) - self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + # build the object from hash + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^array\[(.*)\]/i + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + else + #TODO show warning in debug mode + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) else - #TODO show warning in debug mode - end - elsif !attributes[self.class.attribute_map[key]].nil? - self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) - else - # data not found in attributes(hash), not an issue as the data can be optional - end - end - - self - end - - def _deserialize(type, value) - case type.to_sym - when :DateTime - DateTime.parse(value) - when :string - value.to_s - when :int - value.to_i - when :double - value.to_f - when :boolean - if value =~ /^(true|t|yes|y|1)$/i - true - else - false - end - else # model - _model = Object.const_get(type).new - _model.build_from_hash(value) - end - end - - - - # to_body is an alias to to_body (backward compatibility) - def to_hash - hash = {} - self.class.attribute_map.each_pair do |key, value| - if self.send(key).is_a?(Array) - next if self.send(key).empty? - hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? - else - unless (_tmp_value = _to_hash self.send(key)).nil? - hash[value] = _tmp_value + # data not found in attributes(hash), not an issue as the data can be optional end end - end - hash - end - # Method to output non-array value in the form of hash - # For object, use to_hash. Otherwise, just return the value - def _to_hash(value) - if value.respond_to? :to_hash - value.to_hash - else - value + self end - end + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :string + value.to_s + when :int + value.to_i + when :double + value.to_f + when :boolean + if value =~ /^(true|t|yes|y|1)$/i + true + else + false + end + else # model + _model = {{moduleName}}.const_get(type).new + _model.build_from_hash(value) + end + end + + # to_body is an alias to to_body (backward compatibility) + def to_hash + hash = {} + self.class.attribute_map.each_pair do |key, value| + if self.send(key).is_a?(Array) + next if self.send(key).empty? + hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + else + unless (_tmp_value = _to_hash self.send(key)).nil? + hash[value] = _tmp_value + end + end + end + hash + end + + # Method to output non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + def _to_hash(value) + if value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end end diff --git a/modules/swagger-codegen/src/main/resources/ruby/model.mustache b/modules/swagger-codegen/src/main/resources/ruby/model.mustache index 23e589b0862..d0d4e787756 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/model.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/model.mustache @@ -1,5 +1,3 @@ -require_relative 'base_object' - module {{moduleName}} {{#models}} # {{description}} {{#model}} class {{classname}} < BaseObject diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache index 78d45438825..89b4860a043 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -7,6 +7,7 @@ require '{{gemName}}/swagger/response' require '{{gemName}}/swagger/version' # Models +require '{{modelPackage}}/base_object' {{#models}} {{#model}} require '{{importPath}}' @@ -23,4 +24,4 @@ require '{{importPath}}' module {{moduleName}} # Initialize the default configuration Swagger.configuration ||= Swagger::Configuration.new -end \ No newline at end of file +end From ab4975b7f1eb4f26e10eeae1ef0973078df93804 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:46:49 +0800 Subject: [PATCH 53/75] Regenerate petstore ruby sample --- .../petstore/ruby/lib/swagger_client.rb | 3 +- .../ruby/lib/swagger_client/api/pet_api.rb | 182 +++++++------- .../ruby/lib/swagger_client/api/store_api.rb | 92 ++++---- .../ruby/lib/swagger_client/api/user_api.rb | 222 +++++++----------- .../lib/swagger_client/models/base_object.rb | 83 +++++++ .../lib/swagger_client/models/category.rb | 51 ++-- .../ruby/lib/swagger_client/models/order.rb | 103 ++++---- .../ruby/lib/swagger_client/models/pet.rb | 83 ++++--- .../ruby/lib/swagger_client/models/tag.rb | 51 ++-- .../ruby/lib/swagger_client/models/user.rb | 129 ++++++---- .../ruby/lib/swagger_client/swagger.rb | 25 +- .../lib/swagger_client/swagger/request.rb | 98 ++++++-- .../lib/swagger_client/swagger/response.rb | 8 +- 13 files changed, 646 insertions(+), 484 deletions(-) create mode 100644 samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb diff --git a/samples/client/petstore/ruby/lib/swagger_client.rb b/samples/client/petstore/ruby/lib/swagger_client.rb index 33922da4c73..6d239185005 100644 --- a/samples/client/petstore/ruby/lib/swagger_client.rb +++ b/samples/client/petstore/ruby/lib/swagger_client.rb @@ -7,6 +7,7 @@ require 'swagger_client/swagger/response' require 'swagger_client/swagger/version' # Models +require 'swagger_client/models/base_object' require 'swagger_client/models/user' require 'swagger_client/models/category' require 'swagger_client/models/pet' @@ -21,4 +22,4 @@ require 'swagger_client/api/store_api' module SwaggerClient # Initialize the default configuration Swagger.configuration ||= Swagger::Configuration.new -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb index 25a1a8f8bf4..6f2740b22e9 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb @@ -11,7 +11,7 @@ module SwaggerClient # @option opts [Pet] :body Pet object that needs to be added to the store # @return void def self.update_pet(opts = {}) - # verify existence of params + # resource path path = "/pet".sub('{format}','json') @@ -22,40 +22,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Add a new pet to the store # @@ -63,7 +46,7 @@ module SwaggerClient # @option opts [Pet] :body Pet object that needs to be added to the store # @return void def self.add_pet(opts = {}) - # verify existence of params + # resource path path = "/pet".sub('{format}','json') @@ -74,40 +57,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = ['application/json', 'application/xml', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Finds Pets by status # Multiple status values can be provided with comma seperated strings @@ -115,7 +81,7 @@ module SwaggerClient # @option opts [array[string]] :status Status values that need to be considered for filter # @return array[Pet] def self.find_pets_by_status(opts = {}) - # verify existence of params + # resource path path = "/pet/findByStatus".sub('{format}','json') @@ -127,21 +93,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| Pet.new(response) } - end + response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } + end # Finds Pets by tags # Muliple tags can be provided with comma seperated strings. Use tag1, tag2, tag3 for testing. @@ -149,7 +118,7 @@ module SwaggerClient # @option opts [array[string]] :tags Tags to filter by # @return array[Pet] def self.find_pets_by_tags(opts = {}) - # verify existence of params + # resource path path = "/pet/findByTags".sub('{format}','json') @@ -161,21 +130,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| Pet.new(response) } - end + response.map {|response| obj = Pet.new() and obj.build_from_hash(response) } + end # Find pet by ID # Returns a pet when ID < 10. ID > 10 or nonintegers will simulate API error conditions @@ -183,8 +155,10 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @return Pet def self.get_pet_by_id(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling get_pet_by_id" if pet_id.nil? + # resource path path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) @@ -195,21 +169,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - Pet.new(response) - end + obj = Pet.new() and obj.build_from_hash(response) + end # Updates a pet in the store with form data # @@ -219,8 +196,10 @@ module SwaggerClient # @option opts [string] :status Updated status of the pet # @return void def self.update_pet_with_form(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling update_pet_with_form" if pet_id.nil? + # resource path path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) @@ -231,11 +210,13 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = ['application/x-www-form-urlencoded', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -244,9 +225,10 @@ module SwaggerClient # http body (model) post_body = nil + - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Deletes a pet # @@ -255,8 +237,10 @@ module SwaggerClient # @option opts [string] :api_key # @return void def self.delete_pet(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling delete_pet" if pet_id.nil? + # resource path path = "/pet/{petId}".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) @@ -267,11 +251,13 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) header_params[:'api_key'] = opts[:'api_key'] if opts[:'api_key'] # form parameters @@ -279,9 +265,10 @@ module SwaggerClient # http body (model) post_body = nil + - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # uploads an image # @@ -291,8 +278,10 @@ module SwaggerClient # @option opts [file] :file file to upload # @return void def self.upload_file(pet_id, opts = {}) - # verify existence of params - raise "pet_id is required" if pet_id.nil? + + # verify the required parameter 'pet_id' is set + raise "Missing the required parameter 'pet_id' when calling upload_file" if pet_id.nil? + # resource path path = "/pet/{petId}/uploadImage".sub('{format}','json').sub('{' + 'petId' + '}', pet_id.to_s) @@ -303,11 +292,13 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = ['multipart/form-data', ] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} @@ -316,8 +307,9 @@ module SwaggerClient # http body (model) post_body = nil + - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end -end \ No newline at end of file + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb index 40a0d63c7ab..37595c2147e 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/store_api.rb @@ -10,7 +10,7 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @return map[string,int] def self.get_inventory(opts = {}) - # verify existence of params + # resource path path = "/store/inventory".sub('{format}','json') @@ -21,21 +21,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - response.map {|response| map.new(response) } - end + response.map {|response| obj = map.new() and obj.build_from_hash(response) } + end # Place an order for a pet # @@ -43,7 +46,7 @@ module SwaggerClient # @option opts [Order] :body order placed for purchasing the pet # @return Order def self.place_order(opts = {}) - # verify existence of params + # resource path path = "/store/order".sub('{format}','json') @@ -54,41 +57,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + response = Swagger::Request.new(:POST, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - Order.new(response) - end + obj = Order.new() and obj.build_from_hash(response) + end # Find purchase order by ID # For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions @@ -96,8 +82,10 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @return Order def self.get_order_by_id(order_id, opts = {}) - # verify existence of params - raise "order_id is required" if order_id.nil? + + # verify the required parameter 'order_id' is set + raise "Missing the required parameter 'order_id' when calling get_order_by_id" if order_id.nil? + # resource path path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) @@ -108,21 +96,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - Order.new(response) - end + obj = Order.new() and obj.build_from_hash(response) + end # Delete purchase order by ID # For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors @@ -130,8 +121,10 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @return void def self.delete_order(order_id, opts = {}) - # verify existence of params - raise "order_id is required" if order_id.nil? + + # verify the required parameter 'order_id' is set + raise "Missing the required parameter 'order_id' when calling delete_order" if order_id.nil? + # resource path path = "/store/order/{orderId}".sub('{format}','json').sub('{' + 'orderId' + '}', order_id.to_s) @@ -142,19 +135,22 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end -end \ No newline at end of file + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb index 0df9d287199..12a45561e3f 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/user_api.rb @@ -11,7 +11,7 @@ module SwaggerClient # @option opts [User] :body Created user object # @return void def self.create_user(opts = {}) - # verify existence of params + # resource path path = "/user".sub('{format}','json') @@ -22,40 +22,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Creates list of users with given input array # @@ -63,7 +46,7 @@ module SwaggerClient # @option opts [array[User]] :body List of user object # @return void def self.create_users_with_array_input(opts = {}) - # verify existence of params + # resource path path = "/user/createWithArray".sub('{format}','json') @@ -74,40 +57,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Creates list of users with given input array # @@ -115,7 +81,7 @@ module SwaggerClient # @option opts [array[User]] :body List of user object # @return void def self.create_users_with_list_input(opts = {}) - # verify existence of params + # resource path path = "/user/createWithList".sub('{format}','json') @@ -126,40 +92,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + - Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:POST, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Logs user into the system # @@ -168,7 +117,7 @@ module SwaggerClient # @option opts [string] :password The password for login in clear text # @return string def self.login_user(opts = {}) - # verify existence of params + # resource path path = "/user/login".sub('{format}','json') @@ -181,28 +130,31 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - string.new(response) - end + obj = string.new() and obj.build_from_hash(response) + end # Logs out current logged in user session # # @param [Hash] opts the optional parameters # @return void def self.logout_user(opts = {}) - # verify existence of params + # resource path path = "/user/logout".sub('{format}','json') @@ -213,20 +165,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + - Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:GET, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Get user by user name # @@ -234,8 +189,10 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @return User def self.get_user_by_name(username, opts = {}) - # verify existence of params - raise "username is required" if username.nil? + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling get_user_by_name" if username.nil? + # resource path path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) @@ -246,21 +203,24 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + response = Swagger::Request.new(:GET, path, {:params => query_params, :headers => header_params, :form_params => form_params, :body => post_body}).make.body - User.new(response) - end + obj = User.new() and obj.build_from_hash(response) + end # Updated user # This can only be done by the logged in user. @@ -269,8 +229,10 @@ module SwaggerClient # @option opts [User] :body Updated user object # @return void def self.update_user(username, opts = {}) - # verify existence of params - raise "username is required" if username.nil? + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling update_user" if username.nil? + # resource path path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) @@ -281,40 +243,23 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) - post_body = nil - _body_param = opts[:'body'] - if _body_param != nil - if _body_param.is_a?(Array) - _array = Array.new - _body_param.each do |item| - if item.respond_to?(:to_body) - _array.push item.to_body - else - _array.push item - end - end - post_body = _array - else - if _body_param.respond_to?(:to_body) - post_body = _body_param.to_body - else - post_body = _body_param - end - end - end + post_body = Swagger::Request.object_to_http_body(opts[:'body']) + - Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:PUT, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make + end # Delete user # This can only be done by the logged in user. @@ -322,8 +267,10 @@ module SwaggerClient # @param [Hash] opts the optional parameters # @return void def self.delete_user(username, opts = {}) - # verify existence of params - raise "username is required" if username.nil? + + # verify the required parameter 'username' is set + raise "Missing the required parameter 'username' when calling delete_user" if username.nil? + # resource path path = "/user/{username}".sub('{format}','json').sub('{' + 'username' + '}', username.to_s) @@ -334,19 +281,22 @@ module SwaggerClient # header parameters header_params = {} - _header_accept = 'application/json, application/xml' - header_params['Accept'] = _header_accept if _header_accept != '' + # HTTP header 'Accept' (if needed) + _header_accept = ['application/json', 'application/xml'] + _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result + # HTTP header 'Content-Type' _header_content_type = [] - header_params['Content-Type'] = _header_content_type.length > 0 ? _header_content_type[0] : 'application/json' + header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters form_params = {} # http body (model) post_body = nil + - Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make - end + Swagger::Request.new(:DELETE, path, {:params => query_params,:headers => header_params, :form_params => form_params, :body => post_body}).make end -end \ No newline at end of file + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb new file mode 100644 index 00000000000..642e4769e55 --- /dev/null +++ b/samples/client/petstore/ruby/lib/swagger_client/models/base_object.rb @@ -0,0 +1,83 @@ +module SwaggerClient + # base class containing fundamental method such as to_hash, build_from_hash and more + class BaseObject + + # return the object in the form of hash + def to_body + body = {} + self.class.attribute_map.each_pair do |key, value| + body[value] = self.send(key) unless self.send(key).nil? + end + body + end + + # build the object from hash + def build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + self.class.swagger_types.each_pair do |key, type| + if type =~ /^array\[(.*)\]/i + if attributes[self.class.attribute_map[key]].is_a?(Array) + self.send("#{key}=", attributes[self.class.attribute_map[key]].map{ |v| _deserialize($1, v) } ) + else + #TODO show warning in debug mode + end + elsif !attributes[self.class.attribute_map[key]].nil? + self.send("#{key}=", _deserialize(type, attributes[self.class.attribute_map[key]])) + else + # data not found in attributes(hash), not an issue as the data can be optional + end + end + + self + end + + def _deserialize(type, value) + case type.to_sym + when :DateTime + DateTime.parse(value) + when :string + value.to_s + when :int + value.to_i + when :double + value.to_f + when :boolean + if value =~ /^(true|t|yes|y|1)$/i + true + else + false + end + else # model + _model = SwaggerClient.const_get(type).new + _model.build_from_hash(value) + end + end + + # to_body is an alias to to_body (backward compatibility) + def to_hash + hash = {} + self.class.attribute_map.each_pair do |key, value| + if self.send(key).is_a?(Array) + next if self.send(key).empty? + hash[value] = self.send(key).select{|v| !v.nil?}.map{ |v| _to_hash v} unless self.send(key).nil? + else + unless (_tmp_value = _to_hash self.send(key)).nil? + hash[value] = _tmp_value + end + end + end + hash + end + + # Method to output non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + def _to_hash(value) + if value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb index 87e41aad6fd..fe195c7ac87 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/category.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/category.rb @@ -1,35 +1,44 @@ module SwaggerClient - class Category + # + class Category < BaseObject attr_accessor :id, :name - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :name => :'name' + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"name"] - @name = attributes["name"] - end - - end + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] end - body + + if attributes[:'name'] + @name = attributes[:'name'] + end + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb index 9adad6920ad..3fe0282ed9b 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/order.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/order.rb @@ -1,55 +1,76 @@ module SwaggerClient - class Order + # + class Order < BaseObject attr_accessor :id, :pet_id, :quantity, :ship_date, :status, :complete - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :pet_id => :'petId', - :quantity => :'quantity', - :ship_date => :'shipDate', - :status => :'status', - :complete => :'complete' + + # + :'id' => :'id', + + # + :'pet_id' => :'petId', + + # + :'quantity' => :'quantity', + + # + :'ship_date' => :'shipDate', + + # Order Status + :'status' => :'status', + + # + :'complete' => :'complete' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'pet_id' => :'int', + :'quantity' => :'int', + :'ship_date' => :'DateTime', + :'status' => :'string', + :'complete' => :'boolean' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - 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[:"ship_date"] - @ship_date = attributes["shipDate"] - end - - if self.class.attribute_map[:"status"] - @status = attributes["status"] - end - - if self.class.attribute_map[:"complete"] - @complete = attributes["complete"] - end - - end + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] end - body + + if attributes[:'petId'] + @pet_id = attributes[:'petId'] + end + + if attributes[:'quantity'] + @quantity = attributes[:'quantity'] + end + + if attributes[:'shipDate'] + @ship_date = attributes[:'shipDate'] + end + + if attributes[:'status'] + @status = attributes[:'status'] + end + + if attributes[:'complete'] + @complete = attributes[:'complete'] + end + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb index 18e2be1dae0..32f95646c72 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/pet.rb @@ -1,59 +1,80 @@ module SwaggerClient - class Pet + # + class Pet < BaseObject attr_accessor :id, :category, :name, :photo_urls, :tags, :status - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :category => :'category', - :name => :'name', - :photo_urls => :'photoUrls', - :tags => :'tags', - :status => :'status' + + # + :'id' => :'id', + + # + :'category' => :'category', + + # + :'name' => :'name', + + # + :'photo_urls' => :'photoUrls', + + # + :'tags' => :'tags', + + # pet status in the store + :'status' => :'status' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'category' => :'Category', + :'name' => :'string', + :'photo_urls' => :'array[string]', + :'tags' => :'array[Tag]', + :'status' => :'string' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style + return if !attributes.is_a?(Hash) || attributes.empty? + + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + - if self.class.attribute_map[:"id"] - @id = attributes["id"] + if attributes[:'id'] + @id = attributes[:'id'] end - if self.class.attribute_map[:"category"] - @category = attributes["category"] + if attributes[:'category'] + @category = attributes[:'category'] end - if self.class.attribute_map[:"name"] - @name = attributes["name"] + if attributes[:'name'] + @name = attributes[:'name'] end - if self.class.attribute_map[:"photo_urls"] - if (value = attributes["photoUrls"]).is_a?(Array) + if attributes[:'photoUrls'] + if (value = attributes[:'photoUrls']).is_a?(Array) @photo_urls = value end end - if self.class.attribute_map[:"tags"] - if (value = attributes["tags"]).is_a?(Array) - @tags = value.map{ |v| Tag.new(v) } + if attributes[:'tags'] + if (value = attributes[:'tags']).is_a?(Array) + @tags = value end end - if self.class.attribute_map[:"status"] - @status = attributes["status"] + if attributes[:'status'] + @status = attributes[:'status'] end end - - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? - end - body - end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb index 41477ac7353..9c5cdde1af6 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/tag.rb @@ -1,35 +1,44 @@ module SwaggerClient - class Tag + # + class Tag < BaseObject attr_accessor :id, :name - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :name => :'name' + + # + :'id' => :'id', + + # + :'name' => :'name' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'name' => :'string' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"name"] - @name = attributes["name"] - end - - end + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] end - body + + if attributes[:'name'] + @name = attributes[:'name'] + end + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb index 042d589726b..2d723da54c4 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/models/user.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/models/user.rb @@ -1,65 +1,92 @@ module SwaggerClient - class User + # + class User < BaseObject attr_accessor :id, :username, :first_name, :last_name, :email, :password, :phone, :user_status - # :internal => :external + # attribute mapping from ruby-style variable name to JSON key def self.attribute_map { - :id => :'id', - :username => :'username', - :first_name => :'firstName', - :last_name => :'lastName', - :email => :'email', - :password => :'password', - :phone => :'phone', - :user_status => :'userStatus' + + # + :'id' => :'id', + + # + :'username' => :'username', + + # + :'first_name' => :'firstName', + + # + :'last_name' => :'lastName', + + # + :'email' => :'email', + + # + :'password' => :'password', + + # + :'phone' => :'phone', + + # User Status + :'user_status' => :'userStatus' + + } + end + + # attribute type + def self.swagger_types + { + :'id' => :'int', + :'username' => :'string', + :'first_name' => :'string', + :'last_name' => :'string', + :'email' => :'string', + :'password' => :'string', + :'phone' => :'string', + :'user_status' => :'int' } end def initialize(attributes = {}) - return if attributes.empty? - # Morph attribute keys into undescored rubyish style - - if self.class.attribute_map[:"id"] - @id = attributes["id"] - end - - if self.class.attribute_map[:"username"] - @username = attributes["username"] - end - - if self.class.attribute_map[:"first_name"] - @first_name = attributes["firstName"] - end - - if self.class.attribute_map[:"last_name"] - @last_name = attributes["lastName"] - end - - if self.class.attribute_map[:"email"] - @email = attributes["email"] - end - - if self.class.attribute_map[:"password"] - @password = attributes["password"] - end - - if self.class.attribute_map[:"phone"] - @phone = attributes["phone"] - end - - if self.class.attribute_map[:"user_status"] - @user_status = attributes["userStatus"] - end - - end + return if !attributes.is_a?(Hash) || attributes.empty? - def to_body - body = {} - self.class.attribute_map.each_pair do |key, value| - body[value] = self.send(key) unless self.send(key).nil? + # convert string to symbol for hash key + attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo} + + + if attributes[:'id'] + @id = attributes[:'id'] end - body + + if attributes[:'username'] + @username = attributes[:'username'] + end + + if attributes[:'firstName'] + @first_name = attributes[:'firstName'] + end + + if attributes[:'lastName'] + @last_name = attributes[:'lastName'] + end + + if attributes[:'email'] + @email = attributes[:'email'] + end + + if attributes[:'password'] + @password = attributes[:'password'] + end + + if attributes[:'phone'] + @phone = attributes[:'phone'] + end + + if attributes[:'userStatus'] + @user_status = attributes[:'userStatus'] + end + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb index 925382cf94e..278db36e4ca 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger.rb @@ -1,16 +1,17 @@ require 'logger' +require 'json' module SwaggerClient module Swagger class << self attr_accessor :logger - + # A Swagger configuration object. Must act like a hash and return sensible # values for all Swagger configuration options. See Swagger::Configuration. attr_accessor :configuration attr_accessor :resources - + # Call this method to modify defaults in your initializers. # # @example @@ -38,31 +39,31 @@ module SwaggerClient configuration.base_path = "/#{configuration.base_path}".gsub(/\/+/, '/') configuration.base_path = "" if configuration.base_path == "/" end - + def authenticated? Swagger.configuration.auth_token.present? end - + def de_authenticate Swagger.configuration.auth_token = nil end - + def authenticate return if Swagger.authenticated? - + if Swagger.configuration.username.blank? || Swagger.configuration.password.blank? raise ClientError, "Username and password are required to authenticate." end - + request = Swagger::Request.new( - :get, - "account/authenticate/{username}", + :get, + "account/authenticate/{username}", :params => { - :username => Swagger.configuration.username, + :username => Swagger.configuration.username, :password => Swagger.configuration.password } ) - + response_body = request.response.body Swagger.configuration.auth_token = response_body['token'] end @@ -74,4 +75,4 @@ module SwaggerClient class ClientError < StandardError end -end \ No newline at end of file +end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb index 8a605784a3a..d5f266267da 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/request.rb @@ -24,21 +24,21 @@ module SwaggerClient if attributes[:headers].present? && attributes[:headers].has_key?(:api_key) default_headers.delete(:api_key) end - + # api_key from params hash trumps all others (headers and default_headers) if attributes[:params].present? && attributes[:params].has_key?(:api_key) default_headers.delete(:api_key) attributes[:headers].delete(:api_key) if attributes[:headers].present? end - + # Merge argument headers into defaults attributes[:headers] = default_headers.merge(attributes[:headers] || {}) - + # Stick in the auth token if there is one if Swagger.authenticated? attributes[:headers].merge!({:auth_token => Swagger.configuration.auth_token}) end - + self.http_method = http_method.to_sym self.path = path attributes.each do |name, value| @@ -47,20 +47,20 @@ module SwaggerClient end # Construct a base URL - def url(options = {}) + def url(options = {}) u = Addressable::URI.new( :scheme => Swagger.configuration.scheme, :host => Swagger.configuration.host, :path => self.interpreted_path, :query => self.query_string.sub(/\?/, '') ).to_s - + # Drop trailing question mark, if present u.sub! /\?$/, '' - + # Obfuscate API key? u.sub! /api\_key=\w+/, 'api_key=YOUR_API_KEY' if options[:obfuscated] - + u end @@ -83,18 +83,18 @@ module SwaggerClient # e.g. /words/blah => /words/blah.{format} if Swagger.configuration.force_ending_format unless ['.json', '.xml', '{format}'].any? {|s| p.downcase.include? s } - p = "#{p}.#{format}" + p = "#{p}.#{format}" end end p = p.sub("{format}", self.format.to_s) - + URI.encode [Swagger.configuration.base_path, p].join("/").gsub(/\/+/, '/') end - + # Massage the request body into a state of readiness # If body is a hash, camelize all keys then convert to a json string - def body=(value) + def body=(value) if value.is_a?(Hash) value = value.inject({}) do |memo, (k,v)| memo[k.to_s.camelize(:lower).to_sym] = v @@ -103,9 +103,9 @@ module SwaggerClient end @body = value end - + # If body is an object, JSONify it before making the actual request. - # For form parameters, remove empty value + # For form parameters, remove empty value def outgoing_body # http form if @body.nil? && @form_params && !@form_params.empty? @@ -118,7 +118,7 @@ module SwaggerClient @body.is_a?(String) ? @body : @body.to_json end end - + # Construct a query string from the query-string-type params def query_string # Iterate over all params, @@ -133,17 +133,17 @@ module SwaggerClient end query_values[key] = value.to_s end - + # We don't want to end up with '?' as our query string # if there aren't really any params return "" if query_values.blank? - + # Addressable requires query_values to be set after initialization.. qs = Addressable::URI.new qs.query_values = query_values qs.to_s end - + def make #TODO use configuration setting to determine if debugging #logger = Logger.new STDOUT @@ -175,7 +175,7 @@ module SwaggerClient :body => self.outgoing_body, :headers => self.headers.stringify_keys, ) - + when :delete,:DELETE Typhoeus::Request.delete( self.url, @@ -185,21 +185,73 @@ module SwaggerClient end Response.new(response) end - + def response self.make end - + def response_code_pretty return unless @response.present? - @response.code.to_s + @response.code.to_s end - + def response_headers_pretty return unless @response.present? # JSON.pretty_generate(@response.headers).gsub(/\n/, '
') # <- This was for RestClient @response.headers.gsub(/\n/, '
') # <- This is for Typhoeus end + + # return 'Accept' based on an array of accept provided + # @param [Array] header_accept_array Array fo 'Accept' + # @return String Accept (e.g. application/json) + def self.select_header_accept header_accept_array + if header_accept_array.empty? + return + elsif header_accept_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # look for json data by default + else + header_accept_array.join(',') + end + end + + # return the content type based on an array of content-type provided + # @param [Array] content_type_array Array fo content-type + # @return String Content-Type (e.g. application/json) + def self.select_header_content_type content_type_array + if content_type_array.empty? + 'application/json' # use application/json by default + elsif content_type_array.any?{ |s| s.casecmp('application/json')==0 } + 'application/json' # use application/json if it's included + else + content_type_array[0]; # otherwise, use the first one + end + end + + # static method to convert object (array, hash, object, etc) to JSON string + # @param model object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_http_body model + return if model.nil? + _body = nil + if model.is_a?(Array) + _body = model.map{|m| object_to_hash(m) } + else + _body = object_to_hash(model) + end + _body.to_json + end + + # static method to convert object(non-array) to hash + # @param obj object to be converted into JSON string + # @return string JSON string representation of the object + def self.object_to_hash obj + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + end end end diff --git a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb index b0870d2f220..538821bea69 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/swagger/response.rb @@ -17,7 +17,7 @@ module SwaggerClient def code raw.code end - + # Account for error messages that take different forms... def error_message body['message'] @@ -28,12 +28,12 @@ module SwaggerClient # If body is JSON, parse it # Otherwise return raw string def body - JSON.parse raw.body + JSON.parse(raw.body, :symbolize_names => true) rescue raw.body end - # `headers_hash` is a Typhoeus-specific extension of Hash, + # `headers_hash` is a Typhoeus-specific extension of Hash, # so simplify it back into a regular old Hash. def headers h = {} @@ -67,4 +67,4 @@ module SwaggerClient end end end -end \ No newline at end of file +end From 70c74d282f89249cdc617abf2399441b06d5b160 Mon Sep 17 00:00:00 2001 From: xhh Date: Mon, 18 May 2015 16:47:35 +0800 Subject: [PATCH 54/75] Fix tests --- samples/client/petstore/ruby/spec/pet_spec.rb | 24 +++++++++---------- .../client/petstore/ruby/spec/spec_helper.rb | 10 ++++---- 2 files changed, 17 insertions(+), 17 deletions(-) diff --git a/samples/client/petstore/ruby/spec/pet_spec.rb b/samples/client/petstore/ruby/spec/pet_spec.rb index fce80afb3bc..f66f33cf84c 100644 --- a/samples/client/petstore/ruby/spec/pet_spec.rb +++ b/samples/client/petstore/ruby/spec/pet_spec.rb @@ -6,17 +6,17 @@ describe "Pet" do configure_swagger prepare_pet end - + describe "pet methods" do it "should construct a new pet object" do - tag1 = Tag.new({'id' => 1, 'name'=> 'tag1'}) - tag2 = Tag.new({'id' => 2, 'name'=> 'tag2'}) - category1 = Category.new({:id => 1, :name => 'category unknown'}) + tag1 = SwaggerClient::Tag.new({'id' => 1, 'name'=> 'tag1'}) + tag2 = SwaggerClient::Tag.new({'id' => 2, 'name'=> 'tag2'}) + category1 = SwaggerClient::Category.new({:id => 1, :name => 'category unknown'}) # initalize using both string and symbol key pet_hash = {:'id' => 10002, :'name' => "RUBY UNIT TESTING", :'status' => "pending", :'photo_urls' => ["url1", "url2"], :'category' => category1, :'tags' => [tag1, tag2]} - pet = Pet.new(pet_hash) + pet = SwaggerClient::Pet.new(pet_hash) # test new pet.name.should == "RUBY UNIT TESTING" pet.status.should == "pending" @@ -26,7 +26,7 @@ describe "Pet" do pet.category.name.should == 'category unknown' # test build_from_hash - pet2 = Pet.new + pet2 = SwaggerClient::Pet.new pet2.build_from_hash(pet.to_hash) pet.to_hash.should == pet2.to_hash @@ -49,7 +49,7 @@ describe "Pet" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'available') pets.length.should >= 3 end - + it "should not find a pet with invalid status" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => 'invalid-status') pets.length.should == 0 @@ -57,23 +57,23 @@ describe "Pet" do it "should find a pet by status" do pets = SwaggerClient::PetApi.find_pets_by_status(:status => "available,sold") - pets.map {|pet| - if(pet.status != 'available' && pet.status != 'sold') + pets.map {|pet| + if(pet.status != 'available' && pet.status != 'sold') raise "pet status wasn't right" end } end - + it "should update a pet" do pet = SwaggerClient::Pet.new({'id' => 10002, 'status' => 'sold'}) SwaggerClient::PetApi.add_pet(:body => pet) - + fetched = SwaggerClient::PetApi.get_pet_by_id(10002) fetched.id.should == 10002 fetched.status.should == 'sold' end - it "should create a pet" do + it "should create a pet" do pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING") SwaggerClient::PetApi.add_pet(:body => pet) diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 12d51679fc8..09012db2998 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -49,12 +49,12 @@ def prepare_pet # remove the pet SwaggerClient::PetApi.delete_pet(10002) # recreate the pet - category = Category.new('id' => 20002, 'name' => 'category test') - tag = Tag.new('id' => 30002, 'name' => 'tag test') - pet = Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', - 'category' => category, 'tags' => [tag], 'status' => 'pending') + category = SwaggerClient::Category.new('id' => 20002, 'name' => 'category test') + tag = SwaggerClient::Tag.new('id' => 30002, 'name' => 'tag test') + pet = SwaggerClient::Pet.new('id' => 10002, 'name' => "RUBY UNIT TESTING", 'photo_urls' => 'photo url', + 'category' => category, 'tags' => [tag], 'status' => 'pending') - PetApi.add_pet(:'body'=> pet) + SwaggerClient::PetApi.add_pet(:'body'=> pet) end # always delete and then re-create the store order From 792059f195fa0377c7561bf3ebae6e452089d33a Mon Sep 17 00:00:00 2001 From: xhh Date: Tue, 19 May 2015 11:12:49 +0800 Subject: [PATCH 55/75] Avoid warnings for ruby gem building --- .../ruby/swagger_client.gemspec.mustache | 21 ++++++++++--------- samples/client/petstore/ruby/Gemfile.lock | 20 +++++++++--------- .../petstore/ruby/swagger_client.gemspec | 21 ++++++++++--------- 3 files changed, 32 insertions(+), 30 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache index d23c4851b24..9f84d88d4e1 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.gemspec.mustache @@ -11,18 +11,19 @@ Gem::Specification.new do |s| s.homepage = "http://developer.wordnik.com" s.summary = %q{A ruby wrapper for the swagger APIs} s.description = %q{This gem maps to a swagger API} + s.license = "Apache-2.0" - s.add_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' + s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' + s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' - s.add_development_dependency 'rspec', '>=2.5.0' - s.add_development_dependency 'vcr', '>=1.5.1' - s.add_development_dependency 'webmock', '>=1.6.2' - s.add_development_dependency 'autotest' - s.add_development_dependency 'autotest-rails-pure' - s.add_development_dependency 'autotest-growl' - s.add_development_dependency 'autotest-fsevent' + s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' + s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' + s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' + s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' + s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' + s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.test_files = `find spec/*`.split("\n") diff --git a/samples/client/petstore/ruby/Gemfile.lock b/samples/client/petstore/ruby/Gemfile.lock index c2f0a21b3fc..e9e03f10b77 100644 --- a/samples/client/petstore/ruby/Gemfile.lock +++ b/samples/client/petstore/ruby/Gemfile.lock @@ -2,9 +2,9 @@ PATH remote: . specs: swagger_client (1.0.0) - addressable (>= 2.2.4) - json (>= 1.4.6) - typhoeus (>= 0.2.1) + addressable (~> 2.2, >= 2.2.4) + json (~> 1.4, >= 1.4.6) + typhoeus (~> 0.2, >= 0.2.1) GEM remote: http://rubygems.org/ @@ -51,11 +51,11 @@ PLATFORMS ruby DEPENDENCIES - autotest - autotest-fsevent - autotest-growl - autotest-rails-pure - rspec (>= 2.5.0) + autotest (~> 4.4, >= 4.4.6) + autotest-fsevent (~> 0.2, >= 0.2.10) + autotest-growl (~> 0.2, >= 0.2.16) + autotest-rails-pure (~> 4.1, >= 4.1.2) + rspec (~> 3.2, >= 3.2.0) swagger_client! - vcr (>= 1.5.1) - webmock (>= 1.6.2) + vcr (~> 2.9, >= 2.9.3) + webmock (~> 1.6, >= 1.6.2) diff --git a/samples/client/petstore/ruby/swagger_client.gemspec b/samples/client/petstore/ruby/swagger_client.gemspec index dc3cd8350bd..6ec2484e05c 100644 --- a/samples/client/petstore/ruby/swagger_client.gemspec +++ b/samples/client/petstore/ruby/swagger_client.gemspec @@ -11,18 +11,19 @@ Gem::Specification.new do |s| s.homepage = "http://developer.wordnik.com" s.summary = %q{A ruby wrapper for the swagger APIs} s.description = %q{This gem maps to a swagger API} + s.license = "Apache-2.0" - s.add_dependency 'typhoeus', '>=0.2.1' - s.add_dependency 'addressable', '>=2.2.4' - s.add_dependency 'json', '>=1.4.6' + s.add_runtime_dependency 'typhoeus', '~> 0.2', '>= 0.2.1' + s.add_runtime_dependency 'addressable', '~> 2.2', '>= 2.2.4' + s.add_runtime_dependency 'json', '~> 1.4', '>= 1.4.6' - s.add_development_dependency 'rspec', '>=2.5.0' - s.add_development_dependency 'vcr', '>=1.5.1' - s.add_development_dependency 'webmock', '>=1.6.2' - s.add_development_dependency 'autotest' - s.add_development_dependency 'autotest-rails-pure' - s.add_development_dependency 'autotest-growl' - s.add_development_dependency 'autotest-fsevent' + s.add_development_dependency 'rspec', '~> 3.2', '>= 3.2.0' + s.add_development_dependency 'vcr', '~> 2.9', '>= 2.9.3' + s.add_development_dependency 'webmock', '~> 1.6', '>= 1.6.2' + s.add_development_dependency 'autotest', '~> 4.4', '>= 4.4.6' + s.add_development_dependency 'autotest-rails-pure', '~> 4.1', '>= 4.1.2' + s.add_development_dependency 'autotest-growl', '~> 0.2', '>= 0.2.16' + s.add_development_dependency 'autotest-fsevent', '~> 0.2', '>= 0.2.10' s.files = `find *`.split("\n").uniq.sort.select{|f| !f.empty? } s.test_files = `find spec/*`.split("\n") From 312f1c6f25461a8c7b01e47625cf3d9313f383f3 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 20 May 2015 09:23:02 +0800 Subject: [PATCH 56/75] Avoid the importPath field --- .../com/wordnik/swagger/codegen/CodegenModel.java | 2 +- .../com/wordnik/swagger/codegen/DefaultCodegen.java | 13 ++++++------- .../wordnik/swagger/codegen/DefaultGenerator.java | 1 + .../src/main/resources/ruby/swagger_client.mustache | 2 -- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index 274b77b4e9d..bcd78fa3e04 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -7,7 +7,7 @@ import java.util.*; public class CodegenModel { public String parent; - public String name, classname, importPath, description, classVarName, modelJson; + public String name, classname, description, classVarName, modelJson; public String defaultValue; public List vars = new ArrayList(); public Set imports = new HashSet(); 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 3642e8de1b6..2e79cdcdcc2 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 @@ -61,7 +61,7 @@ public class DefaultCodegen { // override with any special handling of the entire swagger spec public void processSwagger(Swagger swagger) {} - + // override with any special text escaping logic public String escapeText(String input) { if(input != null) { @@ -428,7 +428,6 @@ public class DefaultCodegen { m.name = name; m.description = escapeText(model.getDescription()); m.classname = toModelName(name); - m.importPath = toModelImport(name); m.classVarName = toVarName(name); m.modelJson = Json.pretty(model); m.externalDocs = model.getExternalDocs(); @@ -503,18 +502,18 @@ public class DefaultCodegen { if(cp.isContainer != null) { String arrayImport = typeMapping.get("array"); if(arrayImport != null && - !languageSpecificPrimitives.contains(arrayImport) && + !languageSpecificPrimitives.contains(arrayImport) && !defaultIncludes.contains(arrayImport)) m.imports.add(arrayImport); } if(cp.complexType != null && - !languageSpecificPrimitives.contains(cp.complexType) && + !languageSpecificPrimitives.contains(cp.complexType) && !defaultIncludes.contains(cp.complexType)) m.imports.add(cp.complexType); if(cp.baseType != null && - !languageSpecificPrimitives.contains(cp.baseType) && + !languageSpecificPrimitives.contains(cp.baseType) && !defaultIncludes.contains(cp.baseType)) m.imports.add(cp.baseType); } @@ -842,7 +841,7 @@ public class DefaultCodegen { op.nickname = op.operationId; - if(op.allParams.size() > 0) + if(op.allParams.size() > 0) op.hasParams = true; op.externalDocs = operation.getExternalDocs(); @@ -1081,7 +1080,7 @@ public class DefaultCodegen { operations.put(tag, opList); } opList.add(co); - co.baseName = tag; + co.baseName = tag; } /* underscore and camelize are copied from Twitter elephant bird 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 395f298eb07..7a522230c29 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 @@ -428,6 +428,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { CodegenModel cm = config.fromModel(key, mm); Map mo = new HashMap(); mo.put("model", cm); + mo.put("importPath", config.toModelImport(key)); models.add(mo); allImports.addAll(cm.imports); } diff --git a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache index 89b4860a043..df675ddf26e 100644 --- a/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache +++ b/modules/swagger-codegen/src/main/resources/ruby/swagger_client.mustache @@ -9,9 +9,7 @@ require '{{gemName}}/swagger/version' # Models require '{{modelPackage}}/base_object' {{#models}} -{{#model}} require '{{importPath}}' -{{/model}} {{/models}} # APIs From 0fb191819620dbc7bebe2a7f3a35482a7b3740d3 Mon Sep 17 00:00:00 2001 From: xhh Date: Wed, 20 May 2015 10:13:29 +0800 Subject: [PATCH 57/75] Revert unnecessary changes on whitespace --- .../com/wordnik/swagger/codegen/CodegenModel.java | 2 +- .../com/wordnik/swagger/codegen/DefaultCodegen.java | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java index bcd78fa3e04..169886da22e 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenModel.java @@ -13,4 +13,4 @@ public class CodegenModel { public Set imports = new HashSet(); public Boolean hasVars, emptyVars, hasMoreModels; public ExternalDocs externalDocs; -} +} \ No newline at end of file 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 2e79cdcdcc2..6f51374c536 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 @@ -61,7 +61,7 @@ public class DefaultCodegen { // override with any special handling of the entire swagger spec public void processSwagger(Swagger swagger) {} - + // override with any special text escaping logic public String escapeText(String input) { if(input != null) { @@ -502,18 +502,18 @@ public class DefaultCodegen { if(cp.isContainer != null) { String arrayImport = typeMapping.get("array"); if(arrayImport != null && - !languageSpecificPrimitives.contains(arrayImport) && + !languageSpecificPrimitives.contains(arrayImport) && !defaultIncludes.contains(arrayImport)) m.imports.add(arrayImport); } if(cp.complexType != null && - !languageSpecificPrimitives.contains(cp.complexType) && + !languageSpecificPrimitives.contains(cp.complexType) && !defaultIncludes.contains(cp.complexType)) m.imports.add(cp.complexType); if(cp.baseType != null && - !languageSpecificPrimitives.contains(cp.baseType) && + !languageSpecificPrimitives.contains(cp.baseType) && !defaultIncludes.contains(cp.baseType)) m.imports.add(cp.baseType); } @@ -841,7 +841,7 @@ public class DefaultCodegen { op.nickname = op.operationId; - if(op.allParams.size() > 0) + if(op.allParams.size() > 0) op.hasParams = true; op.externalDocs = operation.getExternalDocs(); @@ -1080,7 +1080,7 @@ public class DefaultCodegen { operations.put(tag, opList); } opList.add(co); - co.baseName = tag; + co.baseName = tag; } /* underscore and camelize are copied from Twitter elephant bird From 278a653154cc2aafbeaaadb13f86ccf39f98f155 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 May 2015 15:57:54 +0800 Subject: [PATCH 58/75] add authentication --- .../swagger/codegen/DefaultGenerator.java | 1 + .../src/main/resources/php/APIClient.mustache | 26 ++++++++- .../src/main/resources/php/api.mustache | 10 ++-- .../php/SwaggerClient-php/lib/APIClient.php | 42 ++++++++++++-- .../php/SwaggerClient-php/lib/PetApi.php | 55 +++++++++++++------ .../php/SwaggerClient-php/lib/StoreApi.php | 35 +++++++----- .../php/SwaggerClient-php/lib/UserApi.php | 50 ++++++++++++----- 7 files changed, 164 insertions(+), 55 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 7a522230c29..1636a1dc79f 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 @@ -218,6 +218,7 @@ public class DefaultGenerator extends AbstractGenerator implements Generator { bundle.put("models", allModels); bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); bundle.put("modelPackage", config.modelPackage()); + bundle.put("authMethods", config.fromSecurity(swagger.getSecurityDefinitions())); if (swagger.getExternalDocs() != null) { bundle.put("externalDocs", swagger.getExternalDocs()); } diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index a750daff12d..bb43e7bdc4b 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -67,6 +67,30 @@ class APIClient { $this->curl_timeout = $seconds; } + /** + * @param array $headerParams + * @param array $queryParams + * @param array $authSettings + */ + public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) + { + if (count($authSettings) == 0) + return; + + // one endpoint can have more than 1 auth settings + foreach($authSettings as $auth) { + // determine which one to use + switch($auth) { + {{#authMethods}} + case '{{name}}': + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = Configuration::$api_key;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = Configuration::$api_key;{{/isKeyInQuery}}{{#isBasic}}$headerParams['Authorization'] = base64_encode(Configuraiton::$username.":"Configuration::$password){{/isBasic}}{{/isApiKey}} + break; + {{/authMethods}} + } + } + } + + /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -76,7 +100,7 @@ class APIClient { * @return mixed */ public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { + $headerParams, $authSettings) { $headers = array(); diff --git a/modules/swagger-codegen/src/main/resources/php/api.mustache b/modules/swagger-codegen/src/main/resources/php/api.mustache index 7759af5004d..09a53fd7a74 100644 --- a/modules/swagger-codegen/src/main/resources/php/api.mustache +++ b/modules/swagger-codegen/src/main/resources/php/api.mustache @@ -92,18 +92,20 @@ class {{classname}} { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array({{#authMethods}}'{{name}}'{{#hasMore}}, {{/hasMore}}{{/authMethods}}); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); {{#returnType}}if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - '{{returnType}}'); - return $responseObject;{{/returnType}} + $responseObject = $this->apiClient->deserialize($response,'{{returnType}}'); + return $responseObject;{{/returnType}} } {{/operation}} {{newline}} diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d6d14c72527..e608421a891 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -67,6 +67,35 @@ class APIClient { $this->curl_timeout = $seconds; } + /** + * @param array $headerParams + * @param array $queryParams + * @param array $authSettings + */ + public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) + { + if (count($authSettings) == 0) + return; + + // one endpoint can have more than 1 auth settings + foreach($authSettings as $auth) { + // determine which auth scheme to use + switch($auth) { + + case 'api_key': + $headerParams['api_key'] = Configuration::$api_key; + + break; + + case 'petstore_auth': + + break; + + } + } + } + + /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -76,7 +105,7 @@ class APIClient { * @return mixed */ public function callAPI($resourcePath, $method, $queryParams, $postData, - $headerParams) { + $headerParams, $authSettings) { $headers = array(); @@ -142,20 +171,21 @@ class APIClient { $response_info = curl_getinfo($curl); // Handle the response - if ($response === false) { // error, likely in the client side - throw new APIClientException("API Error ($url): ".curl_error($curl), 0, $response_info, $response); + if ($response_info['http_code'] == 0) { + throw new APIClientException("TIMEOUT: api call to " . $url . + " took more than 5s to return", 0, $response_info, $response); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { $data = json_decode($response); if (json_last_error() > 0) { // if response is a string $data = $response; } - } else if ($response_info['http_code'] == 401) { // server returns 401 + } else if ($response_info['http_code'] == 401) { throw new APIClientException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { // server returns 404 + } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new APIClientException("Can't connect to the API: " . $url . + throw new APIClientException("Can't connect to the api: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 07f6181a730..b5f1954acde 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -73,10 +73,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -125,10 +128,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -176,18 +182,20 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'array[Pet]'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'array[Pet]'); + return $responseObject; } /** @@ -233,18 +241,20 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'array[Pet]'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'array[Pet]'); + return $responseObject; } /** @@ -296,18 +306,20 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('api_key', 'petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'Pet'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'Pet'); + return $responseObject; } /** @@ -367,10 +379,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -428,10 +443,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -493,10 +511,13 @@ class PetApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('petstore_auth'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 78e23ec9034..4012a88fc54 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -68,18 +68,20 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array('api_key'); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'map[string,int]'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'map[string,int]'); + return $responseObject; } /** @@ -126,18 +128,20 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'Order'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'Order'); + return $responseObject; } /** @@ -189,18 +193,20 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'Order'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'Order'); + return $responseObject; } /** @@ -252,10 +258,13 @@ class StoreApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php index a3ed8a8ab25..b2ef035e972 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/UserApi.php @@ -73,10 +73,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -125,10 +128,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -177,10 +183,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -232,18 +241,20 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'string'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'string'); + return $responseObject; } /** @@ -285,10 +296,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -342,18 +356,20 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); if(! $response) { return null; } - $responseObject = $this->apiClient->deserialize($response, - 'User'); - return $responseObject; + $responseObject = $this->apiClient->deserialize($response,'User'); + return $responseObject; } /** @@ -410,10 +426,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } @@ -467,10 +486,13 @@ class UserApi { $httpBody = $formParams; } + // authentication setting, if any + $authSettings = array(); + // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, $queryParams, $httpBody, - $headerParams); + $headerParams, $authSettings); } From 06c7a6a10932edab1ce7cba502621c409aa45f02 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 May 2015 17:13:01 +0800 Subject: [PATCH 59/75] add todo for oauth, support multiple api key --- .../codegen/languages/PhpClientCodegen.java | 1 + .../src/main/resources/php/APIClient.mustache | 5 ++- .../main/resources/php/configuration.mustache | 36 +++++++++++++++++++ .../src/test/resources/2_0/petstore.json | 8 +++++ .../php/SwaggerClient-php/lib/APIClient.php | 12 +++++-- .../SwaggerClient-php/lib/Configuration.php | 36 +++++++++++++++++++ .../php/SwaggerClient-php/lib/StoreApi.php | 2 +- 7 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 modules/swagger-codegen/src/main/resources/php/configuration.mustache create mode 100644 samples/client/petstore/php/SwaggerClient-php/lib/Configuration.php diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java index 48d4a86b09d..55d358154f8 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/PhpClientCodegen.java @@ -84,6 +84,7 @@ public class PhpClientCodegen extends DefaultCodegen implements CodegenConfig { typeMapping.put("list", "array"); supportingFiles.add(new SupportingFile("composer.mustache", packagePath, "composer.json")); + supportingFiles.add(new SupportingFile("configuration.mustache", packagePath + "/lib", "Configuration.php")); supportingFiles.add(new SupportingFile("APIClient.mustache", packagePath + "/lib", "APIClient.php")); supportingFiles.add(new SupportingFile("APIClientException.mustache", packagePath + "/lib", "APIClientException.php")); supportingFiles.add(new SupportingFile("require.mustache", packagePath, invokerPackage + ".php")); diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index bb43e7bdc4b..e1de6566b17 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -68,6 +68,8 @@ class APIClient { } /** + * update hearder and query param based on authentication setting + * * @param array $headerParams * @param array $queryParams * @param array $authSettings @@ -83,7 +85,8 @@ class APIClient { switch($auth) { {{#authMethods}} case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = Configuration::$api_key;{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = Configuration::$api_key;{{/isKeyInQuery}}{{#isBasic}}$headerParams['Authorization'] = base64_encode(Configuraiton::$username.":"Configuration::$password){{/isBasic}}{{/isApiKey}} + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = Configuration::$apiKey['{{keyParamName}}'];{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = Configuration::$apiKey['{{keyParamName}}'];{{/isKeyInQuery}}{{#isBasic}}$headerParams['Authorization'] = base64_encode(Configuraiton::$username.":"Configuration::$password){{/isBasic}}{{/isApiKey}} + {{#isOAuth}}#TODO support oauth{{/isOAuth}} break; {{/authMethods}} } diff --git a/modules/swagger-codegen/src/main/resources/php/configuration.mustache b/modules/swagger-codegen/src/main/resources/php/configuration.mustache new file mode 100644 index 00000000000..9af553702ae --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/php/configuration.mustache @@ -0,0 +1,36 @@ +apiClient->callAPI($resourcePath, $method, From 20439e646f4c06212582e94931cf2f09488944a0 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 May 2015 18:25:35 +0800 Subject: [PATCH 60/75] add test case and prefix support --- .../src/main/resources/php/APIClient.mustache | 25 +++++++++++-- .../php/SwaggerClient-php/lib/APIClient.php | 37 ++++++++++++++----- .../SwaggerClient-php/tests/PetApiTest.php | 30 +++++++++++++++ 3 files changed, 78 insertions(+), 14 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index e1de6566b17..573b3183f51 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -67,6 +67,19 @@ class APIClient { $this->curl_timeout = $seconds; } + /** + * Get API key (with prefix if set) + * @param string key name + * @return string + */ + public function getApiKeyWithPrefix($apiKey) { + if (Configuration::$apiKeyPrefix[$apiKey]) { + return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; + } else { + return Configuration::$apiKey[$apiKey]; + } + } + /** * update hearder and query param based on authentication setting * @@ -85,15 +98,16 @@ class APIClient { switch($auth) { {{#authMethods}} case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = Configuration::$apiKey['{{keyParamName}}'];{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = Configuration::$apiKey['{{keyParamName}}'];{{/isKeyInQuery}}{{#isBasic}}$headerParams['Authorization'] = base64_encode(Configuraiton::$username.":"Configuration::$password){{/isBasic}}{{/isApiKey}} - {{#isOAuth}}#TODO support oauth{{/isOAuth}} - break; + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{#isBasic}}$headerParams['Authorization'] = base64_encode(Configuraiton::$username.":"Configuration::$password){{/isBasic}}{{/isApiKey}} + {{#isOAuth}}//TODO support oauth{{/isOAuth}} + break; {{/authMethods}} + default: + //TODO show warning about security definition not found } } } - /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -107,6 +121,9 @@ class APIClient { $headers = array(); + # determine authentication setting + $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); + # Allow API key from $headerParams to override default $added_api_key = False; if ($headerParams != null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d6b74f610e2..fed11b95450 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -67,6 +67,19 @@ class APIClient { $this->curl_timeout = $seconds; } + /** + * Get API key (with prefix if set) + * @param string key name + * @return string + */ + public function getApiKeyWithPrefix($apiKey) { + if (Configuration::$apiKeyPrefix[$apiKey]) { + return Configuration::$apiKeyPrefix[$apiKey]." ".Configuration::$apiKey[$apiKey]; + } else { + return Configuration::$apiKey[$apiKey]; + } + } + /** * update hearder and query param based on authentication setting * @@ -85,25 +98,26 @@ class APIClient { switch($auth) { case 'api_key': - $headerParams['api_key'] = Configuration::$apiKey['api_key']; - - break; + $headerParams['api_key'] = $this->getApiKeyWithPrefix('api_key'); + + break; case 'api_secret': - $queryParams['api_secret'] = Configuration::$apiKey['api_secret']; - - break; + $queryParams['api_secret'] = $this->getApiKeyWithPrefix('api_secret'); + + break; case 'petstore_auth': - - #TODO support oauth - break; + + //TODO support oauth + break; + default: + //TODO show warning about security definition not found } } } - /** * @param string $resourcePath path to method endpoint * @param string $method method to call @@ -117,6 +131,9 @@ class APIClient { $headers = array(); + # determine authentication setting + $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); + # Allow API key from $headerParams to override default $added_api_key = False; if ($headerParams != null) { diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index d2d398ae140..fe5ed3a9ae2 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -31,6 +31,36 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $add_response = $pet_api->addPet($new_pet); } + public function testConfiguration() + { + $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + SwaggerClient\Configuration::$apiKey['api_key'] = '123456'; + $headerParams = array('test1' => 'value1'); + $queryParams = array('test2' => 'value2'); + $authSettings = array('api_key', 'unknown'); + + # test prefix + SwaggerClient\Configuration::$apiKeyPrefix['api_key'] = 'PREFIX'; + $this->assertSame('PREFIX', SwaggerClient\Configuration::$apiKeyPrefix['api_key']); + + # update parameters based on auth setting + $api_client->updateParamsForAuth($headerParams, $queryParams, $authSettings); + + # test api key + $this->assertSame($headerParams['test1'], 'value1'); + $this->assertSame($headerParams['api_key'], 'PREFIX 123456'); + $this->assertSame($queryParams['test2'], 'value2'); + + # test http basic auth + SwaggerClient\Configuration::$username = 'test_username'; + SwaggerClient\Configuration::$password = 'test_password'; + $this->assertSame('test_username', SwaggerClient\Configuration::$username); + $this->assertSame('test_password', SwaggerClient\Configuration::$password); + + + + } + // test getPetById with a Pet object (id 10005) public function testGetPetById() { From 9a1dedbe7649b9da98c51027bee74c459ad694dc Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 May 2015 18:43:34 +0800 Subject: [PATCH 61/75] add test case (getPetbyId), remove old authenetication (only supports header) --- .../src/main/resources/php/APIClient.mustache | 22 +++++++------------ .../php/SwaggerClient-php/lib/APIClient.php | 22 +++++++------------ .../SwaggerClient-php/tests/PetApiTest.php | 3 +-- 3 files changed, 17 insertions(+), 30 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 573b3183f51..9f07b721d1e 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -36,13 +36,14 @@ class APIClient { protected $user_agent = "PHP-Swagger"; /** - * @param string $host the address of the API server - * @param string $headerName a header to pass on requests + * @param string $host Base url of the API server (optional) */ - function __construct($host, $headerName = null, $headerValue = null) { - $this->host = $host; - $this->headerName = $headerName; - $this->headerValue = $headerValue; + function __construct($host = null) { + if ($host == null) { + $this->host = '{{basePath}}'; + } else { + $this->host = $host; + } } /** @@ -124,19 +125,12 @@ class APIClient { # determine authentication setting $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - # Allow API key from $headerParams to override default - $added_api_key = False; + # construct the http header if ($headerParams != null) { foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; - if ($key == $this->headerName) { - $added_api_key = True; - } } } - if (! $added_api_key && $this->headerName != null) { - $headers[] = $this->headerName . ": " . $this->headerValue; - } // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index fed11b95450..9f7ee55e693 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -36,13 +36,14 @@ class APIClient { protected $user_agent = "PHP-Swagger"; /** - * @param string $host the address of the API server - * @param string $headerName a header to pass on requests + * @param string $host Base url of the API server (optional) */ - function __construct($host, $headerName = null, $headerValue = null) { - $this->host = $host; - $this->headerName = $headerName; - $this->headerValue = $headerValue; + function __construct($host = null) { + if ($host == null) { + $this->host = 'http://petstore.swagger.io/v2'; + } else { + $this->host = $host; + } } /** @@ -134,19 +135,12 @@ class APIClient { # determine authentication setting $this->updateParamsForAuth($headerParams, $queryParams, $authSettings); - # Allow API key from $headerParams to override default - $added_api_key = False; + # construct the http header if ($headerParams != null) { foreach ($headerParams as $key => $val) { $headers[] = "$key: $val"; - if ($key == $this->headerName) { - $added_api_key = True; - } } } - if (! $added_api_key && $this->headerName != null) { - $headers[] = $this->headerName . ": " . $this->headerValue; - } // form data if ($postData and in_array('Content-Type: application/x-www-form-urlencoded', $headers)) { diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index fe5ed3a9ae2..9dd4042f3e0 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -57,8 +57,6 @@ class PetApiTest extends \PHPUnit_Framework_TestCase $this->assertSame('test_username', SwaggerClient\Configuration::$username); $this->assertSame('test_password', SwaggerClient\Configuration::$password); - - } // test getPetById with a Pet object (id 10005) @@ -66,6 +64,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { // initialize the API client $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + SwaggerClient\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); // return Pet (model) From 6e13403a371d140d28cd89e1e39d5883a2b9f001 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 May 2015 21:55:16 +0800 Subject: [PATCH 62/75] fix http basic auth, add test cases for new api client without host --- .../src/main/resources/php/APIClient.mustache | 2 +- .../swagger-codegen/src/test/resources/2_0/petstore.json | 8 -------- .../petstore/php/SwaggerClient-php/lib/APIClient.php | 5 ----- .../petstore/php/SwaggerClient-php/lib/StoreApi.php | 2 +- .../petstore/php/SwaggerClient-php/tests/PetApiTest.php | 5 +++-- 5 files changed, 5 insertions(+), 17 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 9f07b721d1e..03918b79d76 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -99,7 +99,7 @@ class APIClient { switch($auth) { {{#authMethods}} case '{{name}}': - {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{#isBasic}}$headerParams['Authorization'] = base64_encode(Configuraiton::$username.":"Configuration::$password){{/isBasic}}{{/isApiKey}} + {{#isApiKey}}{{#isKeyInHeader}}$headerParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInHeader}}{{#isKeyInQuery}}$queryParams['{{keyParamName}}'] = $this->getApiKeyWithPrefix('{{keyParamName}}');{{/isKeyInQuery}}{{/isApiKey}}{{#isBasic}}$headerParams['Authorization'] = 'Basic '.base64_encode(Configuration::$username.":".Configuration::$password);{{/isBasic}} {{#isOAuth}}//TODO support oauth{{/isOAuth}} break; {{/authMethods}} diff --git a/modules/swagger-codegen/src/test/resources/2_0/petstore.json b/modules/swagger-codegen/src/test/resources/2_0/petstore.json index 5bc9b83ca0c..b4678fc3ab9 100644 --- a/modules/swagger-codegen/src/test/resources/2_0/petstore.json +++ b/modules/swagger-codegen/src/test/resources/2_0/petstore.json @@ -429,9 +429,6 @@ "security": [ { "api_key": [] - }, - { - "api_secret": [] } ] } @@ -805,11 +802,6 @@ "name": "api_key", "in": "header" }, - "api_secret": { - "type": "apiKey", - "name": "api_secret", - "in": "query" - }, "petstore_auth": { "type": "oauth2", "authorizationUrl": "http://petstore.swagger.io/api/oauth/dialog", diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 9f7ee55e693..84e261b4959 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -103,11 +103,6 @@ class APIClient { break; - case 'api_secret': - $queryParams['api_secret'] = $this->getApiKeyWithPrefix('api_secret'); - - break; - case 'petstore_auth': //TODO support oauth diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php index 2b719114ff6..4012a88fc54 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/StoreApi.php @@ -69,7 +69,7 @@ class StoreApi { } // authentication setting, if any - $authSettings = array('api_key', 'api_secret'); + $authSettings = array('api_key'); // make the API Call $response = $this->apiClient->callAPI($resourcePath, $method, diff --git a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php index 9dd4042f3e0..f920381f646 100644 --- a/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php +++ b/samples/client/petstore/php/SwaggerClient-php/tests/PetApiTest.php @@ -35,6 +35,7 @@ class PetApiTest extends \PHPUnit_Framework_TestCase { $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); SwaggerClient\Configuration::$apiKey['api_key'] = '123456'; + $headerParams = array('test1' => 'value1'); $queryParams = array('test2' => 'value2'); $authSettings = array('api_key', 'unknown'); @@ -62,8 +63,8 @@ class PetApiTest extends \PHPUnit_Framework_TestCase // test getPetById with a Pet object (id 10005) public function testGetPetById() { - // initialize the API client - $api_client = new SwaggerClient\APIClient('http://petstore.swagger.io/v2'); + // initialize the API client without host + $api_client = new SwaggerClient\APIClient(); SwaggerClient\Configuration::$apiKey['api_key'] = '111222333444555'; $pet_id = 10005; // ID of pet that needs to be fetched $pet_api = new SwaggerClient\PetAPI($api_client); From 9ff0d908531cbe91c16de1d70b5bbe859db0f9bf Mon Sep 17 00:00:00 2001 From: geekerzp Date: Wed, 20 May 2015 22:05:34 +0800 Subject: [PATCH 63/75] Updated python models. Overwrite the instance method `__repr__`, make the `pprint` method output properties infos of the models. --- .../src/main/resources/python/model.mustache | 8 ++++++++ .../SwaggerPetstore/models/category.py | 8 ++++++++ .../SwaggerPetstore/models/order.py | 8 ++++++++ .../SwaggerPetstore-python/SwaggerPetstore/models/pet.py | 8 ++++++++ .../SwaggerPetstore-python/SwaggerPetstore/models/tag.py | 8 ++++++++ .../SwaggerPetstore-python/SwaggerPetstore/models/user.py | 8 ++++++++ 6 files changed, 48 insertions(+) diff --git a/modules/swagger-codegen/src/main/resources/python/model.mustache b/modules/swagger-codegen/src/main/resources/python/model.mustache index e46c63df637..6100447bb7c 100644 --- a/modules/swagger-codegen/src/main/resources/python/model.mustache +++ b/modules/swagger-codegen/src/main/resources/python/model.mustache @@ -48,5 +48,13 @@ class {{classname}}(object): {{/description}} self.{{name}} = None # {{{datatype}}} {{/vars}} + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) {{/model}} {{/models}} diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py index 7b41a32a7d7..9ed6a44fa65 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/category.py @@ -52,3 +52,11 @@ class Category(object): self.name = None # str + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py index 84780db3780..528d477ac6e 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/order.py @@ -85,3 +85,11 @@ class Order(object): self.complete = None # bool + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py index 1415d6f8535..b7b2dc69621 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/pet.py @@ -85,3 +85,11 @@ class Pet(object): self.status = None # str + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py index a6ed3083422..f0bade25983 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/tag.py @@ -52,3 +52,11 @@ class Tag(object): self.name = None # str + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py index 8559b331203..59a169fe97b 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/models/user.py @@ -101,3 +101,11 @@ class User(object): self.user_status = None # int + + def __repr__(self): + properties = [] + for p in self.__dict__: + if p != 'swaggerTypes' and p != 'attributeMap': + properties.append('{prop}={val!r}'.format(prop=p, val=self.__dict__[p])) + + return '<{name} {props}>'.format(name=__name__, props=' '.join(properties)) From 4f310cd7b1671a862f7297d8c3f85b75cc999b95 Mon Sep 17 00:00:00 2001 From: wing328 Date: Wed, 20 May 2015 22:13:24 +0800 Subject: [PATCH 64/75] update function comment --- .../src/main/resources/php/APIClient.mustache | 8 ++++---- .../petstore/php/SwaggerClient-php/lib/APIClient.php | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache index 03918b79d76..27bdc5697af 100644 --- a/modules/swagger-codegen/src/main/resources/php/APIClient.mustache +++ b/modules/swagger-codegen/src/main/resources/php/APIClient.mustache @@ -71,7 +71,7 @@ class APIClient { /** * Get API key (with prefix if set) * @param string key name - * @return string + * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { if (Configuration::$apiKeyPrefix[$apiKey]) { @@ -84,9 +84,9 @@ class APIClient { /** * update hearder and query param based on authentication setting * - * @param array $headerParams - * @param array $queryParams - * @param array $authSettings + * @param array $headerParams header parameters (by ref) + * @param array $queryParams query parameters (by ref) + * @param array $authSettings array of authentication scheme (e.g ['api_key']) */ public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) { diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index 84e261b4959..032d1b53a44 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -71,7 +71,7 @@ class APIClient { /** * Get API key (with prefix if set) * @param string key name - * @return string + * @return string API key with the prefix */ public function getApiKeyWithPrefix($apiKey) { if (Configuration::$apiKeyPrefix[$apiKey]) { @@ -84,9 +84,9 @@ class APIClient { /** * update hearder and query param based on authentication setting * - * @param array $headerParams - * @param array $queryParams - * @param array $authSettings + * @param array $headerParams header parameters (by ref) + * @param array $queryParams query parameters (by ref) + * @param array $authSettings array of authentication scheme (e.g ['api_key']) */ public function updateParamsForAuth(&$headerParams, &$queryParams, $authSettings) { From 17d8d14cc86133bc8d71c28338637806c73e7722 Mon Sep 17 00:00:00 2001 From: Ole Lensmar Date: Wed, 20 May 2015 16:49:50 -0600 Subject: [PATCH 65/75] defaulted sources to go to src/gen/main and added possibility to set impl folder via system property at command-line --- .../wordnik/swagger/codegen/cmd/Generate.java | 17 +++++++++ .../codegen/languages/JaxRSServerCodegen.java | 36 +++++++++++++------ .../src/main/resources/JavaJaxRS/pom.mustache | 19 ++++++++++ 3 files changed, 61 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen-cli/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 index 0e88a947b47..47449d84286 100644 --- a/modules/swagger-codegen-cli/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 @@ -54,10 +54,16 @@ public class Generate implements Runnable { "Pass in a URL-encoded string of name:header with a comma separating multiple values") private String auth; + @Option( name= {"-D"}, title = "system properties", description = "sets specified system properties in " + + "the format of name=value,name=value") + private String systemProperties; + @Override public void run() { verbosed(verbose); + setSystemProperties(); + ClientOptInput input = new ClientOptInput(); if (isNotEmpty(auth)) { @@ -77,6 +83,17 @@ public class Generate implements Runnable { new DefaultGenerator().opts(input.opts(new ClientOpts()).swagger(swagger)).generate(); } + private void setSystemProperties() { + if( systemProperties != null && systemProperties.length() > 0 ){ + for( String property : systemProperties.split(",")) { + int ix = property.indexOf('='); + if( ix > 0 && ix < property.length()-1 ){ + System.setProperty( property.substring(0, ix), property.substring(ix+1) ); + } + } + } + } + /** * If true parameter, adds system properties which enables debug mode in generator * @param verbose - if true, enables debug mode diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java index f4f16ca63f9..0bc8097d671 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/languages/JaxRSServerCodegen.java @@ -1,8 +1,6 @@ package com.wordnik.swagger.codegen.languages; import com.wordnik.swagger.models.Operation; -import com.wordnik.swagger.models.Path; -import com.wordnik.swagger.util.Json; import com.wordnik.swagger.codegen.*; import com.wordnik.swagger.models.properties.*; @@ -14,7 +12,6 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf protected String groupId = "io.swagger"; protected String artifactId = "swagger-jaxrs-server"; protected String artifactVersion = "1.0.0"; - protected String sourceFolder = "src/main/java"; protected String title = "Swagger Server"; public CodegenType getTag() { @@ -32,7 +29,9 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf public JaxRSServerCodegen() { super(); - outputFolder = "generated-code/javaJaxRS"; + sourceFolder = "src/gen/java"; + + outputFolder = System.getProperty( "swagger.codegen.jaxrs.genfolder", "generated-code/javaJaxRS" ); modelTemplateFiles.put("model.mustache", ".java"); apiTemplateFiles.put("api.mustache", ".java"); apiTemplateFiles.put("apiService.mustache", ".java"); @@ -40,8 +39,8 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf apiTemplateFiles.put("apiServiceFactory.mustache", ".java"); templateDir = "JavaJaxRS"; - apiPackage = "io.swagger.api"; - modelPackage = "io.swagger.model"; + apiPackage = System.getProperty( "swagger.codegen.jaxrs.apipackage", "io.swagger.api") ; + modelPackage = System.getProperty( "swagger.codegen.jaxrs.modelpackage", "io.swagger.model" ); additionalProperties.put("invokerPackage", invokerPackage); additionalProperties.put("groupId", groupId); @@ -158,20 +157,35 @@ public class JaxRSServerCodegen extends JavaClientCodegen implements CodegenConf String result = super.apiFilename(templateName, tag); if( templateName.endsWith( "Impl.mustache")){ - int ix = result.lastIndexOf( '/' ); - result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java"; - } else if( templateName.endsWith( "Service.mustache")){ - int ix = result.lastIndexOf( '.' ); - result = result.substring( 0, ix ) + "Service.java"; + int ix = result.lastIndexOf( '/' ); + result = result.substring( 0, ix ) + "/impl" + result.substring( ix, result.length()-5 ) + "ServiceImpl.java"; + + String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); + if( output != null ){ + result = result.replace( apiFileFolder(), implFileFolder(output)); + } } else if( templateName.endsWith( "Factory.mustache")){ int ix = result.lastIndexOf( '/' ); result = result.substring( 0, ix ) + "/factories" + result.substring( ix, result.length()-5 ) + "ServiceFactory.java"; + + String output = System.getProperty( "swagger.codegen.jaxrs.impl.source" ); + if( output != null ){ + result = result.replace( apiFileFolder(), implFileFolder(output)); + } + } + else if( templateName.endsWith( "Service.mustache")) { + int ix = result.lastIndexOf('.'); + result = result.substring(0, ix) + "Service.java"; } return result; } + private String implFileFolder(String output) { + return outputFolder + "/" + output + "/" + apiPackage().replace('.', File.separatorChar); + } + public boolean shouldOverwrite( String filename ){ return !filename.endsWith( "ServiceImpl.java") && !filename.endsWith( "ServiceFactory.java"); diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 1bd168af747..bf2055bb133 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -62,6 +62,25 @@
+ + org.codehaus.mojo + build-helper-maven-plugin + 1.9.1 + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + +
From 05268c27425103b68f6d61840ecabb34e58af1d1 Mon Sep 17 00:00:00 2001 From: Ole Lensmar Date: Wed, 20 May 2015 16:50:26 -0600 Subject: [PATCH 66/75] added system property for setting impl folder --- bin/jaxrs-petstore-server.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/jaxrs-petstore-server.sh b/bin/jaxrs-petstore-server.sh index 2dd4fc03b38..91a418d6f9a 100755 --- a/bin/jaxrs-petstore-server.sh +++ b/bin/jaxrs-petstore-server.sh @@ -26,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="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs" +ags="$@ generate -t modules/swagger-codegen/src/main/resources/JavaJaxRS -i modules/swagger-codegen/src/test/resources/2_0/petstore.json -l jaxrs -o samples/server/petstore/jaxrs -Dswagger.codegen.jaxrs.impl.source=src/main/java" java $JAVA_OPTS -jar $executable $ags From 713e7a658404d2fb1b16e7440a8a3074d5de4738 Mon Sep 17 00:00:00 2001 From: Ole Lensmar Date: Wed, 20 May 2015 18:06:37 -0600 Subject: [PATCH 67/75] updated core dependency version to 1.5.2-M2 with related fixes --- .../wordnik/swagger/codegen/CodegenProperty.java | 5 ++++- .../wordnik/swagger/codegen/DefaultCodegen.java | 4 ++-- .../codegen/examples/ExampleGenerator.java | 4 ++-- pom.xml | 15 +-------------- 4 files changed, 9 insertions(+), 19 deletions(-) diff --git a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java index b00c962ba6b..921ca90f189 100644 --- a/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/com/wordnik/swagger/codegen/CodegenProperty.java @@ -16,7 +16,10 @@ public class CodegenProperty { public String example; public String jsonSchema; - public Double minimum, maximum, exclusiveMinimum, exclusiveMaximum; + public Double minimum; + public Double maximum; + public Boolean exclusiveMinimum; + public Boolean exclusiveMaximum; public Boolean hasMore = null, required = null, secondaryParam = null; public Boolean isPrimitiveType, isContainer, isNotContainer; public boolean isEnum; 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 6f51374c536..f9c304f794a 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 @@ -1024,13 +1024,13 @@ public class DefaultCodegen { return secs; } - protected List> toExamples(Map examples) { + protected List> toExamples(Map examples) { if(examples == null) return null; List> output = new ArrayList>(); for(String key: examples.keySet()) { - String value = examples.get(key); + String value = String.valueOf(examples.get(key)); Map kv = new HashMap(); kv.put("contentType", key); 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 80063625440..b0fbf34a07f 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 @@ -22,7 +22,7 @@ public class ExampleGenerator { this.examples = examples; } - public List> generate(Map examples, List mediaTypes, Property property) { + public List> generate(Map examples, List mediaTypes, Property property) { List> output = new ArrayList>(); Set processedModels = new HashSet(); if(examples == null ) { @@ -54,7 +54,7 @@ public class ExampleGenerator { } else { for(String key: examples.keySet()) { - String value = examples.get(key); + String value = String.valueOf(examples.get(key)); Map kv = new HashMap(); kv.put("contentType", key); diff --git a/pom.xml b/pom.xml index e28a46bb442..b7c837b42e5 100644 --- a/pom.xml +++ b/pom.xml @@ -302,18 +302,6 @@ samples/client/petstore/java - - scala-client - - - env - scala - - - - samples/client/petstore/scala - - objc-client @@ -373,7 +361,6 @@ samples/client/petstore/android-java samples/client/petstore/java - samples/client/petstore/scala samples/server/petstore/jaxrs samples/server/petstore/spring-mvc samples/client/petstore/objc @@ -453,7 +440,7 @@ 1.0.6-SNAPSHOT 2.10.4 2.3.4 - 1.5.1-M2 + 1.5.2-M2 2.1.4 2.3 1.2 From efb40e149fc96e61767fecb3b389d5c8c3947130 Mon Sep 17 00:00:00 2001 From: Ole Lensmar Date: Wed, 20 May 2015 18:23:44 -0600 Subject: [PATCH 68/75] brought back scala tests --- pom.xml | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/pom.xml b/pom.xml index b7c837b42e5..64131870bbe 100644 --- a/pom.xml +++ b/pom.xml @@ -302,6 +302,18 @@ samples/client/petstore/java + + scala-client + + + env + scala + + + + samples/client/petstore/scala + + objc-client @@ -361,6 +373,7 @@ samples/client/petstore/android-java samples/client/petstore/java + samples/client/petstore/scala samples/server/petstore/jaxrs samples/server/petstore/spring-mvc samples/client/petstore/objc From e6efcdb6af009ae839f9d074501d5787adef0013 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 20 May 2015 21:39:09 -0700 Subject: [PATCH 69/75] added files, updated parser version --- .gitignore | 12 +- pom.xml | 2 +- .../scala/io/swagger/client/ApiInvoker.scala | 195 ++++++++ .../io/swagger/client/api/AccountApi.scala | 201 ++++++++ .../scala/io/swagger/client/api/WordApi.scala | 438 ++++++++++++++++++ .../io/swagger/client/api/WordListApi.scala | 245 ++++++++++ .../io/swagger/client/api/WordListsApi.scala | 57 +++ .../io/swagger/client/api/WordsApi.scala | 238 ++++++++++ .../swagger/client/model/ApiTokenStatus.scala | 13 + .../io/swagger/client/model/AudioFile.scala | 22 + .../io/swagger/client/model/AudioType.scala | 9 + .../client/model/AuthenticationToken.scala | 10 + .../io/swagger/client/model/Bigram.scala | 12 + .../io/swagger/client/model/Category.scala | 9 + .../io/swagger/client/model/Citation.scala | 9 + .../client/model/ContentProvider.scala | 9 + .../io/swagger/client/model/Definition.scala | 29 ++ .../model/DefinitionSearchResults.scala | 10 + .../io/swagger/client/model/Example.scala | 22 + .../client/model/ExampleSearchResults.scala | 11 + .../swagger/client/model/ExampleUsage.scala | 8 + .../scala/io/swagger/client/model/Facet.scala | 10 + .../io/swagger/client/model/FacetValue.scala | 9 + .../io/swagger/client/model/Frequency.scala | 9 + .../client/model/FrequencySummary.scala | 13 + .../scala/io/swagger/client/model/Label.scala | 9 + .../scala/io/swagger/client/model/Note.scala | 11 + .../swagger/client/model/PartOfSpeech.scala | 12 + .../io/swagger/client/model/Related.scala | 14 + .../scala/io/swagger/client/model/Root.scala | 11 + .../io/swagger/client/model/ScoredWord.scala | 18 + .../io/swagger/client/model/Sentence.scala | 14 + .../client/model/SimpleDefinition.scala | 11 + .../swagger/client/model/SimpleExample.scala | 11 + .../io/swagger/client/model/StringValue.scala | 8 + .../io/swagger/client/model/Syllable.scala | 10 + .../io/swagger/client/model/TextPron.scala | 10 + .../scala/io/swagger/client/model/User.scala | 15 + .../io/swagger/client/model/WordList.scala | 19 + .../swagger/client/model/WordListWord.scala | 15 + .../io/swagger/client/model/WordObject.scala | 13 + .../swagger/client/model/WordOfTheDay.scala | 23 + .../client/model/WordSearchResult.scala | 10 + .../client/model/WordSearchResults.scala | 10 + 44 files changed, 1844 insertions(+), 2 deletions(-) create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala create mode 100644 samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala diff --git a/.gitignore b/.gitignore index 210834c6a85..8f160116e5b 100644 --- a/.gitignore +++ b/.gitignore @@ -22,7 +22,17 @@ samples/server-generator/scalatra/output samples/server-generator/node/output/node_modules samples/server-generator/scalatra/target samples/server-generator/scalatra/output/.history - +samples/client/petstore/qt5cpp/PetStore/moc_* +samples/client/petstore/qt5cpp/PetStore/*.o +samples/client/petstore/objc/PetstoreClient.xcworkspace/xcuserdata +samples/client/petstore/qt5cpp/build-* +samples/client/petstore/qt5cpp/PetStore/PetStore +samples/client/petstore/qt5cpp/PetStore/Makefile +samples/client/petstore/java/hello.txt +samples/client/petstore/android-java/hello.txt +samples/client/petstore/objc/Build +samples/client/petstore/objc/Pods +samples/server/petstore/nodejs/node_modules target .idea .lib diff --git a/pom.xml b/pom.xml index 64131870bbe..6fbb36464f8 100644 --- a/pom.xml +++ b/pom.xml @@ -450,7 +450,7 @@ - 1.0.6-SNAPSHOT + 1.0.7 2.10.4 2.3.4 1.5.2-M2 diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala new file mode 100644 index 00000000000..f4b25de8306 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/ApiInvoker.scala @@ -0,0 +1,195 @@ +package io.swagger.client + +import com.sun.jersey.api.client.Client +import com.sun.jersey.api.client.ClientResponse +import com.sun.jersey.api.client.config.ClientConfig +import com.sun.jersey.api.client.config.DefaultClientConfig +import com.sun.jersey.api.client.filter.LoggingFilter + +import com.sun.jersey.multipart.FormDataMultiPart +import com.sun.jersey.multipart.file.FileDataBodyPart + +import java.io.File +import java.net.URLEncoder +import javax.ws.rs.core.MediaType + +import scala.collection.JavaConverters._ +import scala.collection.mutable.HashMap + +import com.fasterxml.jackson.module.scala.DefaultScalaModule +import com.fasterxml.jackson.datatype.joda.JodaModule +import com.fasterxml.jackson.core.JsonGenerator.Feature +import com.fasterxml.jackson.databind._ +import com.fasterxml.jackson.annotation._ +import com.fasterxml.jackson.databind.annotation.JsonSerialize + +object ScalaJsonUtil { + def getJsonMapper = { + val mapper = new ObjectMapper() + mapper.registerModule(new DefaultScalaModule()) + mapper.registerModule(new JodaModule()); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.setSerializationInclusion(JsonInclude.Include.NON_DEFAULT) + mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY) + mapper + } +} + +class ApiInvoker(val mapper: ObjectMapper = ScalaJsonUtil.getJsonMapper, + httpHeaders: HashMap[String, String] = HashMap(), + hostMap: HashMap[String, Client] = HashMap(), + asyncHttpClient: Boolean = false, + authScheme: String = "", + authPreemptive: Boolean = false) { + + var defaultHeaders: HashMap[String, String] = httpHeaders + + def escape(value: String): String = { + URLEncoder.encode(value, "utf-8").replaceAll("\\+", "%20") + } + + def escape(value: Long): String = value.toString + def escape(value: Double): String = value.toString + def escape(value: Float): String = value.toString + + def deserialize(json: String, containerType: String, cls: Class[_]) = { + if (cls == classOf[String]) { + json match { + case s: String => { + if (s.startsWith("\"") && s.endsWith("\"") && s.length > 1) s.substring(1, s.length - 2) + else s + } + case _ => null + } + } else { + containerType.toLowerCase match { + case "array" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case "list" => { + val typeInfo = mapper.getTypeFactory().constructCollectionType(classOf[java.util.List[_]], cls) + val response = mapper.readValue(json, typeInfo).asInstanceOf[java.util.List[_]] + response.asScala.toList + } + case _ => { + json match { + case e: String if ("\"\"" == e) => null + case _ => mapper.readValue(json, cls) + } + } + } + } + } + + def serialize(obj: AnyRef): String = { + if (obj != null) { + obj match { + case e: List[_] => mapper.writeValueAsString(obj.asInstanceOf[List[_]].asJava) + case _ => mapper.writeValueAsString(obj) + } + } else null + } + + def invokeApi(host: String, path: String, method: String, queryParams: Map[String, String], body: AnyRef, headerParams: Map[String, String], contentType: String): String = { + val client = getClient(host) + + val querystring = queryParams.filter(k => k._2 != null).map(k => (escape(k._1) + "=" + escape(k._2))).mkString("?", "&", "") + val builder = client.resource(host + path + querystring).accept(contentType) + headerParams.map(p => builder.header(p._1, p._2)) + defaultHeaders.map(p => { + headerParams.contains(p._1) match { + case true => // override default with supplied header + case false => if (p._2 != null) builder.header(p._1, p._2) + } + }) + + val response: ClientResponse = method match { + case "GET" => { + builder.get(classOf[ClientResponse]).asInstanceOf[ClientResponse] + } + case "POST" => { + if(body != null && body.isInstanceOf[File]) { + val file = body.asInstanceOf[File] + val form = new FormDataMultiPart() + form.field("filename", file.getName()) + form.bodyPart(new FileDataBodyPart("file", file, MediaType.MULTIPART_FORM_DATA_TYPE)) + builder.post(classOf[ClientResponse], form) + } + else { + if(body == null) builder.post(classOf[ClientResponse], serialize(body)) + else builder.`type`(contentType).post(classOf[ClientResponse], serialize(body)) + } + } + case "PUT" => { + if(body == null) builder.put(classOf[ClientResponse], null) + else builder.`type`(contentType).put(classOf[ClientResponse], serialize(body)) + } + case "DELETE" => { + builder.delete(classOf[ClientResponse]) + } + case _ => null + } + response.getClientResponseStatus().getStatusCode() match { + case 204 => "" + case code: Int if (Range(200, 299).contains(code)) => { + response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "" + } + } + case _ => { + val entity = response.hasEntity() match { + case true => response.getEntity(classOf[String]) + case false => "no data" + } + throw new ApiException( + response.getClientResponseStatus().getStatusCode(), + entity) + } + } + } + + def getClient(host: String): Client = { + hostMap.contains(host) match { + case true => hostMap(host) + case false => { + val client = newClient(host) + // client.addFilter(new LoggingFilter()) + hostMap += host -> client + client + } + } + } + + def newClient(host: String): Client = asyncHttpClient match { + case true => { + import org.sonatype.spice.jersey.client.ahc.config.DefaultAhcConfig + import org.sonatype.spice.jersey.client.ahc.AhcHttpClient + import com.ning.http.client.Realm + + val config: DefaultAhcConfig = new DefaultAhcConfig() + if (!authScheme.isEmpty) { + val authSchemeEnum = Realm.AuthScheme.valueOf(authScheme) + config.getAsyncHttpClientConfigBuilder + .setRealm(new Realm.RealmBuilder().setScheme(authSchemeEnum) + .setUsePreemptiveAuth(authPreemptive).build) + } + AhcHttpClient.create(config) + } + case _ => Client.create() + } +} + +object ApiInvoker extends ApiInvoker(mapper = ScalaJsonUtil.getJsonMapper, + httpHeaders = HashMap(), + hostMap = HashMap(), + asyncHttpClient = false, + authScheme = "", + authPreemptive = false) + +class ApiException(val code: Int, msg: String) extends RuntimeException(msg) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala new file mode 100644 index 00000000000..3203f846f27 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/AccountApi.scala @@ -0,0 +1,201 @@ +package io.swagger.client.api + +import io.swagger.client.model.ApiTokenStatus +import io.swagger.client.model.AuthenticationToken +import io.swagger.client.model.User +import io.swagger.client.model.WordList +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class AccountApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getApiTokenStatus (api_key: String) : Option[ApiTokenStatus] = { + // create path and map variables + val path = "/account.json/apiTokenStatus".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "api_key" -> api_key + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[ApiTokenStatus]).asInstanceOf[ApiTokenStatus]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def authenticate (username: String, password: String) : Option[AuthenticationToken] = { + // create path and map variables + val path = "/account.json/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(password) != "null") queryParams += "password" -> password.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[AuthenticationToken]).asInstanceOf[AuthenticationToken]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def authenticatePost (username: String, body: String) : Option[AuthenticationToken] = { + // create path and map variables + val path = "/account.json/authenticate/{username}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "username" + "\\}",apiInvoker.escape(username)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[AuthenticationToken]).asInstanceOf[AuthenticationToken]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getLoggedInUser (auth_token: String) : Option[User] = { + // create path and map variables + val path = "/account.json/user".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[User]).asInstanceOf[User]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordListsForLoggedInUser (auth_token: String, skip: Integer, limit: Integer) : Option[List[WordList]] = { + // create path and map variables + val path = "/account.json/wordLists".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[WordList]).asInstanceOf[List[WordList]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala new file mode 100644 index 00000000000..b6f076a4b43 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordApi.scala @@ -0,0 +1,438 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.AudioFile +import io.swagger.client.model.Definition +import io.swagger.client.model.FrequencySummary +import io.swagger.client.model.Bigram +import io.swagger.client.model.Example +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getWord (word: String, useCanonical: String, includeSuggestions: String) : Option[WordObject] = { + // create path and map variables + val path = "/word.json/{word}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(includeSuggestions) != "null") queryParams += "includeSuggestions" -> includeSuggestions.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordObject]).asInstanceOf[WordObject]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getAudio (word: String, useCanonical: String, limit: Integer) : Option[List[AudioFile]] = { + // create path and map variables + val path = "/word.json/{word}/audio".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[AudioFile]).asInstanceOf[List[AudioFile]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getDefinitions (word: String, limit: Integer, partOfSpeech: String, includeRelated: String, sourceDictionaries: List[String], useCanonical: String, includeTags: String) : Option[List[Definition]] = { + // create path and map variables + val path = "/word.json/{word}/definitions".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + if(String.valueOf(partOfSpeech) != "null") queryParams += "partOfSpeech" -> partOfSpeech.toString + if(String.valueOf(includeRelated) != "null") queryParams += "includeRelated" -> includeRelated.toString + if(String.valueOf(sourceDictionaries) != "null") queryParams += "sourceDictionaries" -> sourceDictionaries.toString + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(includeTags) != "null") queryParams += "includeTags" -> includeTags.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[Definition]).asInstanceOf[List[Definition]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getEtymologies (word: String, useCanonical: String) : Option[List[String]] = { + // create path and map variables + val path = "/word.json/{word}/etymologies".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[String]).asInstanceOf[List[String]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getExamples (word: String, includeDuplicates: String, useCanonical: String, skip: Integer, limit: Integer) = { + // create path and map variables + val path = "/word.json/{word}/examples".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(includeDuplicates) != "null") queryParams += "includeDuplicates" -> includeDuplicates.toString + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordFrequency (word: String, useCanonical: String, startYear: Integer, endYear: Integer) : Option[FrequencySummary] = { + // create path and map variables + val path = "/word.json/{word}/frequency".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(startYear) != "null") queryParams += "startYear" -> startYear.toString + if(String.valueOf(endYear) != "null") queryParams += "endYear" -> endYear.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[FrequencySummary]).asInstanceOf[FrequencySummary]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getHyphenation (word: String, useCanonical: String, sourceDictionary: String, limit: Integer) = { + // create path and map variables + val path = "/word.json/{word}/hyphenation".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(sourceDictionary) != "null") queryParams += "sourceDictionary" -> sourceDictionary.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getPhrases (word: String, limit: Integer, wlmi: Integer, useCanonical: String) : Option[List[Bigram]] = { + // create path and map variables + val path = "/word.json/{word}/phrases".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + if(String.valueOf(wlmi) != "null") queryParams += "wlmi" -> wlmi.toString + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "array", classOf[Bigram]).asInstanceOf[List[Bigram]]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getTextPronunciations (word: String, useCanonical: String, sourceDictionary: String, typeFormat: String, limit: Integer) = { + // create path and map variables + val path = "/word.json/{word}/pronunciations".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(sourceDictionary) != "null") queryParams += "sourceDictionary" -> sourceDictionary.toString + if(String.valueOf(typeFormat) != "null") queryParams += "typeFormat" -> typeFormat.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getRelatedWords (word: String, useCanonical: String, relationshipTypes: String, limitPerRelationshipType: Integer) = { + // create path and map variables + val path = "/word.json/{word}/relatedWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + if(String.valueOf(relationshipTypes) != "null") queryParams += "relationshipTypes" -> relationshipTypes.toString + if(String.valueOf(limitPerRelationshipType) != "null") queryParams += "limitPerRelationshipType" -> limitPerRelationshipType.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getTopExample (word: String, useCanonical: String) : Option[Example] = { + // create path and map variables + val path = "/word.json/{word}/topExample".replaceAll("\\{format\\}","json").replaceAll("\\{" + "word" + "\\}",apiInvoker.escape(word)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(useCanonical) != "null") queryParams += "useCanonical" -> useCanonical.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[Example]).asInstanceOf[Example]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala new file mode 100644 index 00000000000..958bc234ab3 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListApi.scala @@ -0,0 +1,245 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.model.StringValue +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordListApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getWordListByPermalink (permalink: String, auth_token: String) : Option[WordList] = { + // create path and map variables + val path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordList]).asInstanceOf[WordList]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def updateWordList (permalink: String, body: WordList, auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "PUT", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def deleteWordList (permalink: String, auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "DELETE", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def deleteWordsFromWordList (permalink: String, body: List[StringValue], auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}/deleteWords".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordListWords (permalink: String, sortBy: String, sortOrder: String, skip: Integer, limit: Integer, auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(sortBy) != "null") queryParams += "sortBy" -> sortBy.toString + if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def addWordsToWordList (permalink: String, body: List[StringValue], auth_token: String) = { + // create path and map variables + val path = "/wordList.json/{permalink}/words".replaceAll("\\{format\\}","json").replaceAll("\\{" + "permalink" + "\\}",apiInvoker.escape(permalink)) + + + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala new file mode 100644 index 00000000000..805f62d4be7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordListsApi.scala @@ -0,0 +1,57 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordList +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordListsApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def createWordList (body: WordList, auth_token: String) : Option[WordList] = { + // create path and map variables + val path = "/wordLists.json".replaceAll("\\{format\\}","json") + + + val contentType = { + if(body != null && body.isInstanceOf[File] ) + "multipart/form-data" + else "application/json" + + + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + + + headerParams += "auth_token" -> auth_token + + + try { + apiInvoker.invokeApi(basePath, path, "POST", queryParams.toMap, body, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordList]).asInstanceOf[WordList]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala new file mode 100644 index 00000000000..6613abb7589 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/api/WordsApi.scala @@ -0,0 +1,238 @@ +package io.swagger.client.api + +import io.swagger.client.model.WordObject +import io.swagger.client.model.DefinitionSearchResults +import io.swagger.client.model.WordSearchResults +import io.swagger.client.model.WordOfTheDay +import io.swagger.client.ApiInvoker +import io.swagger.client.ApiException + +import java.io.File +import java.util.Date + +import scala.collection.mutable.HashMap + +class WordsApi(val defBasePath: String = "https://api.wordnik.com/v4", + defApiInvoker: ApiInvoker = ApiInvoker) { + var basePath = defBasePath + var apiInvoker = defApiInvoker + + def addHeader(key: String, value: String) = apiInvoker.defaultHeaders += key -> value + + + def getRandomWord (hasDictionaryDef: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minDictionaryCount: Integer, maxDictionaryCount: Integer, minLength: Integer, maxLength: Integer) : Option[WordObject] = { + // create path and map variables + val path = "/words.json/randomWord".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(hasDictionaryDef) != "null") queryParams += "hasDictionaryDef" -> hasDictionaryDef.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minDictionaryCount) != "null") queryParams += "minDictionaryCount" -> minDictionaryCount.toString + if(String.valueOf(maxDictionaryCount) != "null") queryParams += "maxDictionaryCount" -> maxDictionaryCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordObject]).asInstanceOf[WordObject]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getRandomWords (hasDictionaryDef: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minDictionaryCount: Integer, maxDictionaryCount: Integer, minLength: Integer, maxLength: Integer, sortBy: String, sortOrder: String, limit: Integer) = { + // create path and map variables + val path = "/words.json/randomWords".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(hasDictionaryDef) != "null") queryParams += "hasDictionaryDef" -> hasDictionaryDef.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minDictionaryCount) != "null") queryParams += "minDictionaryCount" -> minDictionaryCount.toString + if(String.valueOf(maxDictionaryCount) != "null") queryParams += "maxDictionaryCount" -> maxDictionaryCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + if(String.valueOf(sortBy) != "null") queryParams += "sortBy" -> sortBy.toString + if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def reverseDictionary (query: String, findSenseForWord: String, includeSourceDictionaries: String, excludeSourceDictionaries: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minLength: Integer, maxLength: Integer, expandTerms: String, includeTags: String, sortBy: String, sortOrder: String, skip: String, limit: Integer) : Option[DefinitionSearchResults] = { + // create path and map variables + val path = "/words.json/reverseDictionary".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(query) != "null") queryParams += "query" -> query.toString + if(String.valueOf(findSenseForWord) != "null") queryParams += "findSenseForWord" -> findSenseForWord.toString + if(String.valueOf(includeSourceDictionaries) != "null") queryParams += "includeSourceDictionaries" -> includeSourceDictionaries.toString + if(String.valueOf(excludeSourceDictionaries) != "null") queryParams += "excludeSourceDictionaries" -> excludeSourceDictionaries.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + if(String.valueOf(expandTerms) != "null") queryParams += "expandTerms" -> expandTerms.toString + if(String.valueOf(includeTags) != "null") queryParams += "includeTags" -> includeTags.toString + if(String.valueOf(sortBy) != "null") queryParams += "sortBy" -> sortBy.toString + if(String.valueOf(sortOrder) != "null") queryParams += "sortOrder" -> sortOrder.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[DefinitionSearchResults]).asInstanceOf[DefinitionSearchResults]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def searchWords (query: String, caseSensitive: String, includePartOfSpeech: String, excludePartOfSpeech: String, minCorpusCount: Integer, maxCorpusCount: Integer, minDictionaryCount: Integer, maxDictionaryCount: Integer, minLength: Integer, maxLength: Integer, skip: Integer, limit: Integer) : Option[WordSearchResults] = { + // create path and map variables + val path = "/words.json/search/{query}".replaceAll("\\{format\\}","json").replaceAll("\\{" + "query" + "\\}",apiInvoker.escape(query)) + + + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(caseSensitive) != "null") queryParams += "caseSensitive" -> caseSensitive.toString + if(String.valueOf(includePartOfSpeech) != "null") queryParams += "includePartOfSpeech" -> includePartOfSpeech.toString + if(String.valueOf(excludePartOfSpeech) != "null") queryParams += "excludePartOfSpeech" -> excludePartOfSpeech.toString + if(String.valueOf(minCorpusCount) != "null") queryParams += "minCorpusCount" -> minCorpusCount.toString + if(String.valueOf(maxCorpusCount) != "null") queryParams += "maxCorpusCount" -> maxCorpusCount.toString + if(String.valueOf(minDictionaryCount) != "null") queryParams += "minDictionaryCount" -> minDictionaryCount.toString + if(String.valueOf(maxDictionaryCount) != "null") queryParams += "maxDictionaryCount" -> maxDictionaryCount.toString + if(String.valueOf(minLength) != "null") queryParams += "minLength" -> minLength.toString + if(String.valueOf(maxLength) != "null") queryParams += "maxLength" -> maxLength.toString + if(String.valueOf(skip) != "null") queryParams += "skip" -> skip.toString + if(String.valueOf(limit) != "null") queryParams += "limit" -> limit.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordSearchResults]).asInstanceOf[WordSearchResults]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + + def getWordOfTheDay (date: String) : Option[WordOfTheDay] = { + // create path and map variables + val path = "/words.json/wordOfTheDay".replaceAll("\\{format\\}","json") + + + val contentType = { + + "application/json" + } + + // query params + val queryParams = new HashMap[String, String] + val headerParams = new HashMap[String, String] + + + + if(String.valueOf(date) != "null") queryParams += "date" -> date.toString + + + + + try { + apiInvoker.invokeApi(basePath, path, "GET", queryParams.toMap, None, headerParams.toMap, contentType) match { + case s: String => + Some(ApiInvoker.deserialize(s, "", classOf[WordOfTheDay]).asInstanceOf[WordOfTheDay]) + + case _ => None + } + } catch { + case ex: ApiException if ex.code == 404 => None + case ex: ApiException => throw ex + } + } + +} diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala new file mode 100644 index 00000000000..9ec5f7cec64 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ApiTokenStatus.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + + + + +case class ApiTokenStatus ( + valid: Boolean, + token: String, + resetsInMillis: Long, + remainingCalls: Long, + expiresInMillis: Long, + totalRequests: Long) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala new file mode 100644 index 00000000000..6a8355c2078 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioFile.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class AudioFile ( + attributionUrl: String, + commentCount: Integer, + voteCount: Integer, + fileUrl: String, + audioType: String, + id: Long, + duration: Double, + attributionText: String, + createdBy: String, + description: String, + createdAt: DateTime, + voteWeightedAverage: Float, + voteAverage: Float, + word: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala new file mode 100644 index 00000000000..1a4e310481a --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AudioType.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class AudioType ( + id: Integer, + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala new file mode 100644 index 00000000000..80d13cc41a5 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/AuthenticationToken.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class AuthenticationToken ( + token: String, + userId: Long, + userSignature: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala new file mode 100644 index 00000000000..0ecde0290ef --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Bigram.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + + + + +case class Bigram ( + count: Long, + gram2: String, + gram1: String, + wlmi: Double, + mi: Double) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala new file mode 100644 index 00000000000..122411e3ff7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Category.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Category ( + id: Long, + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala new file mode 100644 index 00000000000..a8192a80822 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Citation.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Citation ( + cite: String, + source: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala new file mode 100644 index 00000000000..8638e5ae204 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ContentProvider.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class ContentProvider ( + id: Integer, + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala new file mode 100644 index 00000000000..a4e323ddb29 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Definition.scala @@ -0,0 +1,29 @@ +package io.swagger.client.model + +import io.swagger.client.model.ExampleUsage +import io.swagger.client.model.Note +import io.swagger.client.model.Label +import io.swagger.client.model.Related +import io.swagger.client.model.Citation +import io.swagger.client.model.TextPron + + + +case class Definition ( + extendedText: String, + text: String, + sourceDictionary: String, + citations: List[Citation], + labels: List[Label], + score: Float, + exampleUses: List[ExampleUsage], + attributionUrl: String, + seqString: String, + attributionText: String, + relatedWords: List[Related], + sequence: String, + word: String, + notes: List[Note], + textProns: List[TextPron], + partOfSpeech: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala new file mode 100644 index 00000000000..bf7c430ff10 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/DefinitionSearchResults.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import io.swagger.client.model.Definition + + + +case class DefinitionSearchResults ( + results: List[Definition], + totalResults: Integer) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala new file mode 100644 index 00000000000..7f9544ad5b4 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Example.scala @@ -0,0 +1,22 @@ +package io.swagger.client.model + +import io.swagger.client.model.Sentence +import io.swagger.client.model.ContentProvider +import io.swagger.client.model.ScoredWord + + + +case class Example ( + id: Long, + exampleId: Long, + title: String, + text: String, + score: ScoredWord, + sentence: Sentence, + word: String, + provider: ContentProvider, + year: Integer, + rating: Float, + documentId: Long, + url: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala new file mode 100644 index 00000000000..8d33a90020d --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleSearchResults.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.model.Example +import io.swagger.client.model.Facet + + + +case class ExampleSearchResults ( + facets: List[Facet], + examples: List[Example]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala new file mode 100644 index 00000000000..4e54562515c --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ExampleUsage.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class ExampleUsage ( + text: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala new file mode 100644 index 00000000000..4bea80d58ff --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Facet.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import io.swagger.client.model.FacetValue + + + +case class Facet ( + facetValues: List[FacetValue], + name: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala new file mode 100644 index 00000000000..21ec01a8332 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FacetValue.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class FacetValue ( + count: Long, + value: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala new file mode 100644 index 00000000000..ac1d92e4507 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Frequency.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Frequency ( + count: Long, + year: Integer) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala new file mode 100644 index 00000000000..15c4b15ac12 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/FrequencySummary.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + +import io.swagger.client.model.Frequency + + + +case class FrequencySummary ( + unknownYearCount: Integer, + totalCount: Long, + frequencyString: String, + word: String, + frequency: List[Frequency]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala new file mode 100644 index 00000000000..73644b338f2 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Label.scala @@ -0,0 +1,9 @@ +package io.swagger.client.model + + + + +case class Label ( + text: String, + _type: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala new file mode 100644 index 00000000000..c5424025d3b --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Note.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + + + + +case class Note ( + noteType: String, + appliesTo: List[String], + value: String, + pos: Integer) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala new file mode 100644 index 00000000000..74d1fa926d7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/PartOfSpeech.scala @@ -0,0 +1,12 @@ +package io.swagger.client.model + +import io.swagger.client.model.Category +import io.swagger.client.model.Root + + + +case class PartOfSpeech ( + roots: List[Root], + storageAbbr: List[String], + allCategories: List[Category]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala new file mode 100644 index 00000000000..0207dc96b16 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Related.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + + + + +case class Related ( + label1: String, + relationshipType: String, + label2: String, + label3: String, + words: List[String], + gram: String, + label4: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala new file mode 100644 index 00000000000..9210af25f4d --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Root.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + +import io.swagger.client.model.Category + + + +case class Root ( + id: Long, + name: String, + categories: List[Category]) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala new file mode 100644 index 00000000000..f74fcba41f7 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/ScoredWord.scala @@ -0,0 +1,18 @@ +package io.swagger.client.model + + + + +case class ScoredWord ( + position: Integer, + id: Long, + docTermCount: Integer, + lemma: String, + wordType: String, + score: Float, + sentenceId: Long, + word: String, + stopword: Boolean, + baseWordScore: Double, + partOfSpeech: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala new file mode 100644 index 00000000000..04319cd6029 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Sentence.scala @@ -0,0 +1,14 @@ +package io.swagger.client.model + +import io.swagger.client.model.ScoredWord + + + +case class Sentence ( + hasScoredWords: Boolean, + id: Long, + scoredWords: List[ScoredWord], + display: String, + rating: Integer, + documentMetadataId: Long) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala new file mode 100644 index 00000000000..1071880411c --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleDefinition.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + + + + +case class SimpleDefinition ( + text: String, + source: String, + note: String, + partOfSpeech: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala new file mode 100644 index 00000000000..61e9154acfb --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/SimpleExample.scala @@ -0,0 +1,11 @@ +package io.swagger.client.model + + + + +case class SimpleExample ( + id: Long, + title: String, + text: String, + url: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala new file mode 100644 index 00000000000..1ff8087c817 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/StringValue.scala @@ -0,0 +1,8 @@ +package io.swagger.client.model + + + + +case class StringValue ( + word: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala new file mode 100644 index 00000000000..04ca0f802ab --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/Syllable.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class Syllable ( + text: String, + seq: Integer, + _type: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala new file mode 100644 index 00000000000..582e62b5aa1 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/TextPron.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class TextPron ( + raw: String, + seq: Integer, + rawType: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala new file mode 100644 index 00000000000..4651b6eee71 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/User.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + + + + +case class User ( + id: Long, + username: String, + email: String, + status: Integer, + faceBookId: String, + userName: String, + displayName: String, + password: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala new file mode 100644 index 00000000000..b37ae05661a --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordList.scala @@ -0,0 +1,19 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class WordList ( + id: Long, + permalink: String, + name: String, + createdAt: DateTime, + updatedAt: DateTime, + lastActivityAt: DateTime, + username: String, + userId: Long, + description: String, + numberWordsInList: Long, + _type: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala new file mode 100644 index 00000000000..a28fdd0f181 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordListWord.scala @@ -0,0 +1,15 @@ +package io.swagger.client.model + +import org.joda.time.DateTime + + + +case class WordListWord ( + id: Long, + word: String, + username: String, + userId: Long, + createdAt: DateTime, + numberCommentsOnWord: Long, + numberLists: Long) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala new file mode 100644 index 00000000000..5d3d3a44d7b --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordObject.scala @@ -0,0 +1,13 @@ +package io.swagger.client.model + + + + +case class WordObject ( + id: Long, + word: String, + originalWord: String, + suggestions: List[String], + canonicalForm: String, + vulgar: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala new file mode 100644 index 00000000000..b41e1afc286 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordOfTheDay.scala @@ -0,0 +1,23 @@ +package io.swagger.client.model + +import org.joda.time.DateTime +import io.swagger.client.model.SimpleDefinition +import io.swagger.client.model.ContentProvider +import io.swagger.client.model.SimpleExample + + + +case class WordOfTheDay ( + id: Long, + parentId: String, + category: String, + createdBy: String, + createdAt: DateTime, + contentProvider: ContentProvider, + htmlExtra: String, + word: String, + definitions: List[SimpleDefinition], + examples: List[SimpleExample], + note: String, + publishDate: DateTime) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala new file mode 100644 index 00000000000..4feb0d31190 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResult.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + + + + +case class WordSearchResult ( + count: Long, + lexicality: Double, + word: String) + diff --git a/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala new file mode 100644 index 00000000000..bf46436eef2 --- /dev/null +++ b/samples/client/wordnik/scala/src/main/scala/io/swagger/client/model/WordSearchResults.scala @@ -0,0 +1,10 @@ +package io.swagger.client.model + +import io.swagger.client.model.WordSearchResult + + + +case class WordSearchResults ( + searchResults: List[WordSearchResult], + totalResults: Integer) + From 11dd7784f8d014c9390f06f70f47da66f256ce47 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 20 May 2015 22:20:51 -0700 Subject: [PATCH 70/75] rebuilt --- .../src/main/resources/JavaJaxRS/pom.mustache | 2 +- .../java/io/swagger/client/api/PetApi.java | 8 +- .../java/io/swagger/client/api/PetApi.java | 8 +- .../client/petstore/objc/client/SWGPetApi.m | 8 +- .../php/SwaggerClient-php/lib/APIClient.php | 11 +- .../php/SwaggerClient-php/lib/PetApi.php | 8 +- .../SwaggerPetstore/pet_api.py | 8 +- .../client/petstore/qt5cpp/client/SWGPet.h | 6 +- .../ruby/lib/swagger_client/api/pet_api.rb | 8 +- samples/html/index.html | 149 +++++++++++++++--- samples/server/petstore/jaxrs/pom.xml | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 10 +- .../main/java/io/swagger/api/StoreApi.java | 2 + .../src/main/java/io/swagger/api/UserApi.java | 2 + .../src/main/java/io/swagger/api/PetApi.java | 41 +++-- .../main/java/io/swagger/api/StoreApi.java | 9 +- .../src/main/java/io/swagger/api/UserApi.java | 27 ++-- 17 files changed, 227 insertions(+), 82 deletions(-) diff --git a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache index 1bd168af747..eebdd6f7578 100644 --- a/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/swagger-codegen/src/main/resources/JavaJaxRS/pom.mustache @@ -129,7 +129,7 @@ - 1.5.2-M2-SNAPSHOT + 1.5.2-M2 9.2.9.v20150224 1.13 1.6.3 diff --git a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java index 88fdfdb6980..ebf600d787e 100644 --- a/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/android-java/src/main/java/io/swagger/client/api/PetApi.java @@ -63,7 +63,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -117,7 +117,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -349,7 +349,7 @@ public class PetApi { String[] contentTypes = { - "application/x-www-form-urlencoded", + "application/x-www-form-urlencoded" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -481,7 +481,7 @@ public class PetApi { String[] contentTypes = { - "multipart/form-data", + "multipart/form-data" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; diff --git a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java index b5d6bb70d79..10326d8a2d6 100644 --- a/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java +++ b/samples/client/petstore/java/src/main/java/io/swagger/client/api/PetApi.java @@ -57,7 +57,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -107,7 +107,7 @@ public class PetApi { String[] contentTypes = { - "application/json","application/xml", + "application/json","application/xml" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -325,7 +325,7 @@ public class PetApi { String[] contentTypes = { - "application/x-www-form-urlencoded", + "application/x-www-form-urlencoded" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; @@ -449,7 +449,7 @@ public class PetApi { String[] contentTypes = { - "multipart/form-data", + "multipart/form-data" }; String contentType = contentTypes.length > 0 ? contentTypes[0] : "application/json"; diff --git a/samples/client/petstore/objc/client/SWGPetApi.m b/samples/client/petstore/objc/client/SWGPetApi.m index 62bc34acbee..55ea82f99b0 100644 --- a/samples/client/petstore/objc/client/SWGPetApi.m +++ b/samples/client/petstore/objc/client/SWGPetApi.m @@ -75,7 +75,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[@"application/json", @"application/xml", ]; + NSArray* requestContentTypes = @[@"application/json", @"application/xml"]; NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; @@ -166,7 +166,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; - NSArray* requestContentTypes = @[@"application/json", @"application/xml", ]; + NSArray* requestContentTypes = @[@"application/json", @"application/xml"]; NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; @@ -519,7 +519,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSArray* requestContentTypes = @[@"application/x-www-form-urlencoded", ]; + NSArray* requestContentTypes = @[@"application/x-www-form-urlencoded"]; NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; @@ -681,7 +681,7 @@ static NSString * basePath = @"http://petstore.swagger.io/v2"; [requestUrl replaceCharactersInRange: [requestUrl rangeOfString:[NSString stringWithFormat:@"%@%@%@", @"{", @"petId", @"}"]] withString: [SWGApiClient escape:petId]]; - NSArray* requestContentTypes = @[@"multipart/form-data", ]; + NSArray* requestContentTypes = @[@"multipart/form-data"]; NSString* requestContentType = [requestContentTypes count] > 0 ? requestContentTypes[0] : @"application/json"; NSArray* responseContentTypes = @[@"application/json", @"application/xml"]; diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php index d6d14c72527..d3fe07aa911 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/APIClient.php @@ -142,20 +142,21 @@ class APIClient { $response_info = curl_getinfo($curl); // Handle the response - if ($response === false) { // error, likely in the client side - throw new APIClientException("API Error ($url): ".curl_error($curl), 0, $response_info, $response); + if ($response_info['http_code'] == 0) { + throw new APIClientException("TIMEOUT: api call to " . $url . + " took more than 5s to return", 0, $response_info, $response); } else if ($response_info['http_code'] >= 200 && $response_info['http_code'] <= 299 ) { $data = json_decode($response); if (json_last_error() > 0) { // if response is a string $data = $response; } - } else if ($response_info['http_code'] == 401) { // server returns 401 + } else if ($response_info['http_code'] == 401) { throw new APIClientException("Unauthorized API request to " . $url . ": " . serialize($response), 0, $response_info, $response); - } else if ($response_info['http_code'] == 404) { // server returns 404 + } else if ($response_info['http_code'] == 404) { $data = null; } else { - throw new APIClientException("Can't connect to the API: " . $url . + throw new APIClientException("Can't connect to the api: " . $url . " response code: " . $response_info['http_code'], 0, $response_info, $response); } diff --git a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php index 07f6181a730..a61757e2160 100644 --- a/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php +++ b/samples/client/petstore/php/SwaggerClient-php/lib/PetApi.php @@ -52,7 +52,7 @@ class PetApi { if ($_header_accept !== '') { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/json','application/xml',); + $_header_content_type = array('application/json','application/xml'); $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; @@ -104,7 +104,7 @@ class PetApi { if ($_header_accept !== '') { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/json','application/xml',); + $_header_content_type = array('application/json','application/xml'); $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; @@ -340,7 +340,7 @@ class PetApi { if ($_header_accept !== '') { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('application/x-www-form-urlencoded',); + $_header_content_type = array('application/x-www-form-urlencoded'); $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; @@ -466,7 +466,7 @@ class PetApi { if ($_header_accept !== '') { $headerParams['Accept'] = $_header_accept; } - $_header_content_type = array('multipart/form-data',); + $_header_content_type = array('multipart/form-data'); $headerParams['Content-Type'] = count($_header_content_type) > 0 ? $_header_content_type[0] : 'application/json'; diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py index d842c2f0a0f..b9d38108718 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/pet_api.py @@ -66,7 +66,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] headerParams['Accept'] = ', '.join(accepts) - content_types = ['application/json', 'application/xml', ] + content_types = ['application/json', 'application/xml'] headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' @@ -124,7 +124,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] headerParams['Accept'] = ', '.join(accepts) - content_types = ['application/json', 'application/xml', ] + content_types = ['application/json', 'application/xml'] headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' @@ -379,7 +379,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] headerParams['Accept'] = ', '.join(accepts) - content_types = ['application/x-www-form-urlencoded', ] + content_types = ['application/x-www-form-urlencoded'] headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' @@ -513,7 +513,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] headerParams['Accept'] = ', '.join(accepts) - content_types = ['multipart/form-data', ] + content_types = ['multipart/form-data'] headerParams['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' diff --git a/samples/client/petstore/qt5cpp/client/SWGPet.h b/samples/client/petstore/qt5cpp/client/SWGPet.h index 3f9320f1507..e9cb4d08233 100644 --- a/samples/client/petstore/qt5cpp/client/SWGPet.h +++ b/samples/client/petstore/qt5cpp/client/SWGPet.h @@ -10,10 +10,10 @@ #include -#include -#include "SWGCategory.h" -#include #include "SWGTag.h" +#include +#include "SWGCategory.h" +#include #include "SWGObject.h" diff --git a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb index 6f2740b22e9..d89cb6ae566 100644 --- a/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/swagger_client/api/pet_api.rb @@ -27,7 +27,7 @@ module SwaggerClient _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml', ] + _header_content_type = ['application/json', 'application/xml'] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters @@ -62,7 +62,7 @@ module SwaggerClient _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['application/json', 'application/xml', ] + _header_content_type = ['application/json', 'application/xml'] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters @@ -215,7 +215,7 @@ module SwaggerClient _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['application/x-www-form-urlencoded', ] + _header_content_type = ['application/x-www-form-urlencoded'] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters @@ -297,7 +297,7 @@ module SwaggerClient _header_accept_result = Swagger::Request.select_header_accept(_header_accept) and header_params['Accept'] = _header_accept_result # HTTP header 'Content-Type' - _header_content_type = ['multipart/form-data', ] + _header_content_type = ['multipart/form-data'] header_params['Content-Type'] = Swagger::Request.select_header_content_type(_header_content_type) # form parameters diff --git a/samples/html/index.html b/samples/html/index.html index 1025186dc4b..4a9212ea440 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -79,11 +79,37 @@

Example data

Content-Type: application/json
-
[ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
+
[ {
+  "tags" : [ {
+    "id" : 123456789,
+    "name" : "aeiou"
+  } ],
+  "id" : 123456789,
+  "category" : {
+    "id" : 123456789,
+    "name" : "aeiou"
+  },
+  "status" : "aeiou",
+  "name" : "doggie",
+  "photoUrls" : [ "aeiou" ]
+} ]

Example data

Content-Type: application/xml
-
\n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
+
<Pet>
+  <id>123456</id>
+  <Category>
+    <id>123456</id>
+    <name>string</name>
+  </Category>
+  <name>doggie</name>
+  <photoUrls>string</photoUrls>
+  <Tag>
+    <id>123456</id>
+    <name>string</name>
+  </Tag>
+  <status>string</status>
+</Pet>

@@ -108,11 +134,37 @@

Example data

Content-Type: application/json
-
[ {\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n} ]
+
[ {
+  "tags" : [ {
+    "id" : 123456789,
+    "name" : "aeiou"
+  } ],
+  "id" : 123456789,
+  "category" : {
+    "id" : 123456789,
+    "name" : "aeiou"
+  },
+  "status" : "aeiou",
+  "name" : "doggie",
+  "photoUrls" : [ "aeiou" ]
+} ]

Example data

Content-Type: application/xml
-
\n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
+
<Pet>
+  <id>123456</id>
+  <Category>
+    <id>123456</id>
+    <name>string</name>
+  </Category>
+  <name>doggie</name>
+  <photoUrls>string</photoUrls>
+  <Tag>
+    <id>123456</id>
+    <name>string</name>
+  </Tag>
+  <status>string</status>
+</Pet>

@@ -137,11 +189,37 @@

Example data

Content-Type: application/json
-
{\n  "tags" : [ {\n    "id" : 123456789,\n    "name" : "aeiou"\n  } ],\n  "id" : 123456789,\n  "category" : {\n    "id" : 123456789,\n    "name" : "aeiou"\n  },\n  "status" : "aeiou",\n  "name" : "doggie",\n  "photoUrls" : [ "aeiou" ]\n}
+
{
+  "tags" : [ {
+    "id" : 123456789,
+    "name" : "aeiou"
+  } ],
+  "id" : 123456789,
+  "category" : {
+    "id" : 123456789,
+    "name" : "aeiou"
+  },
+  "status" : "aeiou",
+  "name" : "doggie",
+  "photoUrls" : [ "aeiou" ]
+}

Example data

Content-Type: application/xml
-
\n  123456\n  \n    123456\n    string\n  \n  doggie\n  string\n  \n    123456\n    string\n  \n  string\n
+
<Pet>
+  <id>123456</id>
+  <Category>
+    <id>123456</id>
+    <name>string</name>
+  </Category>
+  <name>doggie</name>
+  <photoUrls>string</photoUrls>
+  <Tag>
+    <id>123456</id>
+    <name>string</name>
+  </Tag>
+  <status>string</status>
+</Pet>

@@ -241,11 +319,13 @@

Example data

Content-Type: application/json
-
{\n  "key" : 123\n}
+
{
+  "key" : 123
+}

Example data

Content-Type: application/xml
-
not implemented com.wordnik.swagger.models.properties.MapProperty@5076b51c
+
not implemented com.wordnik.swagger.models.properties.MapProperty@3e

@@ -270,11 +350,25 @@

Example data

Content-Type: application/json
-
{\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-05-12T09:58:06.953+0000"\n}
+
{
+  "id" : 123456789,
+  "petId" : 123456789,
+  "complete" : true,
+  "status" : "aeiou",
+  "quantity" : 123,
+  "shipDate" : "2015-05-21T05:19:00.242+0000"
+}

Example data

Content-Type: application/xml
-
\n  123456\n  123456\n  0\n  2015-05-12T05:58:06.956Z\n  string\n  true\n
+
<Order>
+  <id>123456</id>
+  <petId>123456</petId>
+  <quantity>0</quantity>
+  <shipDate>2015-05-20T22:19:00.244Z</shipDate>
+  <status>string</status>
+  <complete>true</complete>
+</Order>

@@ -299,11 +393,25 @@

Example data

Content-Type: application/json
-
{\n  "id" : 123456789,\n  "petId" : 123456789,\n  "complete" : true,\n  "status" : "aeiou",\n  "quantity" : 123,\n  "shipDate" : "2015-05-12T09:58:06.957+0000"\n}
+
{
+  "id" : 123456789,
+  "petId" : 123456789,
+  "complete" : true,
+  "status" : "aeiou",
+  "quantity" : 123,
+  "shipDate" : "2015-05-21T05:19:00.245+0000"
+}

Example data

Content-Type: application/xml
-
\n  123456\n  123456\n  0\n  2015-05-12T05:58:06.957Z\n  string\n  true\n
+
<Order>
+  <id>123456</id>
+  <petId>123456</petId>
+  <quantity>0</quantity>
+  <shipDate>2015-05-20T22:19:00.246Z</shipDate>
+  <status>string</status>
+  <complete>true</complete>
+</Order>

@@ -415,7 +523,7 @@

Example data

Content-Type: application/json
-
"aeiou"
+
"aeiou"

Example data

Content-Type: application/xml
@@ -462,11 +570,16 @@

Example data

Content-Type: application/json
-
{\n  "id" : 123456789,\n  "lastName" : "aeiou",\n  "phone" : "aeiou",\n  "username" : "aeiou",\n  "email" : "aeiou",\n  "userStatus" : 123,\n  "firstName" : "aeiou",\n  "password" : "aeiou"\n}
- -

Example data

-
Content-Type: application/xml
-
\n  123456\n  string\n  string\n  string\n  string\n  string\n  string\n  0\n
+
{
+  "id" : 1,
+  "username" : "johnp",
+  "firstName" : "John",
+  "lastName" : "Public",
+  "email" : "johnp@swagger.io",
+  "password" : "-secret-",
+  "phone" : "0123456789",
+  "userStatus" : 0
+}

diff --git a/samples/server/petstore/jaxrs/pom.xml b/samples/server/petstore/jaxrs/pom.xml index c928b341b38..b57a4fd416d 100644 --- a/samples/server/petstore/jaxrs/pom.xml +++ b/samples/server/petstore/jaxrs/pom.xml @@ -129,7 +129,7 @@ - 1.5.2-M2-SNAPSHOT + 1.5.2-M2 9.2.9.v20150224 1.13 1.6.3 diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java index 8b3b9d40b06..a303cf84bc3 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java @@ -21,12 +21,14 @@ import javax.ws.rs.core.Response; import javax.ws.rs.*; @Path("/pet") + + @com.wordnik.swagger.annotations.Api(value = "/pet", description = "the pet API") public class PetApi { @PUT - @Consumes({ "application/json", "application/xml", }) + @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Update an existing pet", notes = "", response = Void.class) @com.wordnik.swagger.annotations.ApiResponses(value = { @@ -45,7 +47,7 @@ public class PetApi { @POST - @Consumes({ "application/json", "application/xml", }) + @Consumes({ "application/json", "application/xml" }) @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Add a new pet to the store", notes = "", response = Void.class) @com.wordnik.swagger.annotations.ApiResponses(value = { @@ -113,7 +115,7 @@ public class PetApi { @POST @Path("/{petId}") - @Consumes({ "application/x-www-form-urlencoded", }) + @Consumes({ "application/x-www-form-urlencoded" }) @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "Updates a pet in the store with form data", notes = "", response = Void.class) @com.wordnik.swagger.annotations.ApiResponses(value = { @@ -146,7 +148,7 @@ public class PetApi { @POST @Path("/{petId}/uploadImage") - @Consumes({ "multipart/form-data", }) + @Consumes({ "multipart/form-data" }) @Produces({ "application/json", "application/xml" }) @com.wordnik.swagger.annotations.ApiOperation(value = "uploads an image", notes = "", response = Void.class) @com.wordnik.swagger.annotations.ApiResponses(value = { diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java index d2bde7cf35b..660f6317422 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/StoreApi.java @@ -21,6 +21,8 @@ import javax.ws.rs.core.Response; import javax.ws.rs.*; @Path("/store") + + @com.wordnik.swagger.annotations.Api(value = "/store", description = "the store API") public class StoreApi { diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java index 3f6da2c5d92..d907b8b579b 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/UserApi.java @@ -21,6 +21,8 @@ import javax.ws.rs.core.Response; import javax.ws.rs.*; @Path("/user") + + @com.wordnik.swagger.annotations.Api(value = "/user", description = "the user API") public class UserApi { diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index ca48e7b10ff..1484dcc4dea 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -40,9 +40,10 @@ public class PetApi { @ApiResponse(code = 400, message = "Invalid ID supplied") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, - consumes = { "application/json", "application/xml", }, + consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) - public ResponseEntity updatePet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + public ResponseEntity updatePet( +@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -55,9 +56,10 @@ public class PetApi { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "", produces = { "application/json", "application/xml" }, - consumes = { "application/json", "application/xml", }, + consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity addPet(@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) + public ResponseEntity addPet( +@ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -73,7 +75,8 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @RequestParam(value = "status", required = false) List status) + public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @RequestParam(value = "status", required = false) List status +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -89,7 +92,8 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags) + public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -106,7 +110,8 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId) + public ResponseEntity getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -119,12 +124,15 @@ public class PetApi { @ApiResponse(code = 405, message = "Invalid input") }) @RequestMapping(value = "/{petId}", produces = { "application/json", "application/xml" }, - consumes = { "application/x-www-form-urlencoded", }, + consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId, + public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId +, + @ApiParam(value = "Updated name of the pet" )@RequestPart("name") String name, + @ApiParam(value = "Updated status of the pet" )@RequestPart("status") String status) throws NotFoundException { // do some magic! @@ -140,8 +148,10 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deletePet(@ApiParam(value = "" )@RequestHeader("apiKey") String apiKey, - @ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId) + public ResponseEntity deletePet(@ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey +, + @ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -154,12 +164,15 @@ public class PetApi { @ApiResponse(code = 0, message = "successful operation") }) @RequestMapping(value = "/{petId}/uploadImage", produces = { "application/json", "application/xml" }, - consumes = { "multipart/form-data", }, + consumes = { "multipart/form-data" }, method = RequestMethod.POST) - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId, + public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId +, + @ApiParam(value = "Additional data to pass to server" )@RequestPart("additionalMetadata") String additionalMetadata, - @ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail) + +@ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 4f3eb963e16..5951036403d 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -56,7 +56,8 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity placeOrder(@ApiParam(value = "order placed for purchasing the pet" ) Order body) + public ResponseEntity placeOrder( +@ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -73,7 +74,8 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId) + public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -89,7 +91,8 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId) + public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index 25671c6168d..a978aad2d5e 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -40,7 +40,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity createUser(@ApiParam(value = "Created user object" ) User body) + public ResponseEntity createUser( +@ApiParam(value = "Created user object" ) User body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -55,7 +56,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity createUsersWithArrayInput(@ApiParam(value = "List of user object" ) List body) + public ResponseEntity createUsersWithArrayInput( +@ApiParam(value = "List of user object" ) List body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -70,7 +72,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.POST) - public ResponseEntity createUsersWithListInput(@ApiParam(value = "List of user object" ) List body) + public ResponseEntity createUsersWithListInput( +@ApiParam(value = "List of user object" ) List body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -86,8 +89,10 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username, - @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password) + public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username +, + @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -119,7 +124,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username) + public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -135,8 +141,10 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.PUT) - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username, - @ApiParam(value = "Updated user object" ) User body) + public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username +, + +@ApiParam(value = "Updated user object" ) User body) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -152,7 +160,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username) + public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username +) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); From c509bbcb99bf01444dcedb54c2cacd1a689b97ac Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 20 May 2015 22:34:29 -0700 Subject: [PATCH 71/75] updated --- samples/client/petstore/objc/Podfile.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/samples/client/petstore/objc/Podfile.lock b/samples/client/petstore/objc/Podfile.lock index e9e593cf299..fe43a2c80eb 100644 --- a/samples/client/petstore/objc/Podfile.lock +++ b/samples/client/petstore/objc/Podfile.lock @@ -33,4 +33,4 @@ SPEC CHECKSUMS: ISO8601: 962282de75074c38bbfaa7b133b0e743ed6deb8d JSONModel: ec77e9865236a7a09d9cf7668df6b4b328d9ec1d -COCOAPODS: 0.37.1 +COCOAPODS: 0.36.0 From 779915a51fba3ab1bd91b9d161f8802312b42278 Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 20 May 2015 22:34:54 -0700 Subject: [PATCH 72/75] rebuilt --- samples/client/petstore/objc/client/SWGObject.h | 1 - 1 file changed, 1 deletion(-) diff --git a/samples/client/petstore/objc/client/SWGObject.h b/samples/client/petstore/objc/client/SWGObject.h index 006701cde01..ccec208abc0 100644 --- a/samples/client/petstore/objc/client/SWGObject.h +++ b/samples/client/petstore/objc/client/SWGObject.h @@ -1,6 +1,5 @@ #import #import "JSONModel.h" -#import "JSONValueTransformer+ISO8601.h" @interface SWGObject : JSONModel @end From 3629a190ae4ce2fa8c2e2a4d1e2a9bcb4888c6cc Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 20 May 2015 22:50:59 -0700 Subject: [PATCH 73/75] merged --- .../SwaggerPetstore/apis/pet_api.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py index e6bd35514f4..bf8a51d7ca2 100644 --- a/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py +++ b/samples/client/petstore/python/SwaggerPetstore-python/SwaggerPetstore/apis/pet_api.py @@ -66,7 +66,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] header_params['Accept'] = ', '.join(accepts) - content_types = ['application/json', 'application/xml', ] + content_types = ['application/json', 'application/xml'] header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, @@ -105,7 +105,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] header_params['Accept'] = ', '.join(accepts) - content_types = ['application/json', 'application/xml', ] + content_types = ['application/json', 'application/xml'] header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, @@ -277,7 +277,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] header_params['Accept'] = ', '.join(accepts) - content_types = ['application/x-www-form-urlencoded', ] + content_types = ['application/x-www-form-urlencoded'] header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, @@ -335,7 +335,7 @@ class PetApi(object): :param int pet_id: ID of pet to update (required) :param str additional_metadata: Additional data to pass to server - :param file file: file to upload + :param File file: file to upload :return: None """ @@ -366,7 +366,7 @@ class PetApi(object): accepts = ['application/json', 'application/xml'] header_params['Accept'] = ', '.join(accepts) - content_types = ['multipart/form-data', ] + content_types = ['multipart/form-data'] header_params['Content-Type'] = content_types[0] if len(content_types) > 0 else 'application/json' response = self.api_client.call_api(resource_path, method, path_params, query_params, header_params, From 99a11636da1add580bc6cb3fa413aa4fe051218c Mon Sep 17 00:00:00 2001 From: Tony Tam Date: Wed, 20 May 2015 22:51:30 -0700 Subject: [PATCH 74/75] rebuilt --- .../scala/io/swagger/client/api/PetApi.scala | 2 +- samples/html/index.html | 34 +++---------------- .../src/main/java/io/swagger/api/PetApi.java | 2 +- .../src/main/java/io/swagger/api/PetApi.java | 31 ++++++++++++----- .../main/java/io/swagger/api/StoreApi.java | 7 ++-- .../src/main/java/io/swagger/api/UserApi.java | 15 ++++++-- 6 files changed, 46 insertions(+), 45 deletions(-) diff --git a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala index c17f0a12911..bdf489c08c0 100644 --- a/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala +++ b/samples/client/petstore/scala/src/main/scala/io/swagger/client/api/PetApi.scala @@ -123,7 +123,7 @@ class PetApi(val defBasePath: String = "http://petstore.swagger.io/v2", * @param status Status values that need to be considered for filter * @return List[Pet] */ - def findPetsByStatus (status: List[String]) : Option[List[Pet]] = { + def findPetsByStatus (status: List[String] = available) : Option[List[Pet]] = { // create path and map variables val path = "/pet/findByStatus".replaceAll("\\{format\\}","json") diff --git a/samples/html/index.html b/samples/html/index.html index 4a9212ea440..9d47aa360eb 100644 --- a/samples/html/index.html +++ b/samples/html/index.html @@ -69,7 +69,7 @@
status (optional)
-
Query Parameter — Status values that need to be considered for filter
+
Query Parameter — Status values that need to be considered for filter default: available

Return type

@@ -98,16 +98,8 @@
Content-Type: application/xml
<Pet>
   <id>123456</id>
-  <Category>
-    <id>123456</id>
-    <name>string</name>
-  </Category>
   <name>doggie</name>
   <photoUrls>string</photoUrls>
-  <Tag>
-    <id>123456</id>
-    <name>string</name>
-  </Tag>
   <status>string</status>
 </Pet>
@@ -153,16 +145,8 @@
Content-Type: application/xml
<Pet>
   <id>123456</id>
-  <Category>
-    <id>123456</id>
-    <name>string</name>
-  </Category>
   <name>doggie</name>
   <photoUrls>string</photoUrls>
-  <Tag>
-    <id>123456</id>
-    <name>string</name>
-  </Tag>
   <status>string</status>
 </Pet>
@@ -208,16 +192,8 @@
Content-Type: application/xml
<Pet>
   <id>123456</id>
-  <Category>
-    <id>123456</id>
-    <name>string</name>
-  </Category>
   <name>doggie</name>
   <photoUrls>string</photoUrls>
-  <Tag>
-    <id>123456</id>
-    <name>string</name>
-  </Tag>
   <status>string</status>
 </Pet>
@@ -356,7 +332,7 @@ "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-05-21T05:19:00.242+0000" + "shipDate" : "2015-05-21T05:49:06.118+0000" }

Example data

@@ -365,7 +341,7 @@ <id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-05-20T22:19:00.244Z</shipDate> + <shipDate>2015-05-20T22:49:06.120Z</shipDate> <status>string</status> <complete>true</complete> </Order> @@ -399,7 +375,7 @@ "complete" : true, "status" : "aeiou", "quantity" : 123, - "shipDate" : "2015-05-21T05:19:00.245+0000" + "shipDate" : "2015-05-21T05:49:06.121+0000" }

Example data

@@ -408,7 +384,7 @@ <id>123456</id> <petId>123456</petId> <quantity>0</quantity> - <shipDate>2015-05-20T22:19:00.246Z</shipDate> + <shipDate>2015-05-20T22:49:06.122Z</shipDate> <status>string</status> <complete>true</complete> </Order> diff --git a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java index a303cf84bc3..8abaf768136 100644 --- a/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/jaxrs/src/main/java/io/swagger/api/PetApi.java @@ -70,7 +70,7 @@ public class PetApi { @com.wordnik.swagger.annotations.ApiResponse(code = 400, message = "Invalid status value") }) - public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @QueryParam("status") List status) + public Response findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue="available") @QueryParam("status") List status) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java index 1484dcc4dea..a39a8e70970 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/PetApi.java @@ -43,6 +43,7 @@ public class PetApi { consumes = { "application/json", "application/xml" }, method = RequestMethod.PUT) public ResponseEntity updatePet( + @ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { // do some magic! @@ -59,6 +60,7 @@ public class PetApi { consumes = { "application/json", "application/xml" }, method = RequestMethod.POST) public ResponseEntity addPet( + @ApiParam(value = "Pet object that needs to be added to the store" ) Pet body) throws NotFoundException { // do some magic! @@ -75,7 +77,8 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter") @RequestParam(value = "status", required = false) List status + public ResponseEntity findPetsByStatus(@ApiParam(value = "Status values that need to be considered for filter", defaultValue = "available") @RequestParam(value = "status", required = false, defaultValue="available") List status + ) throws NotFoundException { // do some magic! @@ -93,6 +96,7 @@ public class PetApi { method = RequestMethod.GET) public ResponseEntity findPetsByTags(@ApiParam(value = "Tags to filter by") @RequestParam(value = "tags", required = false) List tags + ) throws NotFoundException { // do some magic! @@ -110,7 +114,8 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getPetById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId + public ResponseEntity getPetById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("petId") Long petId ) throws NotFoundException { // do some magic! @@ -126,14 +131,17 @@ public class PetApi { produces = { "application/json", "application/xml" }, consumes = { "application/x-www-form-urlencoded" }, method = RequestMethod.POST) - public ResponseEntity updatePetWithForm(@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId + public ResponseEntity updatePetWithForm( +@ApiParam(value = "ID of pet that needs to be updated",required=true ) @PathVariable("petId") String petId , -@ApiParam(value = "Updated name of the pet" )@RequestPart("name") String name, + +@ApiParam(value = "Updated name of the pet" ) @RequestPart(value="name", required=false) String name, -@ApiParam(value = "Updated status of the pet" )@RequestPart("status") String status) + +@ApiParam(value = "Updated status of the pet" ) @RequestPart(value="status", required=false) String status) throws NotFoundException { // do some magic! return new ResponseEntity(HttpStatus.OK); @@ -148,9 +156,11 @@ public class PetApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deletePet(@ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey + public ResponseEntity deletePet( +@ApiParam(value = "" ) @RequestHeader(value="apiKey", required=false) String apiKey , - @ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId + +@ApiParam(value = "Pet id to delete",required=true ) @PathVariable("petId") Long petId ) throws NotFoundException { // do some magic! @@ -166,12 +176,15 @@ public class PetApi { produces = { "application/json", "application/xml" }, consumes = { "multipart/form-data" }, method = RequestMethod.POST) - public ResponseEntity uploadFile(@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId + public ResponseEntity uploadFile( +@ApiParam(value = "ID of pet to update",required=true ) @PathVariable("petId") Long petId , -@ApiParam(value = "Additional data to pass to server" )@RequestPart("additionalMetadata") String additionalMetadata, + +@ApiParam(value = "Additional data to pass to server" ) @RequestPart(value="additionalMetadata", required=false) String additionalMetadata, + @ApiParam(value = "file detail") @RequestPart("file") MultipartFile fileDetail) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java index 5951036403d..ba6e233ce9c 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/StoreApi.java @@ -57,6 +57,7 @@ public class StoreApi { method = RequestMethod.POST) public ResponseEntity placeOrder( + @ApiParam(value = "order placed for purchasing the pet" ) Order body) throws NotFoundException { // do some magic! @@ -74,7 +75,8 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getOrderById(@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId + public ResponseEntity getOrderById( +@ApiParam(value = "ID of pet that needs to be fetched",required=true ) @PathVariable("orderId") String orderId ) throws NotFoundException { // do some magic! @@ -91,7 +93,8 @@ public class StoreApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deleteOrder(@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId + public ResponseEntity deleteOrder( +@ApiParam(value = "ID of the order that needs to be deleted",required=true ) @PathVariable("orderId") String orderId ) throws NotFoundException { // do some magic! diff --git a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java index a978aad2d5e..15b170e90a7 100644 --- a/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java +++ b/samples/server/petstore/spring-mvc/src/main/java/io/swagger/api/UserApi.java @@ -41,6 +41,7 @@ public class UserApi { method = RequestMethod.POST) public ResponseEntity createUser( + @ApiParam(value = "Created user object" ) User body) throws NotFoundException { // do some magic! @@ -57,6 +58,7 @@ public class UserApi { method = RequestMethod.POST) public ResponseEntity createUsersWithArrayInput( + @ApiParam(value = "List of user object" ) List body) throws NotFoundException { // do some magic! @@ -73,6 +75,7 @@ public class UserApi { method = RequestMethod.POST) public ResponseEntity createUsersWithListInput( + @ApiParam(value = "List of user object" ) List body) throws NotFoundException { // do some magic! @@ -90,8 +93,10 @@ public class UserApi { method = RequestMethod.GET) public ResponseEntity loginUser(@ApiParam(value = "The user name for login") @RequestParam(value = "username", required = false) String username + , @ApiParam(value = "The password for login in clear text") @RequestParam(value = "password", required = false) String password + ) throws NotFoundException { // do some magic! @@ -124,7 +129,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.GET) - public ResponseEntity getUserByName(@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username + public ResponseEntity getUserByName( +@ApiParam(value = "The name that needs to be fetched. Use user1 for testing. ",required=true ) @PathVariable("username") String username ) throws NotFoundException { // do some magic! @@ -141,9 +147,11 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.PUT) - public ResponseEntity updateUser(@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username + public ResponseEntity updateUser( +@ApiParam(value = "name that need to be deleted",required=true ) @PathVariable("username") String username , + @ApiParam(value = "Updated user object" ) User body) throws NotFoundException { // do some magic! @@ -160,7 +168,8 @@ public class UserApi { produces = { "application/json", "application/xml" }, method = RequestMethod.DELETE) - public ResponseEntity deleteUser(@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username + public ResponseEntity deleteUser( +@ApiParam(value = "The name that needs to be deleted",required=true ) @PathVariable("username") String username ) throws NotFoundException { // do some magic! From a590239df9b32d92b93d287ac613c8a0c417aae5 Mon Sep 17 00:00:00 2001 From: Alexey Nechaev Date: Thu, 21 May 2015 10:49:20 +0300 Subject: [PATCH 75/75] Fixes #771: Unit test has been fixed after merge. --- .../src/test/scala/ExampleGeneratorTest.scala | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala index 5407202c5d3..09ffbf0e16c 100644 --- a/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala +++ b/modules/swagger-codegen/src/test/scala/ExampleGeneratorTest.scala @@ -42,17 +42,17 @@ class ExampleGeneratorTest extends FlatSpec with Matchers { item.get("contentType") match { case `xml` => { types += xml - example should be ("\\n" + - " \\n" + - " string\\n" + - " \\n" + - " \\n" + - " \\n" + - " \\n" + - " string\\n" + - " \\n" + - " \\n" + - " \\n" + + example should be ("\n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " string\n" + + " \n" + + " \n" + + " \n" + "") } case `json` => {