diff --git a/bin/lua-petstore.sh b/bin/lua-petstore.sh new file mode 100755 index 00000000000..2b8f732d14b --- /dev/null +++ b/bin/lua-petstore.sh @@ -0,0 +1,31 @@ +#!/bin/sh + +SCRIPT="$0" + +while [ -h "$SCRIPT" ] ; do + ls=`ls -ld "$SCRIPT"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + SCRIPT="$link" + else + SCRIPT=`dirname "$SCRIPT"`/"$link" + fi +done + +if [ ! -d "${APP_DIR}" ]; then + APP_DIR=`dirname "$SCRIPT"`/.. + APP_DIR=`cd "${APP_DIR}"; pwd` +fi + +executable="./modules/swagger-codegen-cli/target/swagger-codegen-cli.jar" + +if [ ! -f "$executable" ] +then + mvn clean package +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/lua -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l lua -o samples/client/petstore/lua -DpackageName=petstore $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/lua-petstore.bat b/bin/windows/lua-petstore.bat new file mode 100755 index 00000000000..39f9c81fa32 --- /dev/null +++ b/bin/windows/lua-petstore.bat @@ -0,0 +1,10 @@ +set executable=.\modules\swagger-codegen-cli\target\swagger-codegen-cli.jar + +If Not Exist %executable% ( + mvn clean package +) + +REM set JAVA_OPTS=%JAVA_OPTS% -Xmx1024M -DloggerPath=conf/log4j.properties +set ags=generate -i modules\swagger-codegen\src\test\resources\2_0\petstore.yaml -l lua -o samples\client\petstore\lua + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LuaClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LuaClientCodegen.java new file mode 100644 index 00000000000..30288b8baf1 --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/LuaClientCodegen.java @@ -0,0 +1,522 @@ +package io.swagger.codegen.languages; + +import io.swagger.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class LuaClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(LuaClientCodegen.class); + + protected String packageName = "swagger"; + protected String packageVersion = "1.0.0"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public String getName() { + return "lua"; + } + + public String getHelp() { + return "Generates a Lua client library (beta)."; + } + + public LuaClientCodegen() { + super(); + outputFolder = "generated-code/lua"; + modelTemplateFiles.put("model.mustache", ".lua"); + apiTemplateFiles.put("api.mustache", ".lua"); + + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + embeddedTemplateDir = templateDir = "lua"; + + setReservedWordsLowerCase( + Arrays.asList( + // data type + "nil", "string", "boolean", "number", "userdata", "thread", + "table", + + // reserved words: http://www.lua.org/manual/5.1/manual.html#2.1 + "and", "break", "do", "else", "elseif", + "end", "false", "for", "function", "if", + "in", "local", "nil", "not", "or", + "repeat", "return", "then", "true", "until", "while" + ) + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "nil", + "string", + "boolean", + "number") + ); + + instantiationTypes.clear(); + /*instantiationTypes.put("array", "LuaArray"); + instantiationTypes.put("map", "LuaMap");*/ + + typeMapping.clear(); + typeMapping.put("integer", "number"); + typeMapping.put("long", "number"); + typeMapping.put("number", "number"); + typeMapping.put("float", "number"); + typeMapping.put("double", "number"); + typeMapping.put("boolean", "boolean"); + typeMapping.put("string", "string"); + typeMapping.put("UUID", "string"); + typeMapping.put("date", "string"); + typeMapping.put("DateTime", "string"); + typeMapping.put("password", "string"); + typeMapping.put("file", "TODO_FILE_MAPPING"); + // map binary to string as a workaround + // the correct solution is to use []byte + typeMapping.put("binary", "string"); + typeMapping.put("ByteArray", "string"); + typeMapping.put("object", "TODO_OBJECT_MAPPING"); + + importMapping = new HashMap(); + importMapping.put("time.Time", "time"); + importMapping.put("*os.File", "os"); + importMapping.put("os", "io/ioutil"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "Lua package name (convention: lowercase).") + .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "Lua package version.") + .defaultValue("1.0.0")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "hides the timestamp when files were generated") + .defaultValue(Boolean.TRUE.toString())); + + } + + @Override + public void processOpts() { + super.processOpts(); + + // default HIDE_GENERATION_TIMESTAMP to true + if (!additionalProperties.containsKey(CodegenConstants.HIDE_GENERATION_TIMESTAMP)) { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, Boolean.TRUE.toString()); + } else { + additionalProperties.put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + Boolean.valueOf(additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); + } else { + setPackageName("swagger"); + } + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } else { + setPackageVersion("1.0.0"); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + apiTestTemplateFiles.clear(); // TODO: add api test template + modelTestTemplateFiles.clear(); // TODO: add model test template + + apiDocTemplateFiles.clear(); // TODO: add api doc template + modelDocTemplateFiles.clear(); // TODO: add model doc template + + modelPackage = packageName; + apiPackage = packageName; + + //supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + //supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.lua")); + //supportingFiles.add(new SupportingFile("api_client.mustache", "", "api_client.lua")); + //supportingFiles.add(new SupportingFile("api_response.mustache", "", "api_response.lua")); + //supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); + } + + @Override + public String escapeReservedWord(String name) + { + // Can't start with an underscore, as our fields need to start with an + // UppercaseLetter so that Lua treats them as public/visible. + + // Options? + // - MyName + // - AName + // - TheName + // - XName + // - X_Name + // ... or maybe a suffix? + // - Name_ ... think this will work. + if(this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return camelize(name) + '_'; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + "api" + File.separator; + } + + public String modelFileFolder() { + return outputFolder + File.separator + "model" + File.separator; + } + + @Override + public String toVarName(String name) { + // replace - with _ e.g. created-at => created_at + name = sanitizeName(name.replaceAll("-", "_")); + + // if it's all uppper case, do nothing + if (name.matches("^[A-Z_]*$")) + return name; + + // convert variable name to snake case + // PetId => pet_id + name = underscore(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name)) + name = escapeReservedWord(name); + + // for reserved word or word starting with number, append _ + if (name.matches("^\\d.*")) + name = "Var" + name; + + return name; + } + + @Override + public String toParamName(String name) { + return toVarName(name); + } + + @Override + public String toModelName(String name) { + return toModelFilename(name); + } + + @Override + public String toModelFilename(String name) { + if (!StringUtils.isEmpty(modelNamePrefix)) { + name = modelNamePrefix + "_" + name; + } + + if (!StringUtils.isEmpty(modelNameSuffix)) { + name = name + "_" + modelNameSuffix; + } + + name = sanitizeName(name); + + // model name cannot use reserved keyword, e.g. return + if (isReservedWord(name)) { + LOGGER.warn(name + " (reserved word) cannot be used as model name. Renamed to " + ("model_" + name)); + name = "model_" + name; // e.g. return => ModelReturn (after camelize) + } + + // model name starts with number + if (name.matches("^\\d.*")) { + LOGGER.warn(name + " (model name starts with number) cannot be used as model name. Renamed to " + ("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + return underscore(name); + } + + @Override + public String toApiFilename(String name) { + // replace - with _ e.g. created-at => created_at + name = name.replaceAll("-", "_"); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'. + + // e.g. PetApi.lua => pet_api.lua + return underscore(name) + "_api"; + } + + /** + * Overrides postProcessParameter to add a vendor extension "x-exportParamName". + * This is useful when paramName starts with a lowercase letter, but we need that + * param to be exportable (starts with an Uppercase letter). + * + * @param parameter CodegenParameter object to be processed. + */ + @Override + public void postProcessParameter(CodegenParameter parameter){ + + //// Give the base class a chance to process + //super.postProcessParameter(parameter); + + //char firstChar = parameter.paramName.charAt(0); + + //if (Character.isUpperCase(firstChar)) { + // // First char is already uppercase, just use paramName. + // parameter.vendorExtensions.put("x-exportParamName", parameter.paramName); + + //} + + //// It's a lowercase first char, let's convert it to uppercase + //StringBuilder sb = new StringBuilder(parameter.paramName); + //sb.setCharAt(0, Character.toUpperCase(firstChar)); + //parameter.vendorExtensions.put("x-exportParamName", sb.toString()); + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String toModelDocFilename(String name) { + return toModelName(name); + } + + @Override + public String toApiDocFilename(String name) { + return toApiName(name); + } + + @Override + public String toApiName(String name) { + return underscore(super.toApiName(name)); + } + + @Override + public String getTypeDeclaration(Property p) { + if(p instanceof ArrayProperty) { + ArrayProperty ap = (ArrayProperty) p; + Property inner = ap.getItems(); + return getTypeDeclaration(inner); + } else if (p instanceof MapProperty) { + MapProperty mp = (MapProperty) p; + Property inner = mp.getAdditionalProperties(); + return getTypeDeclaration(inner); + } + + // Not using the supertype invocation, because we want to UpperCamelize + // the type. + String swaggerType = getSwaggerType(p); + if (typeMapping.containsKey(swaggerType)) { + return typeMapping.get(swaggerType); + } + + if (typeMapping.containsValue(swaggerType)) { + return swaggerType; + } + + if (languageSpecificPrimitives.contains(swaggerType)) { + return swaggerType; + } + + return toModelName(swaggerType); + } + + @Override + public String getSwaggerType(Property p) { + String swaggerType = super.getSwaggerType(p); + String type = null; + if (typeMapping.containsKey(swaggerType)) { + type = typeMapping.get(swaggerType); + if (languageSpecificPrimitives.contains(type)) + return (type); + } else { + type = swaggerType; + } + return type; + } + + @Override + public String toOperationId(String operationId) { + String sanitizedOperationId = sanitizeName(operationId); + + // method name cannot use reserved keyword, e.g. return + if (isReservedWord(sanitizedOperationId)) { + LOGGER.warn(operationId + " (reserved word) cannot be used as method name. Renamed to " + underscore("call_" + operationId)); + sanitizedOperationId = "call_" + sanitizedOperationId; + } + + return underscore(sanitizedOperationId); + } + + @Override + public Map postProcessOperations(Map objs) { + @SuppressWarnings("unchecked") + Map objectMap = (Map) objs.get("operations"); + @SuppressWarnings("unchecked") + List operations = (List) objectMap.get("operation"); + for (CodegenOperation op: operations) { + + String[] items = op.path.split("/", -1); + String luaPath = ""; + int pathParamIndex = 0; + + for (int i = 0; i < items.length; ++i) { + if (items[i].matches("^\\{(.*)\\}$")) { // wrap in {} + // find the datatype of the parameter + //final CodegenParameter cp = op.pathParams.get(pathParamIndex); + // TODO: Handle non-primitives… + //luaPath = luaPath + cp.dataType.toLowerCase(); + luaPath = luaPath + "/%s"; + pathParamIndex++; + } else if (items[i].length() != 0) { + luaPath = luaPath + "/" + items[i]; + } else { + //luaPath = luaPath + "/"; + } + } + op.vendorExtensions.put("x-codegen-path", luaPath); + } + return objs; + } + + @Override + public Map postProcessModels(Map objs) { + // remove model imports to avoid error + List> imports = (List>) objs.get("imports"); + final String prefix = modelPackage(); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(prefix)) + iterator.remove(); + } + + // recursively add import for mapping one type to multiple imports + List> recursiveImports = (List>) objs.get("imports"); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = imports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + listIterator.add(createMapping("import", importMapping.get(_import))); + } + } + + return postProcessModelsEnum(objs); + } + + @Override + protected boolean needToImport(String type) { + return !defaultIncludes.contains(type) + && !languageSpecificPrimitives.contains(type); + } + + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("]]", "] ]"); + } + + public Map createMapping(String key, String value){ + Map customImport = new HashMap(); + customImport.put(key, value); + + return customImport; + } + + @Override + public String toEnumValue(String value, String datatype) { + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + return value; + } else { + return escapeText(value); + } + } + + @Override + public String toEnumDefaultValue(String value, String datatype) { + return datatype + "_" + value; + } + + @Override + public String toEnumVarName(String name, String datatype) { + if (name.length() == 0) { + return "EMPTY"; + } + + // number + if ("int".equals(datatype) || "double".equals(datatype) || "float".equals(datatype)) { + String varName = name; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // for symbol, e.g. $, # + if (getSymbolName(name) != null) { + return getSymbolName(name).toUpperCase(); + } + + // string + String enumName = sanitizeName(underscore(name).toUpperCase()); + enumName = enumName.replaceFirst("^_", ""); + enumName = enumName.replaceFirst("_$", ""); + + if (isReservedWord(enumName) || enumName.matches("\\d.*")) { // reserved word or starts with number + return escapeReservedWord(enumName); + } else { + return enumName; + } + } + + @Override + public String toEnumName(CodegenProperty property) { + String enumName = underscore(toModelName(property.name)).toUpperCase(); + + // remove [] for array or map of enum + enumName = enumName.replace("[]", ""); + + if (enumName.matches("\\d.*")) { // starts with number + return "_" + enumName; + } else { + return enumName; + } + } +} diff --git a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig index 27d63c44097..670be0ef233 100644 --- a/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig +++ b/modules/swagger-codegen/src/main/resources/META-INF/services/io.swagger.codegen.CodegenConfig @@ -38,6 +38,7 @@ io.swagger.codegen.languages.JavascriptClientCodegen io.swagger.codegen.languages.JavascriptClosureAngularClientCodegen io.swagger.codegen.languages.JavaVertXServerCodegen io.swagger.codegen.languages.KotlinClientCodegen +io.swagger.codegen.languages.LuaClientCodegen io.swagger.codegen.languages.LumenServerCodegen io.swagger.codegen.languages.NancyFXServerCodegen io.swagger.codegen.languages.NodeJSServerCodegen diff --git a/modules/swagger-codegen/src/main/resources/lua/.travis.yml b/modules/swagger-codegen/src/main/resources/lua/.travis.yml new file mode 100644 index 00000000000..4004e966bee --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/.travis.yml @@ -0,0 +1,6 @@ +language: lua + +install: + +script: + diff --git a/modules/swagger-codegen/src/main/resources/lua/README.mustache b/modules/swagger-codegen/src/main/resources/lua/README.mustache new file mode 100644 index 00000000000..f46349d6357 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/README.mustache @@ -0,0 +1,96 @@ +# Lua API client for {{packageName}} + +{{#appDescription}} +{{{appDescription}}} +{{/appDescription}} + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [swagger-spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: {{appVersion}} +- Package version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} +For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +## Installation +Put the package under your project folder and add the following in import: +``` + "./{{packageName}}" +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation For Models + +{{#models}}{{#model}} - [{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} + +## Documentation For Authorization +{{^authMethods}} Endpoints do not require authorization. +{{/authMethods}}{{#authMethods}}{{#last}} Authentication schemes defined for the API:{{/last}}{{/authMethods}} +{{#authMethods}} +## {{{name}}} +{{#isApiKey}}- **Type**: API key + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAPIKey, sw.APIKey{ + Key: "APIKEY", + Prefix: "Bearer", // Omit if not necessary. + }) + r, err := client.Service.Operation(auth, args) +``` +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextBasicAuth, sw.BasicAuth{ + UserName: "username", + Password: "password", + }) + r, err := client.Service.Operation(auth, args) +``` +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{{flow}}} +- **Authorization URL**: {{{authorizationUrl}}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - **{{{scope}}}**: {{{description}}} +{{/scopes}} + +Example +``` + auth := context.WithValue(context.TODO(), sw.ContextAccessToken, "ACCESSTOKENSTRING") + r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automaticly refresh tokens and perform user authentication. +``` + import "golang.org/x/oauth2" + + / .. Perform OAuth2 round trip request and obtain a token .. // + + tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) + auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) + r, err := client.Service.Operation(auth, args) +``` +{{/isOAuth}} +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/lua/api.mustache b/modules/swagger-codegen/src/main/resources/lua/api.mustache new file mode 100644 index 00000000000..3e6f6a0b48c --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/api.mustache @@ -0,0 +1,152 @@ +{{>partial_header}} +--package {{packageName}} + +{{#operations}} +local http_request = require "http.request" +local http_util = require "http.util" +local dkjson = require "dkjson" +local basexx = require "basexx" + +-- model import +local {{{packageName}}}_{{classname}} = require "{{{packageName}}}.api.{{classname}}" + +local {{{packageName}}}= {} +local {{{packageName}}}_mt = { + __name = "{{{classname}}}"; + __index = {{{packageName}}}; +} + +local function new_{{classname}}(host, basePath, schemes) + local schemes_map = {} + for _,v in ipairs(schemes) do + schemes_map[v] = v + end + local default_scheme = schemes_map.https or schemes_map.http + return setmetatable({ + host = host; + basePath = basePath or "{{{basePath}}}"; + schemes = schemes_map; + default_scheme = default_scheme; + http_username = nil; + http_password = nil; + api_key = {}; + access_token = nil; + }, {{{packageName}}}_mt) +end + +{{#operation}} +function {{classname}}:{{operationId}}({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s{{{vendorExtensions.x-codegen-path}}}{{#queryParams}}{{#-first}}?{{/-first}}{{{baseName}}}=%s{{^-last}}&{{/-last}}{{/queryParams}}", + self.basePath{{#pathParams}}, {{paramName}}{{/pathParams}}{{#queryParams}}, http_util.encodeURIComponent({{paramName}}){{/queryParams}}); + }) + + -- set HTTP verb + req.headers:upsert(":method", "{{httpMethod}}") + {{#hasConsumes}} + -- TODO: create a function to select proper accept + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_content_type = { {{#consumes}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/consumes}} } + req.headers:upsert("accept", {{#consumes}}{{#-first}}"{{{mediaType}}}"{{/-first}}{{/consumes}}) + + {{/hasConsumes}} + {{#hasProduces}} + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { {{#produces}}"{{{mediaType}}}"{{#hasMore}}, {{/hasMore}}{{/produces}} } + req.headers:upsert("content-type", {{#produces}}{{#-first}}"{{{mediaType}}}"{{/-first}}{{/produces}}) + + {{/hasProduces}} + {{#headerParams}} + req.headers:upsert("{{baseName}}", {{paramName}}) + {{/headerParams}} + {{#formParams}} + {{#-first}} + req:set_body(http_util.dict_to_query({ + {{/-first}} + ["{{baseName}}"] = {{paramName}}; + {{#-last}} + })) + {{/-last}} + {{/formParams}} + {{#bodyParams}} + req:set_body(dkjson.encode({{paramName}})) + + {{/bodyParams}} + {{#authMethods}} + {{#isApiKey}} + {{#isKeyInHeader}} + -- api key in headers '{{keyParamName}}' + req.headers:upsert("{{{name}}}", api_key['{{{keyParamName}}}']) + {{/isKeyInHeader}} + {{#isKeyInQuery}} + -- TODO: api key in query '{{keyParamName}}' + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + -- HTTP basic auth + req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password)) + {{/isBasic}} + {{#isOAuth}} + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + {{/isOAuth}} + {{/authMethods}} + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + {{#returnType}} + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + {{#returnTypeIsPrimitive}} + return result, headers + {{/returnTypeIsPrimitive}} + {{^returnTypeIsPrimitive}} + {{#isListContainer}} + for _, ob in ipairs(result) do + cast_{{returnType}}(ob) + end + return result, headers + {{/isListContainer}} + {{#isMapContainer}} + return result, headers + {{/isMapContainer}} + {{^isMapContainer}} + {{^isListContainer}} + return cast_{{returnType}}(result), headers + {{/isListContainer}} + {{/isMapContainer}} + {{/returnTypeIsPrimitive}} + {{/returnType}} + {{^returnType}} + return nil, headers + {{/returnType}} + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/lua/api_client.mustache b/modules/swagger-codegen/src/main/resources/lua/api_client.mustache new file mode 100644 index 00000000000..9e88a17d436 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/api_client.mustache @@ -0,0 +1,427 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "bytes" + "encoding/json" + "encoding/xml" + "fmt" + "errors" + "io" + "mime/multipart" + "golang.org/x/oauth2" + "golang.org/x/net/context" + "net/http" + "net/url" + "time" + "os" + "path/filepath" + "reflect" + "regexp" + "strings" + "unicode/utf8" + "strconv" +) + +var ( + jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") + xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") +) + +// APIClient manages communication with the {{appName}} API v{{version}} +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services +{{#apiInfo}} +{{#apis}} +{{#operations}} + {{classname}} *{{classname}}Service +{{/operations}} +{{/apis}} +{{/apiInfo}} +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + +{{#apiInfo}} + // API Services +{{#apis}} +{{#operations}} + c.{{classname}} = (*{{classname}}Service)(&c.common) +{{/operations}} +{{/apis}} +{{/apiInfo}} + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insenstive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.ToLower(a) == strings.ToLower(needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. +func parameterToString(obj interface{}, collectionFormat string) string { + var delimiter string + + switch collectionFormat { + case "pipes": + delimiter = "|" + case "ssv": + delimiter = " " + case "tsv": + delimiter = "\t" + case "csv": + delimiter = "," + } + + if reflect.TypeOf(obj).Kind() == reflect.Slice { + return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + } + + return fmt.Sprintf("%v", obj) +} + +// callAPI do the request. +func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { + return c.cfg.HTTPClient.Do(request) +} + +// Change base path to allow switching to mocks +func (c *APIClient) ChangeBasePath (path string) { + c.cfg.BasePath = path +} + +// prepareRequest build the request +func (c *APIClient) prepareRequest ( + ctx context.Context, + path string, method string, + postBody interface{}, + headerParams map[string]string, + queryParams url.Values, + formParams url.Values, + fileName string, + fileBytes []byte) (localVarRequest *http.Request, err error) { + + var body *bytes.Buffer + + // Detect postBody type and post. + if postBody != nil { + contentType := headerParams["Content-Type"] + if contentType == "" { + contentType = detectContentType(postBody) + headerParams["Content-Type"] = contentType + } + + body, err = setBody(postBody, contentType) + if err != nil { + return nil, err + } + } + + // add form paramters and file if available. + if len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + if len(fileBytes) > 0 && fileName != "" { + w.Boundary() + //_, fileNm := filepath.Split(fileName) + part, err := w.CreateFormFile("file", filepath.Base(fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(fileBytes) + if err != nil { + return nil, err + } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + } + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + // Setup path and query paramters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = query.Encode() + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers.Set(h, v) + } + localVarRequest.Header = headers + } + + // Override request host, if applicable + if c.cfg.Host != "" { + localVarRequest.Host = c.cfg.Host + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + // Walk through any authentication. + if ctx != nil { + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + // Basic HTTP Authentication + if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { + localVarRequest.SetBasicAuth(auth.UserName, auth.Password) + } + + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer " + auth) + } + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + + return localVarRequest, nil +} + + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(path) + if err != nil { + return err + } + defer file.Close() + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) (error) { + return fmt.Errorf(format, a...) +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if jsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if xmlCheck.MatchString(contentType) { + xml.NewEncoder(bodyBuf).Encode(body) + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("Invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) (time.Time) { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } + expires = now.Add(lifetime) + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) (int) { + return utf8.RuneCountInString(s) +} + diff --git a/modules/swagger-codegen/src/main/resources/lua/api_doc.mustache b/modules/swagger-codegen/src/main/resources/lua/api_doc.mustache new file mode 100644 index 00000000000..70d0b96ce86 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/api_doc.mustache @@ -0,0 +1,50 @@ +# {{invokerPackage}}\{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} +# **{{{operationId}}}** +> {{#returnType}}{{{returnType}}} {{/returnType}}{{{operationId}}}({{#authMethods}}ctx, {{/authMethods}}{{#allParams}}{{#required}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/required}}{{/allParams}}{{#hasOptionalParams}}optional{{/hasOptionalParams}}) +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Required Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{#authMethods}} + **ctx** | **context.Context** | context containing the authentication | nil if no authentication{{/authMethods}}{{/-last}}{{/allParams}}{{#allParams}}{{#required}} + **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/required}}{{/allParams}}{{#hasOptionalParams}} + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. +{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}}{{#allParams}} + **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}}{{/allParams}}{{/hasOptionalParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{{returnType}}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}} (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{#hasMore}}, {{/hasMore}}{{/produces}}{{^produces}}Not defined{{/produces}} + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +{{/operation}} +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/lua/configuration.mustache b/modules/swagger-codegen/src/main/resources/lua/configuration.mustache new file mode 100644 index 00000000000..97bfa891d40 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/configuration.mustache @@ -0,0 +1,43 @@ +{{>partial_header}} +package {{packageName}} + +import ( + "net/http" +) + +const ContextOAuth2 int = 1 +const ContextBasicAuth int = 2 +const ContextAccessToken int = 3 +const ContextAPIKey int = 4 + +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +type APIKey struct { + Key string + Prefix string +} + +type Configuration struct { + BasePath string `json:"basePath,omitempty"` + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + HTTPClient *http.Client +} + +func NewConfiguration() *Configuration { + cfg := &Configuration{ + BasePath: "{{{basePath}}}", + DefaultHeader: make(map[string]string), + UserAgent: "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/go{{/httpUserAgent}}", + } + return cfg +} + +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} \ No newline at end of file diff --git a/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/git_push.sh.mustache @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/modules/swagger-codegen/src/main/resources/lua/gitignore.mustache b/modules/swagger-codegen/src/main/resources/lua/gitignore.mustache new file mode 100644 index 00000000000..180988936c5 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/gitignore.mustache @@ -0,0 +1,40 @@ +# Compiled Lua sources +luac.out + +# luarocks build files +*.src.rock +*.zip +*.tar.gz + +# Object files +*.o +*.os +*.ko +*.obj +*.elf + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo +*.def +*.exp + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex diff --git a/modules/swagger-codegen/src/main/resources/lua/model.mustache b/modules/swagger-codegen/src/main/resources/lua/model.mustache new file mode 100644 index 00000000000..65a7e3412c9 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/model.mustache @@ -0,0 +1,28 @@ +{{#models}} +{{#model}} +{{>partial_header}} +-- {{classname}} class +local {{classname}} = {} +local {{classname}}_mt = { + __name = "{{classname}}"; + __index = {{classname}}; +} + +local function cast_{{classname}}(t) + return setmetatable(t, {{classname}}_mt) +end + +local function new_{{classname}}({{#vars}}{{name}}{{#hasMore}}, {{/hasMore}}{{/vars}}) + return cast_{{classname}}({ + {{#vars}} + ["{{baseName}}"] = {{name}}; + {{/vars}} + }) +end + +return { + cast = cast_{{classname}}; + new = new_{{classname}}; +} +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/lua/model_doc.mustache b/modules/swagger-codegen/src/main/resources/lua/model_doc.mustache new file mode 100644 index 00000000000..25537b2c5ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/model_doc.mustache @@ -0,0 +1,11 @@ +{{#models}}{{#model}}# {{classname}} + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{{datatype}}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{^isContainer}}{{^isDateTime}}*{{/isDateTime}}{{/isContainer}}{{{datatype}}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#readOnly}}[readonly] {{/readOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}}{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/lua/partial_header.mustache b/modules/swagger-codegen/src/main/resources/lua/partial_header.mustache new file mode 100644 index 00000000000..63da5d8fc1e --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/lua/partial_header.mustache @@ -0,0 +1,13 @@ +--[[ + {{#appName}} + {{{appName}}} + + {{/appName}} + {{#appDescription}} + {{{appDescription}}} + + {{/appDescription}} + {{#version}}OpenAPI spec version: {{{version}}}{{/version}} + {{#infoEmail}}Contact: {{{infoEmail}}}{{/infoEmail}} + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] diff --git a/samples/client/petstore/lua/.gitignore b/samples/client/petstore/lua/.gitignore new file mode 100644 index 00000000000..180988936c5 --- /dev/null +++ b/samples/client/petstore/lua/.gitignore @@ -0,0 +1,40 @@ +# Compiled Lua sources +luac.out + +# luarocks build files +*.src.rock +*.zip +*.tar.gz + +# Object files +*.o +*.os +*.ko +*.obj +*.elf + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo +*.def +*.exp + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex diff --git a/samples/client/petstore/lua/.swagger-codegen-ignore b/samples/client/petstore/lua/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/lua/.swagger-codegen-ignore @@ -0,0 +1,23 @@ +# Swagger Codegen Ignore +# Generated by swagger-codegen https://github.com/swagger-api/swagger-codegen + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell Swagger Codgen to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/lua/.swagger-codegen/VERSION b/samples/client/petstore/lua/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/lua/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/lua/api/pet_api.lua b/samples/client/petstore/lua/api/pet_api.lua new file mode 100644 index 00000000000..3bc6b8e1c9a --- /dev/null +++ b/samples/client/petstore/lua/api/pet_api.lua @@ -0,0 +1,423 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +--package petstore + +local http_request = require "http.request" +local http_util = require "http.util" +local dkjson = require "dkjson" +local basexx = require "basexx" + +-- model import +local petstore_pet_api = require "petstore.api.pet_api" + +local petstore= {} +local petstore_mt = { + __name = "pet_api"; + __index = petstore; +} + +local function new_pet_api(host, basePath, schemes) + local schemes_map = {} + for _,v in ipairs(schemes) do + schemes_map[v] = v + end + local default_scheme = schemes_map.https or schemes_map.http + return setmetatable({ + host = host; + basePath = basePath or "http://petstore.swagger.io/v2"; + schemes = schemes_map; + default_scheme = default_scheme; + http_username = nil; + http_password = nil; + api_key = {}; + access_token = nil; + }, petstore_mt) +end + +function pet_api:add_pet(body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper accept + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_content_type = { "application/json", "application/xml" } + req.headers:upsert("accept", "application/json") + + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:delete_pet(pet_id, api_key) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet/%s", + self.basePath, pet_id); + }) + + -- set HTTP verb + req.headers:upsert(":method", "DELETE") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req.headers:upsert("api_key", api_key) + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:find_pets_by_status(status) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet/findByStatus?status=%s", + self.basePath, http_util.encodeURIComponent(status)); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + for _, ob in ipairs(result) do + cast_pet(ob) + end + return result, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:find_pets_by_tags(tags) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet/findByTags?tags=%s", + self.basePath, http_util.encodeURIComponent(tags)); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + for _, ob in ipairs(result) do + cast_pet(ob) + end + return result, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:get_pet_by_id(pet_id) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet/%s", + self.basePath, pet_id); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + -- api key in headers 'api_key' + req.headers:upsert("api_key", api_key['api_key']) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return cast_pet(result), headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:update_pet(body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "PUT") + -- TODO: create a function to select proper accept + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_content_type = { "application/json", "application/xml" } + req.headers:upsert("accept", "application/json") + + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:update_pet_with_form(pet_id, name, status) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet/%s", + self.basePath, pet_id); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper accept + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_content_type = { "application/x-www-form-urlencoded" } + req.headers:upsert("accept", "application/x-www-form-urlencoded") + + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(http_util.dict_to_query({ + ["name"] = name; + ["status"] = status; + })) + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function pet_api:upload_file(pet_id, additional_metadata, file) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/pet/%s/uploadImage", + self.basePath, pet_id); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper accept + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_content_type = { "multipart/form-data" } + req.headers:upsert("accept", "multipart/form-data") + + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/json" } + req.headers:upsert("content-type", "application/json") + + req:set_body(http_util.dict_to_query({ + ["additionalMetadata"] = additional_metadata; + ["file"] = file; + })) + -- oAuth + req.headers:upsert("authorization", "Bearer " .. self.access_token) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return cast_api_response(result), headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + diff --git a/samples/client/petstore/lua/api/store_api.lua b/samples/client/petstore/lua/api/store_api.lua new file mode 100644 index 00000000000..fad9f8de747 --- /dev/null +++ b/samples/client/petstore/lua/api/store_api.lua @@ -0,0 +1,221 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +--package petstore + +local http_request = require "http.request" +local http_util = require "http.util" +local dkjson = require "dkjson" +local basexx = require "basexx" + +-- model import +local petstore_store_api = require "petstore.api.store_api" + +local petstore= {} +local petstore_mt = { + __name = "store_api"; + __index = petstore; +} + +local function new_store_api(host, basePath, schemes) + local schemes_map = {} + for _,v in ipairs(schemes) do + schemes_map[v] = v + end + local default_scheme = schemes_map.https or schemes_map.http + return setmetatable({ + host = host; + basePath = basePath or "http://petstore.swagger.io/v2"; + schemes = schemes_map; + default_scheme = default_scheme; + http_username = nil; + http_password = nil; + api_key = {}; + access_token = nil; + }, petstore_mt) +end + +function store_api:delete_order(order_id) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/store/order/%s", + self.basePath, order_id); + }) + + -- set HTTP verb + req.headers:upsert(":method", "DELETE") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function store_api:get_inventory() + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/store/inventory", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/json" } + req.headers:upsert("content-type", "application/json") + + -- api key in headers 'api_key' + req.headers:upsert("api_key", api_key['api_key']) + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return result, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function store_api:get_order_by_id(order_id) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/store/order/%s", + self.basePath, order_id); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return cast_order(result), headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function store_api:place_order(body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/store/order", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return cast_order(result), headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + diff --git a/samples/client/petstore/lua/api/user_api.lua b/samples/client/petstore/lua/api/user_api.lua new file mode 100644 index 00000000000..d48e7e46604 --- /dev/null +++ b/samples/client/petstore/lua/api/user_api.lua @@ -0,0 +1,354 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +--package petstore + +local http_request = require "http.request" +local http_util = require "http.util" +local dkjson = require "dkjson" +local basexx = require "basexx" + +-- model import +local petstore_user_api = require "petstore.api.user_api" + +local petstore= {} +local petstore_mt = { + __name = "user_api"; + __index = petstore; +} + +local function new_user_api(host, basePath, schemes) + local schemes_map = {} + for _,v in ipairs(schemes) do + schemes_map[v] = v + end + local default_scheme = schemes_map.https or schemes_map.http + return setmetatable({ + host = host; + basePath = basePath or "http://petstore.swagger.io/v2"; + schemes = schemes_map; + default_scheme = default_scheme; + http_username = nil; + http_password = nil; + api_key = {}; + access_token = nil; + }, petstore_mt) +end + +function user_api:create_user(body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:create_users_with_array_input(body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/createWithArray", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:create_users_with_list_input(body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/createWithList", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "POST") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:delete_user(username) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/%s", + self.basePath, username); + }) + + -- set HTTP verb + req.headers:upsert(":method", "DELETE") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:get_user_by_name(username) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/%s", + self.basePath, username); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return cast_user(result), headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:login_user(username, password) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/login?username=%s&password=%s", + self.basePath, http_util.encodeURIComponent(username), http_util.encodeURIComponent(password)); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + local body, err, errno2 = stream:get_body_as_string() + -- exception when getting the HTTP body + if not body then + return nil, err, errno2 + end + stream:shutdown() + local result, _, err3 = dkjson.decode(body) + -- exception when decoding the HTTP body + if result == nil then + return nil, err3 + end + return result, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:logout_user() + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/logout", + self.basePath); + }) + + -- set HTTP verb + req.headers:upsert(":method", "GET") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + +function user_api:update_user(username, body) + local req = http_request.new_from_uri({ + scheme = self.default_scheme; + host = self.host; + path = string.format("%s/user/%s", + self.basePath, username); + }) + + -- set HTTP verb + req.headers:upsert(":method", "PUT") + -- TODO: create a function to select proper content-type + -- ref: https://github.com/swagger-api/swagger-codegen/pull/6252#issuecomment-321199879 + --local var_accept = { "application/xml", "application/json" } + req.headers:upsert("content-type", "application/xml") + + req:set_body(dkjson.encode(body)) + + + -- make the HTTP call + local headers, stream, errno = req:go() + if not headers then + return nil, stream, errno + end + local http_status = headers:get(":status") + if http_status:sub(1,1) == "2" then + return nil, headers + else + local body, err, errno2 = stream:get_body_as_string() + if not body then + return nil, err, errno2 + end + stream:shutdown() + -- return the error message (http body) + return nil, http_status, body + end +end + diff --git a/samples/client/petstore/lua/git_push.sh b/samples/client/petstore/lua/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/lua/git_push.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 swagger-petstore-perl "minor update" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git crediential in your environment." + git remote add origin https://github.com/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@github.com/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://github.com/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/lua/model/api_response.lua b/samples/client/petstore/lua/model/api_response.lua new file mode 100644 index 00000000000..4f4572654ba --- /dev/null +++ b/samples/client/petstore/lua/model/api_response.lua @@ -0,0 +1,33 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +-- api_response class +local api_response = {} +local api_response_mt = { + __name = "api_response"; + __index = api_response; +} + +local function cast_api_response(t) + return setmetatable(t, api_response_mt) +end + +local function new_api_response(code, type, message) + return cast_api_response({ + ["code"] = code; + ["type"] = type; + ["message"] = message; + }) +end + +return { + cast = cast_api_response; + new = new_api_response; +} diff --git a/samples/client/petstore/lua/model/category.lua b/samples/client/petstore/lua/model/category.lua new file mode 100644 index 00000000000..96d7f56299a --- /dev/null +++ b/samples/client/petstore/lua/model/category.lua @@ -0,0 +1,32 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +-- category class +local category = {} +local category_mt = { + __name = "category"; + __index = category; +} + +local function cast_category(t) + return setmetatable(t, category_mt) +end + +local function new_category(id, name) + return cast_category({ + ["id"] = id; + ["name"] = name; + }) +end + +return { + cast = cast_category; + new = new_category; +} diff --git a/samples/client/petstore/lua/model/order.lua b/samples/client/petstore/lua/model/order.lua new file mode 100644 index 00000000000..a6346a326cc --- /dev/null +++ b/samples/client/petstore/lua/model/order.lua @@ -0,0 +1,36 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +-- order class +local order = {} +local order_mt = { + __name = "order"; + __index = order; +} + +local function cast_order(t) + return setmetatable(t, order_mt) +end + +local function new_order(id, pet_id, quantity, ship_date, status, complete) + return cast_order({ + ["id"] = id; + ["petId"] = pet_id; + ["quantity"] = quantity; + ["shipDate"] = ship_date; + ["status"] = status; + ["complete"] = complete; + }) +end + +return { + cast = cast_order; + new = new_order; +} diff --git a/samples/client/petstore/lua/model/pet.lua b/samples/client/petstore/lua/model/pet.lua new file mode 100644 index 00000000000..763bc79f3cb --- /dev/null +++ b/samples/client/petstore/lua/model/pet.lua @@ -0,0 +1,36 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +-- pet class +local pet = {} +local pet_mt = { + __name = "pet"; + __index = pet; +} + +local function cast_pet(t) + return setmetatable(t, pet_mt) +end + +local function new_pet(id, category, name, photo_urls, tags, status) + return cast_pet({ + ["id"] = id; + ["category"] = category; + ["name"] = name; + ["photoUrls"] = photo_urls; + ["tags"] = tags; + ["status"] = status; + }) +end + +return { + cast = cast_pet; + new = new_pet; +} diff --git a/samples/client/petstore/lua/model/tag.lua b/samples/client/petstore/lua/model/tag.lua new file mode 100644 index 00000000000..3d8fb67e680 --- /dev/null +++ b/samples/client/petstore/lua/model/tag.lua @@ -0,0 +1,32 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +-- tag class +local tag = {} +local tag_mt = { + __name = "tag"; + __index = tag; +} + +local function cast_tag(t) + return setmetatable(t, tag_mt) +end + +local function new_tag(id, name) + return cast_tag({ + ["id"] = id; + ["name"] = name; + }) +end + +return { + cast = cast_tag; + new = new_tag; +} diff --git a/samples/client/petstore/lua/model/user.lua b/samples/client/petstore/lua/model/user.lua new file mode 100644 index 00000000000..674555f48ad --- /dev/null +++ b/samples/client/petstore/lua/model/user.lua @@ -0,0 +1,38 @@ +--[[ + Swagger Petstore + + This is a sample server Petstore server. You can find out more about Swagger at [http://swagger.io](http://swagger.io) or on [irc.freenode.net, #swagger](http://swagger.io/irc/). For this sample, you can use the api key `special-key` to test the authorization filters. + + OpenAPI spec version: 1.0.0 + Contact: apiteam@swagger.io + Generated by: https://github.com/swagger-api/swagger-codegen.git +]] + +-- user class +local user = {} +local user_mt = { + __name = "user"; + __index = user; +} + +local function cast_user(t) + return setmetatable(t, user_mt) +end + +local function new_user(id, username, first_name, last_name, email, password, phone, user_status) + return cast_user({ + ["id"] = id; + ["username"] = username; + ["firstName"] = first_name; + ["lastName"] = last_name; + ["email"] = email; + ["password"] = password; + ["phone"] = phone; + ["userStatus"] = user_status; + }) +end + +return { + cast = cast_user; + new = new_user; +}