From a4c0975aa47e521bd8084bca6e94334e463acd74 Mon Sep 17 00:00:00 2001 From: wing328 Date: Mon, 4 Sep 2017 00:21:32 +0800 Subject: [PATCH] [R] Add new R client generator (#6351) * add r client codegen * update r api, model templates * various fix * rename Json to JSON * more enhancements * fix json handling * add file upload support, var name to handle hyphen * use httr::upload_file --- bin/r-petstore.sh | 31 ++ bin/windows/r-petstore.bat | 10 + .../io/swagger/codegen/CodegenParameter.java | 6 +- .../io/swagger/codegen/CodegenProperty.java | 6 +- .../io/swagger/codegen/CodegenResponse.java | 6 +- .../io/swagger/codegen/DefaultCodegen.java | 21 +- .../codegen/languages/RClientCodegen.java | 450 ++++++++++++++++++ .../services/io.swagger.codegen.CodegenConfig | 1 + .../src/main/resources/r/.travis.yml | 3 + .../src/main/resources/r/README.mustache | 27 ++ .../main/resources/r/Rbuildignore.mustache | 2 + .../src/main/resources/r/api.mustache | 60 +++ .../src/main/resources/r/api_doc.mustache | 50 ++ .../src/main/resources/r/description.mustache | 12 + .../src/main/resources/r/git_push.sh.mustache | 52 ++ .../src/main/resources/r/gitignore.mustache | 35 ++ .../src/main/resources/r/model.mustache | 140 ++++++ .../src/main/resources/r/model_doc.mustache | 11 + .../src/main/resources/r/namespace.mustache | 0 .../main/resources/r/partial_header.mustache | 11 + samples/client/petstore/r_test/.Rbuildignore | 2 + samples/client/petstore/r_test/.gitignore | 35 ++ .../petstore/r_test/.swagger-codegen-ignore | 23 + .../petstore/r_test/.swagger-codegen/VERSION | 1 + samples/client/petstore/r_test/.travis.yml | 3 + samples/client/petstore/r_test/DESCRIPTION | 12 + .../client/petstore/r_test/R/ApiResponse.r | 93 ++++ samples/client/petstore/r_test/R/Category.r | 85 ++++ samples/client/petstore/r_test/R/Order.r | 116 +++++ samples/client/petstore/r_test/R/Pet.r | 120 +++++ samples/client/petstore/r_test/R/PetApi.r | 152 ++++++ samples/client/petstore/r_test/R/StoreApi.r | 82 ++++ samples/client/petstore/r_test/R/Tag.r | 85 ++++ samples/client/petstore/r_test/R/User.r | 133 ++++++ samples/client/petstore/r_test/R/UserApi.r | 143 ++++++ samples/client/petstore/r_test/README.md | 19 + samples/client/petstore/r_test/git_push.sh | 52 ++ 37 files changed, 2073 insertions(+), 17 deletions(-) create mode 100755 bin/r-petstore.sh create mode 100755 bin/windows/r-petstore.bat create mode 100644 modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RClientCodegen.java create mode 100644 modules/swagger-codegen/src/main/resources/r/.travis.yml create mode 100644 modules/swagger-codegen/src/main/resources/r/README.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/Rbuildignore.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/api.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/api_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/description.mustache create mode 100755 modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/gitignore.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/model.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/model_doc.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/namespace.mustache create mode 100644 modules/swagger-codegen/src/main/resources/r/partial_header.mustache create mode 100644 samples/client/petstore/r_test/.Rbuildignore create mode 100644 samples/client/petstore/r_test/.gitignore create mode 100644 samples/client/petstore/r_test/.swagger-codegen-ignore create mode 100644 samples/client/petstore/r_test/.swagger-codegen/VERSION create mode 100644 samples/client/petstore/r_test/.travis.yml create mode 100644 samples/client/petstore/r_test/DESCRIPTION create mode 100644 samples/client/petstore/r_test/R/ApiResponse.r create mode 100644 samples/client/petstore/r_test/R/Category.r create mode 100644 samples/client/petstore/r_test/R/Order.r create mode 100644 samples/client/petstore/r_test/R/Pet.r create mode 100644 samples/client/petstore/r_test/R/PetApi.r create mode 100644 samples/client/petstore/r_test/R/StoreApi.r create mode 100644 samples/client/petstore/r_test/R/Tag.r create mode 100644 samples/client/petstore/r_test/R/User.r create mode 100644 samples/client/petstore/r_test/R/UserApi.r create mode 100644 samples/client/petstore/r_test/README.md create mode 100644 samples/client/petstore/r_test/git_push.sh diff --git a/bin/r-petstore.sh b/bin/r-petstore.sh new file mode 100755 index 00000000000..6e00e6010e2 --- /dev/null +++ b/bin/r-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/r -i modules/swagger-codegen/src/test/resources/2_0/petstore.yaml -l r -o samples/client/petstore/r_test -DpackageName=petstore $@" + +java $JAVA_OPTS -jar $executable $ags diff --git a/bin/windows/r-petstore.bat b/bin/windows/r-petstore.bat new file mode 100755 index 00000000000..07b8194d76f --- /dev/null +++ b/bin/windows/r-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 r -o samples\client\petstore\r + +java %JAVA_OPTS% -jar %executable% %ags% diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java index b5acd8fc85c..008a01b5586 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenParameter.java @@ -14,7 +14,7 @@ public class CodegenParameter { public String example; // example value (x-example) public String jsonSchema; - public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid; + public boolean isString, isNumeric, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid; public boolean isListContainer, isMapContainer; public boolean isFile, notFile; public boolean isEnum; @@ -133,6 +133,7 @@ public class CodegenParameter { output.isBinary = this.isBinary; output.isByteArray = this.isByteArray; output.isString = this.isString; + output.isNumeric = this.isNumeric; output.isInteger = this.isInteger; output.isLong = this.isLong; output.isDouble = this.isDouble; @@ -210,6 +211,8 @@ public class CodegenParameter { return false; if (isString != that.isString) return false; + if (isNumeric != that.isNumeric) + return false; if (isInteger != that.isInteger) return false; if (isLong != that.isLong) @@ -299,6 +302,7 @@ public class CodegenParameter { result = 31 * result + (example != null ? example.hashCode() : 0); result = 31 * result + (jsonSchema != null ? jsonSchema.hashCode() : 0); result = 31 * result + (isString ? 13:31); + result = 31 * result + (isNumeric ? 13:31); result = 31 * result + (isInteger ? 13:31); result = 31 * result + (isLong ? 13:31); result = 31 * result + (isFloat ? 13:31); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java index 018b85695cf..243b5b930fa 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenProperty.java @@ -39,7 +39,7 @@ public class CodegenProperty implements Cloneable { public boolean hasMore, required, secondaryParam; public boolean hasMoreNonReadOnly; // for model constructor, true if next properyt is not readonly public boolean isPrimitiveType, isContainer, isNotContainer; - public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid; + public boolean isString, isNumeric, isInteger, isLong, isFloat, isDouble, isByteArray, isBinary, isFile, isBoolean, isDate, isDateTime, isUuid; public boolean isListContainer, isMapContainer; public boolean isEnum; public boolean isReadOnly = false; @@ -115,6 +115,7 @@ public class CodegenProperty implements Cloneable { result = prime * result + ((vendorExtensions == null) ? 0 : vendorExtensions.hashCode()); result = prime * result + ((hasValidation ? 13:31)); result = prime * result + ((isString ? 13:31)); + result = prime * result + ((isNumeric ? 13:31)); result = prime * result + ((isInteger ? 13:31)); result = prime * result + ((isLong ?13:31)); result = prime * result + ((isFloat ? 13:31)); @@ -261,6 +262,9 @@ public class CodegenProperty implements Cloneable { return false; } + if (this.isNumeric != other.isNumeric) { + return false; + } if (this.isInteger != other.isInteger) { return false; } diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java index f01b14bdda7..1b2b74214d0 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/CodegenResponse.java @@ -11,7 +11,7 @@ public class CodegenResponse { public List> examples; public String dataType, baseType, containerType; public boolean hasHeaders; - public boolean isString, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid; + public boolean isString, isNumeric, isInteger, isLong, isFloat, isDouble, isByteArray, isBoolean, isDate, isDateTime, isUuid; public boolean isDefault; public boolean simpleType; public boolean primitiveType; @@ -69,12 +69,13 @@ public class CodegenResponse { return false; if (isFile != that.isFile) return false; + if (isNumeric != that.isNumeric) + return false; if (schema != null ? !schema.equals(that.schema) : that.schema != null) return false; if (vendorExtensions != null ? !vendorExtensions.equals(that.vendorExtensions) : that.vendorExtensions != null) return false; return jsonSchema != null ? jsonSchema.equals(that.jsonSchema) : that.jsonSchema == null; - } @Override @@ -88,6 +89,7 @@ public class CodegenResponse { result = 31 * result + (baseType != null ? baseType.hashCode() : 0); result = 31 * result + (containerType != null ? containerType.hashCode() : 0); result = 31 * result + (isDefault ? 13:31); + result = 31 * result + (isNumeric ? 13:31); result = 31 * result + (simpleType ? 13:31); result = 31 * result + (primitiveType ? 13:31); result = 31 * result + (isMapContainer ? 13:31); diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java index 90ed4ab5e26..3bd8e2e9041 100644 --- a/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/DefaultCodegen.java @@ -1647,19 +1647,7 @@ public class DefaultCodegen { if (p instanceof BaseIntegerProperty && !(p instanceof IntegerProperty) && !(p instanceof LongProperty)) { BaseIntegerProperty sp = (BaseIntegerProperty) p; property.isInteger = true; - /*if (sp.getEnum() != null) { - List _enum = sp.getEnum(); - property._enum = new ArrayList(); - for(Integer i : _enum) { - property._enum.add(i.toString()); - } - property.isEnum = true; - - // legacy support - Map allowableValues = new HashMap(); - allowableValues.put("values", _enum); - property.allowableValues = allowableValues; - }*/ + property.isNumeric = true; } if (p instanceof IntegerProperty) { IntegerProperty sp = (IntegerProperty) p; @@ -1681,6 +1669,7 @@ public class DefaultCodegen { if (p instanceof LongProperty) { LongProperty sp = (LongProperty) p; property.isLong = true; + property.isNumeric = true; if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); @@ -1734,6 +1723,7 @@ public class DefaultCodegen { if (p instanceof DoubleProperty) { DoubleProperty sp = (DoubleProperty) p; property.isDouble = true; + property.isNumeric = true; if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); @@ -1751,6 +1741,7 @@ public class DefaultCodegen { if (p instanceof FloatProperty) { FloatProperty sp = (FloatProperty) p; property.isFloat = true; + property.isNumeric = true; if (sp.getEnum() != null) { List _enum = sp.getEnum(); property._enum = new ArrayList(); @@ -2385,12 +2376,16 @@ public class DefaultCodegen { r.isBoolean = true; } else if (Boolean.TRUE.equals(cm.isLong)) { r.isLong = true; + r.isNumeric = true; } else if (Boolean.TRUE.equals(cm.isInteger)) { r.isInteger = true; + r.isNumeric = true; } else if (Boolean.TRUE.equals(cm.isDouble)) { r.isDouble = true; + r.isNumeric = true; } else if (Boolean.TRUE.equals(cm.isFloat)) { r.isFloat = true; + r.isNumeric = true; } else if (Boolean.TRUE.equals(cm.isByteArray)) { r.isByteArray = true; } else if (Boolean.TRUE.equals(cm.isBinary)) { diff --git a/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RClientCodegen.java b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RClientCodegen.java new file mode 100644 index 00000000000..087b4d0c8fd --- /dev/null +++ b/modules/swagger-codegen/src/main/java/io/swagger/codegen/languages/RClientCodegen.java @@ -0,0 +1,450 @@ +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 RClientCodegen extends DefaultCodegen implements CodegenConfig { + static Logger LOGGER = LoggerFactory.getLogger(RClientCodegen.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 "r"; + } + + public String getHelp() { + return "Generates a R client library (beta)."; + } + + public RClientCodegen() { + super(); + outputFolder = "generated-code/r"; + modelTemplateFiles.put("model.mustache", ".r"); + apiTemplateFiles.put("api.mustache", ".r"); + + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + + embeddedTemplateDir = templateDir = "r"; + + setReservedWordsLowerCase( + Arrays.asList( + // reserved words: https://stat.ethz.ch/R-manual/R-devel/library/base/html/Reserved.html + "if", "else", "repeat", "while", "function", "for", "in", + "next", "break", "TRUE", "FALSE", "NULL", "Inf", "NaN", + "NA", "NA_integer_", "NA_real_", "NA_complex_", "NA_character_" + ) + ); + + defaultIncludes = new HashSet( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet( + Arrays.asList( + "Integer", + "Numeric", + "Character") + ); + + instantiationTypes.clear(); + + typeMapping.clear(); + typeMapping.put("integer", "Integer"); + typeMapping.put("long", "Integer"); + typeMapping.put("number", "Numeric"); + typeMapping.put("float", "Numeric"); + typeMapping.put("double", "Numeric"); + typeMapping.put("boolean", "Character"); + typeMapping.put("string", "Character"); + typeMapping.put("UUID", "Character"); + typeMapping.put("date", "Character"); + typeMapping.put("DateTime", "Character"); + typeMapping.put("password", "Character"); + typeMapping.put("file", "TODO_FILE_MAPPING"); + // map binary to string as a workaround + // the correct solution is to use []byte + typeMapping.put("binary", "Character"); + typeMapping.put("ByteArray", "Character"); + typeMapping.put("object", "TODO_OBJECT_MAPPING"); + + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, "R package name (convention: lowercase).") + .defaultValue("swagger")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, "R 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("description.mustache", "", "DESCRIPTION")); + supportingFiles.add(new SupportingFile("Rbuildignore.mustache", "", ".Rbuildignore")); + 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 R 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 + "R" + File.separator; + } + + public String modelFileFolder() { + return outputFolder + File.separator + "R" + 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 " + camelize("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 " + camelize("model_" + name)); + name = "model_" + name; // e.g. 200Response => Model200Response (after camelize) + } + + return camelize(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.r => pet_api.r + return camelize(name + "_api"); + } + + @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 camelize(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 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 c9a01a179f6..fc1593b463d 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 @@ -50,6 +50,7 @@ io.swagger.codegen.languages.PowerShellClientCodegen io.swagger.codegen.languages.PistacheServerCodegen io.swagger.codegen.languages.PythonClientCodegen io.swagger.codegen.languages.Qt5CPPGenerator +io.swagger.codegen.languages.RClientCodegen io.swagger.codegen.languages.Rails5ServerCodegen io.swagger.codegen.languages.RestbedCodegen io.swagger.codegen.languages.RubyClientCodegen diff --git a/modules/swagger-codegen/src/main/resources/r/.travis.yml b/modules/swagger-codegen/src/main/resources/r/.travis.yml new file mode 100644 index 00000000000..3f05544a724 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/.travis.yml @@ -0,0 +1,3 @@ +# ref: https://docs.travis-ci.com/user/languages/r/ +language: r +cache: packages diff --git a/modules/swagger-codegen/src/main/resources/r/README.mustache b/modules/swagger-codegen/src/main/resources/r/README.mustache new file mode 100644 index 00000000000..0bf65d4f3ab --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/README.mustache @@ -0,0 +1,27 @@ +# R 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 [OpenAPI/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 + +TODO + +## Author + +{{#apiInfo}}{{#apis}}{{^hasMore}}{{infoEmail}} +{{/hasMore}}{{/apis}}{{/apiInfo}} diff --git a/modules/swagger-codegen/src/main/resources/r/Rbuildignore.mustache b/modules/swagger-codegen/src/main/resources/r/Rbuildignore.mustache new file mode 100644 index 00000000000..91114bf2f2b --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/Rbuildignore.mustache @@ -0,0 +1,2 @@ +^.*\.Rproj$ +^\.Rproj\.user$ diff --git a/modules/swagger-codegen/src/main/resources/r/api.mustache b/modules/swagger-codegen/src/main/resources/r/api.mustache new file mode 100644 index 00000000000..b863deee4d0 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/api.mustache @@ -0,0 +1,60 @@ +{{>partial_header}} +{{#operations}} +{{classname}} <- R6::R6Class( + '{{classname}}', + public = list( + userAgent = "{{#httpUserAgent}}{{{.}}}{{/httpUserAgent}}{{^httpUserAgent}}Swagger-Codegen/{{{packageVersion}}}/r{{/httpUserAgent}}", + basePath = "{{{basePath}}}", + initialize = function(basePath){ + if (!missing(basePath)) { + stopifnot(is.character(basePath), length(basePath) == 1) + self$basePath <- basePath + } + }, + + {{#operation}} + {{operationId}} = function({{#allParams}}{{paramName}}{{#hasMore}}, {{/hasMore}}{{/allParams}}){ + resp <- httr::{{httpMethod}}(paste0(self$basePath{{#pathParams}}, {{paramName}}{{/pathParams}}), + httr::add_headers("User-Agent" = self$userAgent{{#hasConsumes}}, "accept" = "{{#consumes}}{{#-first}}{{{mediaType}}}{{/-first}}{{/consumes}}"{{/hasConsumes}}{{#hasProduces}}, "content-type" = "{{#produces}}{{#-first}}{{{mediaType}}}{{/-first}}{{/produces}}"{{/hasProduces}}{{#headerParams}}, "{{baseName}}" = {{paramName}}{{/headerParams}}) + {{#hasFormParams}} + ,body = list( + {{#formParams}} + {{^isFile}} + "{{baseName}}" = {{paramName}}{{#hasMore}},{{/hasMore}} + {{/isFile}} + {{#isFile}} + "{{baseName}}" = httr::upload_file({{paramName}}){{#hasMore}},{{/hasMore}} + {{/isFile}} + {{/formParams}} + ) + {{/hasFormParams}} + {{#bodyParams}} + ,body = {{paramName}}$toJSON() + {{/bodyParams}} + {{#hasQueryParams}} + ,query = list( + {{#queryParams}} + "{{baseName}}" = {{paramName}}{{#hasMore}},{{/hasMore}} + {{/queryParams}} + {{/hasQueryParams}} + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + {{#returnType}} + result <- {{returnType}}$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + {{/returnType}} + {{^returnType}} + # void response, no need to return anything + {{/returnType}} + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }{{#hasMore}},{{/hasMore}} + {{/operation}} + ) +) +{{/operations}} diff --git a/modules/swagger-codegen/src/main/resources/r/api_doc.mustache b/modules/swagger-codegen/src/main/resources/r/api_doc.mustache new file mode 100644 index 00000000000..70d0b96ce86 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/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/r/description.mustache b/modules/swagger-codegen/src/main/resources/r/description.mustache new file mode 100644 index 00000000000..d79645cdafe --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/description.mustache @@ -0,0 +1,12 @@ +Package: {{{packageName}}} +Title: R Package Client for {{{appName}}} +Version: {{packageVersion}} +Authors@R: person("Swagger Codegen community", email = "apiteam@swagger.io", role = c("aut", "cre")) +Description: {{{appDescription}}}{{^appDescription}}R Package Client for {{{appName}}}{{/appDescription}} +Depends: R (>= 3.3.3) +Encoding: UTF-8 +License: Unlicense +LazyData: true +Suggests: testthat +Imports: jsonlite, httr, R6 +RoxygenNote: 6.0.1.9000 diff --git a/modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache b/modules/swagger-codegen/src/main/resources/r/git_push.sh.mustache new file mode 100755 index 00000000000..e153ce23ecf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/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/r/gitignore.mustache b/modules/swagger-codegen/src/main/resources/r/gitignore.mustache new file mode 100644 index 00000000000..5d21150e0ca --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/gitignore.mustache @@ -0,0 +1,35 @@ +# ref: https://github.com/github/gitignore/blob/master/R.gitignore + +# History files +.Rhistory +.Rapp.history + +# Session Data files +.RData + +# Example code in package build process +*-Ex.R + +# Output files from R CMD build +/*.tar.gz + +# Output files from R CMD check +/*.Rcheck/ + +# RStudio files +.Rproj.user/ + +# produced vignettes +vignettes/*.html +vignettes/*.pdf + +# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 +.httr-oauth + +# knitr and R markdown default cache directories +/*_cache/ +/cache/ + +# Temporary files created by R markdown +*.utf8.md +*.knit.md diff --git a/modules/swagger-codegen/src/main/resources/r/model.mustache b/modules/swagger-codegen/src/main/resources/r/model.mustache new file mode 100644 index 00000000000..dcd3fa4febf --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/model.mustache @@ -0,0 +1,140 @@ +{{#models}} +{{#model}} +{{>partial_header}} + + +#' {{classname}} Class +#' @export +{{classname}} <- R6::R6Class( + '{{classname}}', + public = list( + {{#vars}} + `{{{baseName}}}` = NULL, + {{/vars}} + initialize = function({{#vars}}`{{baseName}}`{{#hasMore}}, {{/hasMore}}{{/vars}}){ + {{#vars}} + if (!missing(`{{baseName}}`)) { + {{^isListContainer}} + {{#isInteger}} + stopifnot(is.numeric(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isInteger}} + {{#isLong}} + stopifnot(is.numeric(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isLong}} + {{#isFloat}} + stopifnot(is.numeric(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isFloat}} + {{#isDouble}} + stopifnot(is.numeric(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isDouble}} + {{#isString}} + stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isString}} + {{#isDate}} + stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isDate}} + {{#isDateTime}} + stopifnot(is.character(`{{baseName}}`), length(`{{baseName}}`) == 1) + {{/isDateTime}} + {{^isPrimitiveType}} + stopifnot(is.list(tags), length(tags) != 0) + lapply(`{{baseName}}`, function(x) stopifnot("Element" %in% class(x), !is.list(x))) + {{/isPrimitiveType}} + {{/isListContainer}} + {{#isListContainer}} + {{#isPrimitiveType}} + stopifnot(is.list(`{{baseName}}`), length(`{{baseName}}`) != 0) + lapply(`{{baseName}}`, function(x) stopifnot(is.character(x))) + {{/isPrimitiveType}} + {{^isPrimitiveType}} + stopifnot(is.list(tags), length(tags) != 0) + lapply(`{{baseName}}`, function(x) stopifnot("Element" %in% class(x), !is.list(x))) + {{/isPrimitiveType}} + {{/isListContainer}} + self$`{{baseName}}` <- `{{baseName}}` + } + {{/vars}} + }, + toJSON = function() { + sprintf( + '{ + {{#vars}} + "{{baseName}}": {{#isListContainer}}[{{/isListContainer}}{{#isPrimitiveType}}{{#isNumeric}}%d{{/isNumeric}}{{^isNumeric}}"%s"{{/isNumeric}}{{/isPrimitiveType}}{{^isPrimitiveType}}%s{{/isPrimitiveType}}{{#isListContainer}}]{{/isListContainer}}{{#hasMore}},{{/hasMore}} + {{/vars}} + }', + {{#vars}} + {{#isListContainer}} + {{#isPrimitiveType}} + lapply(self$`{{baseName}}`, function(x) paste(paste0('"', x, '"'), sep=",")){{#hasMore}},{{/hasMore}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + lapply(self$`{{baseName}}`, function(x) paste(x$toJSON(), sep=",")){{#hasMore}},{{/hasMore}} + {{/isPrimitiveType}} + {{/isListContainer}} + {{^isListContainer}} + self$`{{baseName}}`{{^isPrimitiveType}}$toJSON(){{/isPrimitiveType}}{{#hasMore}},{{/hasMore}} + {{/isListContainer}} + {{/vars}} + ) + }, + fromJSON = function({{classname}}Json) { + {{classname}}Object <- jsonlite::fromJSON({{classname}}Json) + {{#vars}} + {{#isPrimitiveType}} + self$`{{baseName}}` <- {{classname}}Object`${{baseName}}` + {{/isPrimitiveType}} + {{^isPrimitiveType}} + {{#isListContainer}} + self$`{{baseName}}` <- lapply({{classname}}Object$`{{baseName}}`, function(x) {{datatype}}$new()$fromJSON(jsonlite::toJSON(x)) + {{/isListContainer}} + {{^isListContainer}} + self$`{{baseName}}` <- {{datatype}}$new()$fromJSON(jsonlite::toJSON({{classname}}Object${{baseName})) + {{/isListContainer}} + {{/isPrimitiveType}} + {{/vars}} + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) +{{/model}} +{{/models}} diff --git a/modules/swagger-codegen/src/main/resources/r/model_doc.mustache b/modules/swagger-codegen/src/main/resources/r/model_doc.mustache new file mode 100644 index 00000000000..25537b2c5ed --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/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/r/namespace.mustache b/modules/swagger-codegen/src/main/resources/r/namespace.mustache new file mode 100644 index 00000000000..e69de29bb2d diff --git a/modules/swagger-codegen/src/main/resources/r/partial_header.mustache b/modules/swagger-codegen/src/main/resources/r/partial_header.mustache new file mode 100644 index 00000000000..0e69c393243 --- /dev/null +++ b/modules/swagger-codegen/src/main/resources/r/partial_header.mustache @@ -0,0 +1,11 @@ +{{#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/r_test/.Rbuildignore b/samples/client/petstore/r_test/.Rbuildignore new file mode 100644 index 00000000000..91114bf2f2b --- /dev/null +++ b/samples/client/petstore/r_test/.Rbuildignore @@ -0,0 +1,2 @@ +^.*\.Rproj$ +^\.Rproj\.user$ diff --git a/samples/client/petstore/r_test/.gitignore b/samples/client/petstore/r_test/.gitignore new file mode 100644 index 00000000000..5d21150e0ca --- /dev/null +++ b/samples/client/petstore/r_test/.gitignore @@ -0,0 +1,35 @@ +# ref: https://github.com/github/gitignore/blob/master/R.gitignore + +# History files +.Rhistory +.Rapp.history + +# Session Data files +.RData + +# Example code in package build process +*-Ex.R + +# Output files from R CMD build +/*.tar.gz + +# Output files from R CMD check +/*.Rcheck/ + +# RStudio files +.Rproj.user/ + +# produced vignettes +vignettes/*.html +vignettes/*.pdf + +# OAuth2 token, see https://github.com/hadley/httr/releases/tag/v0.3 +.httr-oauth + +# knitr and R markdown default cache directories +/*_cache/ +/cache/ + +# Temporary files created by R markdown +*.utf8.md +*.knit.md diff --git a/samples/client/petstore/r_test/.swagger-codegen-ignore b/samples/client/petstore/r_test/.swagger-codegen-ignore new file mode 100644 index 00000000000..c5fa491b4c5 --- /dev/null +++ b/samples/client/petstore/r_test/.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/r_test/.swagger-codegen/VERSION b/samples/client/petstore/r_test/.swagger-codegen/VERSION new file mode 100644 index 00000000000..f9f7450d135 --- /dev/null +++ b/samples/client/petstore/r_test/.swagger-codegen/VERSION @@ -0,0 +1 @@ +2.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/r_test/.travis.yml b/samples/client/petstore/r_test/.travis.yml new file mode 100644 index 00000000000..3f05544a724 --- /dev/null +++ b/samples/client/petstore/r_test/.travis.yml @@ -0,0 +1,3 @@ +# ref: https://docs.travis-ci.com/user/languages/r/ +language: r +cache: packages diff --git a/samples/client/petstore/r_test/DESCRIPTION b/samples/client/petstore/r_test/DESCRIPTION new file mode 100644 index 00000000000..a4aa2089c8b --- /dev/null +++ b/samples/client/petstore/r_test/DESCRIPTION @@ -0,0 +1,12 @@ +Package: petstore +Title: R Package Client for Swagger Petstore +Version: 1.0.0 +Authors@R: person("Swagger Codegen community", email = "apiteam@swagger.io", role = c("aut", "cre")) +Description: 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. +Depends: R (>= 3.3.3) +Encoding: UTF-8 +License: Unlicense +LazyData: true +Suggests: testthat +Imports: jsonlite, httr, R6 +RoxygenNote: 6.0.1.9000 diff --git a/samples/client/petstore/r_test/R/ApiResponse.r b/samples/client/petstore/r_test/R/ApiResponse.r new file mode 100644 index 00000000000..1b6c3d578e9 --- /dev/null +++ b/samples/client/petstore/r_test/R/ApiResponse.r @@ -0,0 +1,93 @@ +# 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 + + + +#' ApiResponse Class +#' @export +ApiResponse <- R6::R6Class( + 'ApiResponse', + public = list( + `code` = NULL, + `type` = NULL, + `message` = NULL, + initialize = function(`code`, `type`, `message`){ + if (!missing(`code`)) { + stopifnot(is.numeric(`code`), length(`code`) == 1) + self$`code` <- `code` + } + if (!missing(`type`)) { + stopifnot(is.character(`type`), length(`type`) == 1) + self$`type` <- `type` + } + if (!missing(`message`)) { + stopifnot(is.character(`message`), length(`message`) == 1) + self$`message` <- `message` + } + }, + toJSON = function() { + sprintf( + '{ + "code": "%s", + "type": "%s", + "message": "%s" + }', + self$`code`, + self$`type`, + self$`message` + ) + }, + fromJSON = function(ApiResponseJson) { + ApiResponseObject <- jsonlite::fromJSON(ApiResponseJson) + self$`code` <- ApiResponseObject`$code` + self$`type` <- ApiResponseObject`$type` + self$`message` <- ApiResponseObject`$message` + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) diff --git a/samples/client/petstore/r_test/R/Category.r b/samples/client/petstore/r_test/R/Category.r new file mode 100644 index 00000000000..61884d89ec6 --- /dev/null +++ b/samples/client/petstore/r_test/R/Category.r @@ -0,0 +1,85 @@ +# 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 +#' @export +Category <- R6::R6Class( + 'Category', + public = list( + `id` = NULL, + `name` = NULL, + initialize = function(`id`, `name`){ + if (!missing(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!missing(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + }, + toJSON = function() { + sprintf( + '{ + "id": %d, + "name": "%s" + }', + self$`id`, + self$`name` + ) + }, + fromJSON = function(CategoryJson) { + CategoryObject <- jsonlite::fromJSON(CategoryJson) + self$`id` <- CategoryObject`$id` + self$`name` <- CategoryObject`$name` + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) diff --git a/samples/client/petstore/r_test/R/Order.r b/samples/client/petstore/r_test/R/Order.r new file mode 100644 index 00000000000..4a5fc9ac699 --- /dev/null +++ b/samples/client/petstore/r_test/R/Order.r @@ -0,0 +1,116 @@ +# 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 +#' @export +Order <- R6::R6Class( + 'Order', + public = list( + `id` = NULL, + `petId` = NULL, + `quantity` = NULL, + `shipDate` = NULL, + `status` = NULL, + `complete` = NULL, + initialize = function(`id`, `petId`, `quantity`, `shipDate`, `status`, `complete`){ + if (!missing(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!missing(`petId`)) { + stopifnot(is.numeric(`petId`), length(`petId`) == 1) + self$`petId` <- `petId` + } + if (!missing(`quantity`)) { + stopifnot(is.numeric(`quantity`), length(`quantity`) == 1) + self$`quantity` <- `quantity` + } + if (!missing(`shipDate`)) { + stopifnot(is.character(`shipDate`), length(`shipDate`) == 1) + self$`shipDate` <- `shipDate` + } + if (!missing(`status`)) { + stopifnot(is.character(`status`), length(`status`) == 1) + self$`status` <- `status` + } + if (!missing(`complete`)) { + self$`complete` <- `complete` + } + }, + toJSON = function() { + sprintf( + '{ + "id": %d, + "petId": %d, + "quantity": "%s", + "shipDate": "%s", + "status": "%s", + "complete": "%s" + }', + self$`id`, + self$`petId`, + self$`quantity`, + self$`shipDate`, + self$`status`, + self$`complete` + ) + }, + fromJSON = function(OrderJson) { + OrderObject <- jsonlite::fromJSON(OrderJson) + self$`id` <- OrderObject`$id` + self$`petId` <- OrderObject`$petId` + self$`quantity` <- OrderObject`$quantity` + self$`shipDate` <- OrderObject`$shipDate` + self$`status` <- OrderObject`$status` + self$`complete` <- OrderObject`$complete` + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) diff --git a/samples/client/petstore/r_test/R/Pet.r b/samples/client/petstore/r_test/R/Pet.r new file mode 100644 index 00000000000..45ed0edca97 --- /dev/null +++ b/samples/client/petstore/r_test/R/Pet.r @@ -0,0 +1,120 @@ +# 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 +#' @export +Pet <- R6::R6Class( + 'Pet', + public = list( + `id` = NULL, + `category` = NULL, + `name` = NULL, + `photoUrls` = NULL, + `tags` = NULL, + `status` = NULL, + initialize = function(`id`, `category`, `name`, `photoUrls`, `tags`, `status`){ + if (!missing(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!missing(`category`)) { + stopifnot(is.list(tags), length(tags) != 0) + lapply(`category`, function(x) stopifnot("Element" %in% class(x), !is.list(x))) + self$`category` <- `category` + } + if (!missing(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + if (!missing(`photoUrls`)) { + stopifnot(is.list(`photoUrls`), length(`photoUrls`) != 0) + lapply(`photoUrls`, function(x) stopifnot(is.character(x))) + self$`photoUrls` <- `photoUrls` + } + if (!missing(`tags`)) { + stopifnot(is.list(tags), length(tags) != 0) + lapply(`tags`, function(x) stopifnot("Element" %in% class(x), !is.list(x))) + self$`tags` <- `tags` + } + if (!missing(`status`)) { + stopifnot(is.character(`status`), length(`status`) == 1) + self$`status` <- `status` + } + }, + toJSON = function() { + sprintf( + '{ + "id": %d, + "category": %s, + "name": "%s", + "photoUrls": ["%s"], + "tags": [%s], + "status": "%s" + }', + self$`id`, + self$`category`$toJSON(), + self$`name`, + lapply(self$`photoUrls`, function(x) paste(paste0('"', x, '"'), sep=",")), + lapply(self$`tags`, function(x) paste(x$toJSON(), sep=",")), + self$`status` + ) + }, + fromJSON = function(PetJson) { + PetObject <- jsonlite::fromJSON(PetJson) + self$`id` <- PetObject`$id` + self$`category` <- Category$new()$fromJSON(jsonlite::toJSON(PetObject${{baseName})) + self$`name` <- PetObject`$name` + self$`photoUrls` <- PetObject`$photoUrls` + self$`tags` <- lapply(PetObject$`tags`, function(x) Tag$new()$fromJSON(jsonlite::toJSON(x)) + self$`status` <- PetObject`$status` + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) diff --git a/samples/client/petstore/r_test/R/PetApi.r b/samples/client/petstore/r_test/R/PetApi.r new file mode 100644 index 00000000000..8fa18a7efc6 --- /dev/null +++ b/samples/client/petstore/r_test/R/PetApi.r @@ -0,0 +1,152 @@ +# 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 + +PetApi <- R6::R6Class( + 'PetApi', + public = list( + userAgent = "Swagger-Codegen/1.0.0/r", + basePath = "http://petstore.swagger.io/v2", + initialize = function(basePath){ + if (!missing(basePath)) { + stopifnot(is.character(basePath), length(basePath) == 1) + self$basePath <- basePath + } + }, + + add_pet = function(body){ + resp <- httr::POST(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "accept" = "application/json", "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + delete_pet = function(pet_id, api_key){ + resp <- httr::DELETE(paste0(self$basePath, pet_id), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml", "api_key" = api_key) + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + find_pets_by_status = function(status){ + resp <- httr::GET(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,query = list( + "status" = status + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Pet$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + find_pets_by_tags = function(tags){ + resp <- httr::GET(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,query = list( + "tags" = tags + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Pet$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + get_pet_by_id = function(pet_id){ + resp <- httr::GET(paste0(self$basePath, pet_id), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Pet$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + update_pet = function(body){ + resp <- httr::PUT(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "accept" = "application/json", "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + update_pet_with_form = function(pet_id, name, status){ + resp <- httr::POST(paste0(self$basePath, pet_id), + httr::add_headers("User-Agent" = self$userAgent, "accept" = "application/x-www-form-urlencoded", "content-type" = "application/xml") + ,body = list( + "name" = name, + "status" = status + ) + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + upload_file = function(pet_id, additional_metadata, file){ + resp <- httr::POST(paste0(self$basePath, pet_id), + httr::add_headers("User-Agent" = self$userAgent, "accept" = "multipart/form-data", "content-type" = "application/json") + ,body = list( + "additionalMetadata" = additional_metadata, + "file" = httr::upload_file(file) + ) + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- ApiResponse$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + } + ) +) diff --git a/samples/client/petstore/r_test/R/StoreApi.r b/samples/client/petstore/r_test/R/StoreApi.r new file mode 100644 index 00000000000..944efdf6602 --- /dev/null +++ b/samples/client/petstore/r_test/R/StoreApi.r @@ -0,0 +1,82 @@ +# 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 + +StoreApi <- R6::R6Class( + 'StoreApi', + public = list( + userAgent = "Swagger-Codegen/1.0.0/r", + basePath = "http://petstore.swagger.io/v2", + initialize = function(basePath){ + if (!missing(basePath)) { + stopifnot(is.character(basePath), length(basePath) == 1) + self$basePath <- basePath + } + }, + + delete_order = function(order_id){ + resp <- httr::DELETE(paste0(self$basePath, order_id), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + get_inventory = function(){ + resp <- httr::GET(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/json") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Integer$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + get_order_by_id = function(order_id){ + resp <- httr::GET(paste0(self$basePath, order_id), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Order$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + place_order = function(body){ + resp <- httr::POST(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Order$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + } + ) +) diff --git a/samples/client/petstore/r_test/R/Tag.r b/samples/client/petstore/r_test/R/Tag.r new file mode 100644 index 00000000000..b874ac65b44 --- /dev/null +++ b/samples/client/petstore/r_test/R/Tag.r @@ -0,0 +1,85 @@ +# 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 +#' @export +Tag <- R6::R6Class( + 'Tag', + public = list( + `id` = NULL, + `name` = NULL, + initialize = function(`id`, `name`){ + if (!missing(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!missing(`name`)) { + stopifnot(is.character(`name`), length(`name`) == 1) + self$`name` <- `name` + } + }, + toJSON = function() { + sprintf( + '{ + "id": %d, + "name": "%s" + }', + self$`id`, + self$`name` + ) + }, + fromJSON = function(TagJson) { + TagObject <- jsonlite::fromJSON(TagJson) + self$`id` <- TagObject`$id` + self$`name` <- TagObject`$name` + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) diff --git a/samples/client/petstore/r_test/R/User.r b/samples/client/petstore/r_test/R/User.r new file mode 100644 index 00000000000..07f46ed860e --- /dev/null +++ b/samples/client/petstore/r_test/R/User.r @@ -0,0 +1,133 @@ +# 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 +#' @export +User <- R6::R6Class( + 'User', + public = list( + `id` = NULL, + `username` = NULL, + `firstName` = NULL, + `lastName` = NULL, + `email` = NULL, + `password` = NULL, + `phone` = NULL, + `userStatus` = NULL, + initialize = function(`id`, `username`, `firstName`, `lastName`, `email`, `password`, `phone`, `userStatus`){ + if (!missing(`id`)) { + stopifnot(is.numeric(`id`), length(`id`) == 1) + self$`id` <- `id` + } + if (!missing(`username`)) { + stopifnot(is.character(`username`), length(`username`) == 1) + self$`username` <- `username` + } + if (!missing(`firstName`)) { + stopifnot(is.character(`firstName`), length(`firstName`) == 1) + self$`firstName` <- `firstName` + } + if (!missing(`lastName`)) { + stopifnot(is.character(`lastName`), length(`lastName`) == 1) + self$`lastName` <- `lastName` + } + if (!missing(`email`)) { + stopifnot(is.character(`email`), length(`email`) == 1) + self$`email` <- `email` + } + if (!missing(`password`)) { + stopifnot(is.character(`password`), length(`password`) == 1) + self$`password` <- `password` + } + if (!missing(`phone`)) { + stopifnot(is.character(`phone`), length(`phone`) == 1) + self$`phone` <- `phone` + } + if (!missing(`userStatus`)) { + stopifnot(is.numeric(`userStatus`), length(`userStatus`) == 1) + self$`userStatus` <- `userStatus` + } + }, + toJSON = function() { + sprintf( + '{ + "id": %d, + "username": "%s", + "firstName": "%s", + "lastName": "%s", + "email": "%s", + "password": "%s", + "phone": "%s", + "userStatus": "%s" + }', + self$`id`, + self$`username`, + self$`firstName`, + self$`lastName`, + self$`email`, + self$`password`, + self$`phone`, + self$`userStatus` + ) + }, + fromJSON = function(UserJson) { + UserObject <- jsonlite::fromJSON(UserJson) + self$`id` <- UserObject`$id` + self$`username` <- UserObject`$username` + self$`firstName` <- UserObject`$firstName` + self$`lastName` <- UserObject`$lastName` + self$`email` <- UserObject`$email` + self$`password` <- UserObject`$password` + self$`phone` <- UserObject`$phone` + self$`userStatus` <- UserObject`$userStatus` + } + ) +) + +#' Element Class +#' +#' Element Class +#' @export +Element <- R6::R6Class( + 'Element', + public = list( + id = NULL, + name = NULL, + initialize = function(id,name){ + if (!missing(id)) { + stopifnot(is.numeric(id), length(id) == 1) + self$id <- id + } + if (!missing(name)) { + stopifnot(is.character(name), length(name) == 1) + self$name <- name + } + }, + toJSON = function() { + sprintf('{"id":%d,"name":"%s"}', self$id, self$name) + } + ) +) + +#' Response Class +#' +#' Response Class +#' @export +Response <- R6::R6Class( + 'Response', + public = list( + content = NULL, + response = NULL, + initialize = function(content, response){ + self$content <- content + self$response <- response + } + ) +) diff --git a/samples/client/petstore/r_test/R/UserApi.r b/samples/client/petstore/r_test/R/UserApi.r new file mode 100644 index 00000000000..a9a8f15be6f --- /dev/null +++ b/samples/client/petstore/r_test/R/UserApi.r @@ -0,0 +1,143 @@ +# 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 + +UserApi <- R6::R6Class( + 'UserApi', + public = list( + userAgent = "Swagger-Codegen/1.0.0/r", + basePath = "http://petstore.swagger.io/v2", + initialize = function(basePath){ + if (!missing(basePath)) { + stopifnot(is.character(basePath), length(basePath) == 1) + self$basePath <- basePath + } + }, + + create_user = function(body){ + resp <- httr::POST(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + create_users_with_array_input = function(body){ + resp <- httr::POST(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + create_users_with_list_input = function(body){ + resp <- httr::POST(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + delete_user = function(username){ + resp <- httr::DELETE(paste0(self$basePath, username), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + get_user_by_name = function(username){ + resp <- httr::GET(paste0(self$basePath, username), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- User$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + login_user = function(username, password){ + resp <- httr::GET(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,query = list( + "username" = username, + "password" = password + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + result <- Character$new()$fromJSON(httr::content(resp, "text", encoding = "UTF-8"), simplifyVector = FALSE) + Response$new(result, resp) + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + logout_user = function(){ + resp <- httr::GET(paste0(self$basePath), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + }, + update_user = function(username, body){ + resp <- httr::PUT(paste0(self$basePath, username), + httr::add_headers("User-Agent" = self$userAgent, "content-type" = "application/xml") + ,body = body$toJSON() + ) + + if (httr::status_code(resp) >= 200 && httr::status_code(resp) <= 299) { + # void response, no need to return anything + } else if (httr::status_code(resp) >= 400 && httr::status_code(resp) <= 499){ + Response$new("API client error", resp) + } else if (httr::status_code(resp) >= 500 && httr::status_code(resp) <= 599){ + Response$new("API server error", resp) + } + + } + ) +) diff --git a/samples/client/petstore/r_test/README.md b/samples/client/petstore/r_test/README.md new file mode 100644 index 00000000000..88b32f0758f --- /dev/null +++ b/samples/client/petstore/r_test/README.md @@ -0,0 +1,19 @@ +# R API client for 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. + +## Overview +This API client was generated by the [swagger-codegen](https://github.com/swagger-api/swagger-codegen) project. By using the [OpenAPI/Swagger spec](https://github.com/swagger-api/swagger-spec) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: io.swagger.codegen.languages.RClientCodegen + +## Installation + +TODO + +## Author + +apiteam@swagger.io + diff --git a/samples/client/petstore/r_test/git_push.sh b/samples/client/petstore/r_test/git_push.sh new file mode 100644 index 00000000000..ed374619b13 --- /dev/null +++ b/samples/client/petstore/r_test/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' +