diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
index 2e48077fee5..7130b9d7acd 100644
--- a/.github/PULL_REQUEST_TEMPLATE.md
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -2,7 +2,7 @@
- [ ] Read the [contribution guidelines](https://github.com/openapitools/openapi-generator/blob/master/CONTRIBUTING.md).
- [ ] Ran the shell script under `./bin/` to update Petstore sample so that CIs can verify the change. (For instance, only need to run `./bin/{LANG}-petstore.sh` and `./bin/security/{LANG}-petstore.sh` if updating the {LANG} (e.g. php, ruby, python, etc) code generator or {LANG} client's mustache templates). Windows batch files can be found in `.\bin\windows\`.
-- [ ] Filed the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `3.1.x`, `4.0.x`. Default: `master`.
+- [ ] Filed the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master`, `3.2.x`, `4.0.x`. Default: `master`.
- [ ] Copied the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) to review the pull request if your PR is targeting a particular programming language.
### Description of the PR
diff --git a/README.md b/README.md
index 6ad8180bc08..3b232f224c7 100644
--- a/README.md
+++ b/README.md
@@ -167,6 +167,49 @@ export JAVA_HOME=`/usr/libexec/java_home -v 1.8`
export PATH=${JAVA_HOME}/bin:$PATH
```
+### Launcher Script
+
+One downside to manual jar downloads is that you don't keep up-to-date with the latest released version. We have a Bash launcher script at [bin/utils/openapi-generator.cli.sh](./bin/utils/openapi-generator.cli.sh) which resolves this issue.
+
+To install the launcher script, copy the contents of the script to a location on your path and make the script executable.
+
+An example of setting this up (NOTE: Always evaluate scripts curled from external systems before executing them).
+
+```
+mkdir -p ~/bin/openapitools
+curl https://raw.githubusercontent.com/OpenAPITools/openapi-generator/master/bin/utils/openapi-generator.cli.sh > ~/bin/openapitools/openapi-generator-cli
+chmod u+x ~/bin/openapitools/openapi-generator-cli
+export PATH=$PATH:~/bin/openapitools/
+```
+
+Now, `openapi-generator-cli` is "installed". On invocation, it will query the GitHub repository for the most recently released version. If this matches the last downloaded jar,
+it will execute as normal. If a newer version is found, the script will download the latest release and execute it.
+
+If you need to invoke an older version of the generator, you can define the variable `OPENAPI_GENERATOR_VERSION` either ad hoc or globally. You can export this variable if you'd like to persist a specific release version.
+
+Examples:
+
+```
+# Execute latest released openapi-generator-cli
+openapi-generator-cli version
+
+# Execute version 3.1.0 for the current invocation, regardless of the latest released version
+OPENAPI_GENERATOR_VERSION=3.1.0 openapi-generator-cli version
+
+# Execute version 3.1.0-SNAPSHOT for the current invocation
+OPENAPI_GENERATOR_VERSION=3.1.0-SNAPSHOT openapi-generator-cli version
+
+# Execute version 3.0.2 for every invocation in the current shell session
+export OPENAPI_GENERATOR_VERSION=3.0.2
+openapi-generator-cli version # is 3.0.2
+openapi-generator-cli version # is also 3.0.2
+
+# To "install" a specific version, set the variable in .bashrc/.bash_profile
+echo "export OPENAPI_GENERATOR_VERSION=3.0.2" >> ~/.bashrc
+source ~/.bashrc
+openapi-generator-cli version # is always 3.0.2, unless any of the above overrides are done ad hoc
+```
+
### [1.4 - Build Projects](#table-of-contents)
To build from source, you need the following installed and available in your `$PATH:`
@@ -419,11 +462,11 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in
- [Bithost GmbH](https://www.bithost.ch)
- [GMO Pepabo](https://pepabo.com/en/)
- [Raiffeisen Schweiz Genossenschaft](https://www.raiffeisen.ch)
+- [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development)
- [REST United](https://restunited.com)
- [Telstra](https://dev.telstra.com)
- [unblu inc.](https://www.unblu.com/)
-
## [5 - Presentations/Videos/Tutorials/Books](#table-of-contents)
- 2018/05/12 - [OpenAPI Generator - community drivenで成長するコードジェネレータ](https://ackintosh.github.io/blog/2018/05/12/openapi-generator/) by [中野暁人](https://github.com/ackintosh)
diff --git a/bin/utils/openapi-generator-cli.sh b/bin/utils/openapi-generator-cli.sh
new file mode 100644
index 00000000000..0f1016f9aed
--- /dev/null
+++ b/bin/utils/openapi-generator-cli.sh
@@ -0,0 +1,60 @@
+#!/usr/bin/env bash
+####
+# Save as openapi-generator-cli on your PATH. chmod u+x. Enjoy.
+#
+# This script will query github on every invocation to pull the latest released version
+# of openapi-generator.
+#
+# If you want repeatable executions, you can explicitly set a version via
+# OPENAPI_GENERATOR_VERSION
+# e.g. (in Bash)
+# export OPENAPI_GENERATOR_VERSION=3.1.0
+# openapi-generator-cli.sh
+# or
+# OPENAPI_GENERATOR_VERSION=3.1.0 openapi-generator-cli.sh
+#
+# This is also helpful, for example, if you want want to evaluate a SNAPSHOT version.
+#
+# NOTE: Jars are downloaded on demand from maven into the same directory as this script
+# for every 'latest' version pulled from github. Consider putting this under its own directory.
+####
+set -o pipefail
+
+for cmd in {mvn,python,curl}; do
+ if ! command -v ${cmd} > /dev/null; then
+ >&2 echo "This script requires '${cmd}' to be installed."
+ exit 1
+ fi
+done
+
+function latest.tag {
+ local uri="https://api.github.com/repos/${1}/tags"
+ curl -s ${uri} | python -c "import sys, json; print json.load(sys.stdin)[0]['name'][1:]"
+}
+
+ghrepo=openapitools/openapi-generator
+groupid=org.openapitools
+artifactid=openapi-generator-cli
+ver=${OPENAPI_GENERATOR_VERSION:-$(latest.tag $ghrepo)}
+
+jar=${artifactid}-${ver}.jar
+DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
+
+if [ ! -f ${DIR}/${jar} ]; then
+ repo="central::default::https://repo1.maven.apache.org/maven2"
+ if [[ ${ver} =~ ^.*-SNAPSHOT$ ]]; then
+ repo="central::default::https://oss.sonatype.org/content/repositories/snapshots"
+ fi
+ mvn org.apache.maven.plugins:maven-dependency-plugin:2.9:get \
+ -DremoteRepositories=${repo} \
+ -Dartifact=${groupid}:${artifactid}:${ver} \
+ -Dtransitive=false \
+ -Ddest=${DIR}/${jar}
+fi
+
+java -ea \
+ ${JAVA_OPTS} \
+ -Xms512M \
+ -Xmx1024M \
+ -server \
+ -jar ${DIR}/${jar} "$@"
\ No newline at end of file
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
index 5806a0fd6c6..b6b0df28124 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java
@@ -768,6 +768,8 @@ public class DefaultCodegen implements CodegenConfig {
public String toVarName(String name) {
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
+ } else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains( "" + ((char) character)))) {
+ return escapeSpecialCharacters(name, null, null);
} else {
return name;
}
@@ -784,6 +786,8 @@ public class DefaultCodegen implements CodegenConfig {
name = removeNonNameElementToCamelCase(name); // FIXME: a parameter should not be assigned. Also declare the methods parameters as 'final'.
if (reservedWords.contains(name)) {
return escapeReservedWord(name);
+ } else if (((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains( "" + ((char) character)))) {
+ return escapeSpecialCharacters(name, null, null);
}
return name;
}
@@ -822,6 +826,32 @@ public class DefaultCodegen implements CodegenConfig {
throw new RuntimeException("reserved word " + name + " not allowed");
}
+ /**
+ * Return the name with escaped characters.
+ *
+ * @param name the name to be escaped
+ * @param charactersToAllow characters that are not escaped
+ * @param appdendixToReplacement String to append to replaced characters.
+ * @return the escaped word
+ *
+ * throws Runtime exception as word is not escaped properly.
+ */
+ public String escapeSpecialCharacters(String name, List charactersToAllow, String appdendixToReplacement) {
+ String result = (String) ((CharSequence) name).chars().mapToObj(c -> {
+ String character = "" + (char) c;
+ if (charactersToAllow != null && charactersToAllow.contains(character)) {
+ return character;
+ } else if (specialCharReplacements.containsKey(character)) {
+ return specialCharReplacements.get(character) + (appdendixToReplacement != null ? appdendixToReplacement: "");
+ } else {
+ return character;
+ }
+ }).reduce( (c1, c2) -> "" + c1 + c2).orElse(null);
+
+ if (result != null) return result;
+ throw new RuntimeException("Word '" + name + "' could not be escaped.");
+ }
+
/**
* Return the fully-qualified "Model" name for import
*
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
index 056f56307bf..503bf241359 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java
@@ -896,8 +896,8 @@ public class DefaultGenerator extends AbstractGenerator implements Generator {
if (path.getParameters() != null) {
for (Parameter parameter : path.getParameters()) {
//skip propagation if a parameter with the same name is already defined at the operation level
- if (!operationParameters.contains(generateParameterId(parameter)) && operation.getParameters() != null) {
- operation.getParameters().add(parameter);
+ if (!operationParameters.contains(generateParameterId(parameter))) {
+ operation.addParametersItem(parameter);
}
}
}
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java
index 85feab0ca1c..3f7d014a3ca 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java
@@ -574,6 +574,14 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code
name = name.substring(0, 2).toLowerCase() + name.substring(2);
}
+ // If name contains special chars -> replace them.
+ if ((((CharSequence) name).chars().anyMatch(character -> specialCharReplacements.keySet().contains( "" + ((char) character))))) {
+ List allowedCharacters = new ArrayList<>();
+ allowedCharacters.add("_");
+ allowedCharacters.add("$");
+ name = escapeSpecialCharacters(name, allowedCharacters, "_");
+ }
+
// camelize (lower first character) the variable name
// pet_id => petId
name = camelize(name, true);
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java
index 0f6872b162e..0d2a6c047f9 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java
@@ -49,6 +49,7 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
public static final String DECLSPEC = "declspec";
public static final String DEFAULT_INCLUDE = "defaultInclude";
+ public static final String GENERATE_GMOCKS_FOR_APIS = "generateGMocksForApis";
protected String packageVersion = "1.0.0";
protected String declspec = "";
@@ -114,6 +115,9 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
addOption(DEFAULT_INCLUDE,
"The default include statement that should be placed in all headers for including things like the declspec (convention: #include \"Commons.h\" ",
this.defaultInclude);
+ addOption(GENERATE_GMOCKS_FOR_APIS,
+ "Generate Google Mock classes for APIs.",
+ null);
supportingFiles.add(new SupportingFile("modelbase-header.mustache", "", "ModelBase.h"));
supportingFiles.add(new SupportingFile("modelbase-source.mustache", "", "ModelBase.cpp"));
@@ -177,6 +181,11 @@ public class CppRestSdkClientCodegen extends AbstractCppCodegen {
defaultInclude = additionalProperties.get(DEFAULT_INCLUDE).toString();
}
+ if (convertPropertyToBoolean(GENERATE_GMOCKS_FOR_APIS)) {
+ apiTemplateFiles.put("api-gmock.mustache", "GMock.h");
+ additionalProperties.put("gmockApis", "true");
+ }
+
additionalProperties.put("modelNamespaceDeclarations", modelPackage.split("\\."));
additionalProperties.put("modelNamespace", modelPackage.replaceAll("\\.", "::"));
additionalProperties.put("modelHeaderGuardPrefix", modelPackage.replaceAll("\\.", "_").toUpperCase());
diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java
index f7e46ea78d2..76411f0406c 100644
--- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java
+++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java
@@ -165,8 +165,9 @@ public class RustClientCodegen extends DefaultCodegen implements CodegenConfig {
supportingFiles.add(new SupportingFile("configuration.mustache", apiFolder, "configuration.rs"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
- supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs"));
supportingFiles.add(new SupportingFile("api_mod.mustache", apiFolder, "mod.rs"));
+ supportingFiles.add(new SupportingFile("client.mustache", apiFolder, "client.rs"));
+ supportingFiles.add(new SupportingFile("request.rs", apiFolder, "request.rs"));
supportingFiles.add(new SupportingFile("model_mod.mustache", modelFolder, "mod.rs"));
supportingFiles.add(new SupportingFile("lib.rs", "src", "lib.rs"));
supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml"));
diff --git a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-gmock.mustache b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-gmock.mustache
new file mode 100644
index 00000000000..804099e4caf
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-gmock.mustache
@@ -0,0 +1,41 @@
+{{>licenseInfo}}
+{{#operations}}
+#ifndef {{apiHeaderGuardPrefix}}_{{classname}}GMock_H_
+#define {{apiHeaderGuardPrefix}}_{{classname}}GMock_H_
+
+#include
+
+#include "{{classname}}.h"
+
+{{#apiNamespaceDeclarations}}
+namespace {{this}} {
+{{/apiNamespaceDeclarations}}
+
+using namespace {{modelNamespace}};
+
+
+class {{declspec}} {{classname}}Mock : public I{{classname}}
+{
+public:
+ using Base = I{{classname}};
+
+ {{classname}}Mock() = default;
+ explicit {{classname}}Mock( std::shared_ptr apiClient ) { };
+ ~{{classname}}Mock() override = default;
+
+ {{#operation}}
+ MOCK_METHOD{{allParams.size}}( {{operationId}}, pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> (
+ {{#allParams}}
+ {{^required}}boost::optional<{{/required}}{{#isFile}}std::shared_ptr<{{/isFile}}{{{dataType}}}{{#isFile}}>{{/isFile}}{{^required}}>{{/required}} {{paramName}}{{#hasMore}},{{/hasMore}}
+ {{/allParams}}
+ ) );
+ {{/operation}}
+};
+
+{{#apiNamespaceDeclarations}}
+}
+{{/apiNamespaceDeclarations}}
+
+#endif /* {{apiHeaderGuardPrefix}}_{{classname}}GMock_H_ */
+
+{{/operations}}
diff --git a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-header.mustache
index 49200e4f2ab..ec97511314f 100644
--- a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-header.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/api-header.mustache
@@ -22,11 +22,38 @@ namespace {{this}} {
using namespace {{modelNamespace}};
-class {{declspec}} {{classname}}
+{{#gmockApis}}
+class {{declspec}} I{{classname}}
{
public:
- {{classname}}( std::shared_ptr apiClient );
- virtual ~{{classname}}();
+ I{{classname}}() = default;
+ virtual ~I{{classname}}() = default;
+
+ {{#operation}}
+ virtual pplx::task<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}}> {{operationId}}(
+ {{#allParams}}
+ {{^required}}boost::optional<{{/required}}{{#isFile}}std::shared_ptr<{{/isFile}}{{{dataType}}}{{#isFile}}>{{/isFile}}{{^required}}>{{/required}} {{paramName}}{{#hasMore}},{{/hasMore}}
+ {{/allParams}}
+ ) = 0;
+ {{/operation}}
+};{{/gmockApis}}
+
+class {{declspec}} {{classname}} {{#gmockApis}} : public I{{classname}} {{/gmockApis}}
+{
+public:
+ {{#gmockApis}}
+ using Base = I{{classname}};
+ {{/gmockApis}}
+
+ explicit {{classname}}( std::shared_ptr apiClient );
+
+ {{#gmockApis}}
+ ~{{classname}}() override;
+ {{/gmockApis}}
+ {{^gmockApis}}
+ virtual ~{{classname}}() = default;
+ {{/gmockApis}}
+
{{#operation}}
///
/// {{summary}}
@@ -41,7 +68,7 @@ public:
{{#allParams}}
{{^required}}boost::optional<{{/required}}{{#isFile}}std::shared_ptr<{{/isFile}}{{{dataType}}}{{#isFile}}>{{/isFile}}{{^required}}>{{/required}} {{paramName}}{{#hasMore}},{{/hasMore}}
{{/allParams}}
- );
+ ){{#gmockApis}} override{{/gmockApis}};
{{/operation}}
protected:
diff --git a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/apiclient-source.mustache b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/apiclient-source.mustache
index e5a1500c8d5..3650945081c 100644
--- a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/apiclient-source.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/apiclient-source.mustache
@@ -33,14 +33,14 @@ utility::string_t ApiClient::parameterToString(utility::string_t value)
}
utility::string_t ApiClient::parameterToString(int64_t value)
{
- std::stringstream valueAsStringStream;
- valueAsStringStream << value;
+ std::stringstream valueAsStringStream;
+ valueAsStringStream << value;
return utility::conversions::to_string_t(valueAsStringStream.str());
}
utility::string_t ApiClient::parameterToString(int32_t value)
{
- std::stringstream valueAsStringStream;
- valueAsStringStream << value;
+ std::stringstream valueAsStringStream;
+ valueAsStringStream << value;
return utility::conversions::to_string_t(valueAsStringStream.str());
}
@@ -132,7 +132,7 @@ pplx::task ApiClient::callApi(
if (!formParams.empty())
{
request.set_body(body_data);
- }
+ }
}
else
{
diff --git a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/model-source.mustache b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/model-source.mustache
index e7f3cbeffc7..842571dcbef 100644
--- a/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/model-source.mustache
+++ b/modules/openapi-generator/src/main/resources/cpp-rest-sdk-client/model-source.mustache
@@ -245,29 +245,35 @@ void {{classname}}::fromJson(web::json::value& val)
{{#isString}}
{{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));
{{/isString}}
- {{#isByteArray}}{{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));{{/isByteArray}}
+ {{#isByteArray}}
+ {{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));
+ {{/isByteArray}}
{{^isString}}
{{#isDateTime}}
{{setter}}(ModelBase::dateFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));
{{/isDateTime}}
- {{^isDateTime}}{{^isByteArray}}
+ {{^isDateTime}}
+ {{^isByteArray}}
if(!val[utility::conversions::to_string_t("{{baseName}}")].is_null())
{
{{{dataType}}} newItem({{{defaultValue}}});
newItem->fromJson(val[utility::conversions::to_string_t("{{baseName}}")]);
{{setter}}( newItem );
}
- {{/isByteArray}}{{/isDateTime}}
+ {{/isByteArray}}
+ {{/isDateTime}}
{{/isString}}
}
{{/required}}
{{#required}}
{{#isString}}
{{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));
- {{/isString}}{{#isByteArray}}
+ {{/isString}}
+ {{#isByteArray}}
{{setter}}(ModelBase::stringFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));
{{/isByteArray}}
- {{^isString}}{{^isByteArray}}
+ {{^isString}}
+ {{^isByteArray}}
{{#isDateTime}}
{{setter}}
(ModelBase::dateFromJson(val[utility::conversions::to_string_t("{{baseName}}")]));
@@ -282,7 +288,8 @@ void {{classname}}::fromJson(web::json::value& val)
{{setter}}( new{{name}} );
{{/vendorExtensions.x-codegen-file}}
{{/isDateTime}}
- {{/isByteArray}}{{/isString}}
+ {{/isByteArray}}
+ {{/isString}}
{{/required}}
{{/isPrimitiveType}}
{{/isMapContainer}}
@@ -356,33 +363,47 @@ void {{classname}}::toMultipart(std::shared_ptr multipart, co
{{^required}}
if(m_{{name}}IsSet)
{
- {{#isString}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));{{/isString}}{{#isByteArray}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
- {{/isByteArray}}{{^isString}}{{#isDateTime}}multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
- {{/isDateTime}}{{^isDateTime}}{{^isByteArray}}if (m_{{name}}.get())
+ {{#isString}}
+ multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
+ {{/isString}}
+ {{#isByteArray}}
+ multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
+ {{/isByteArray}}
+ {{^isString}}
+ {{#isDateTime}}
+ multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
+ {{/isDateTime}}
+ {{^isDateTime}}
+ {{^isByteArray}}if (m_{{name}}.get())
{
m_{{name}}->toMultipart(multipart, utility::conversions::to_string_t("{{baseName}}."));
}
- {{/isByteArray}}{{/isDateTime}}{{/isString}}
+ {{/isByteArray}}
+ {{/isDateTime}}
+ {{/isString}}
}
{{/required}}
{{#required}}
{{#isString}}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
- {{/isString}}{{#isByteArray}}
+ {{/isString}}
+ {{#isByteArray}}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
{{/isByteArray}}
{{^isString}}
{{#isDateTime}}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
{{/isDateTime}}
- {{^isDateTime}}{{^isByteArray}}
+ {{^isDateTime}}
+ {{^isByteArray}}
{{#vendorExtensions.x-codegen-file}}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("{{baseName}}"), m_{{name}}));
{{/vendorExtensions.x-codegen-file}}
{{^vendorExtensions.x-codegen-file}}
m_{{name}}->toMultipart(multipart, utility::conversions::to_string_t("{{baseName}}."));
{{/vendorExtensions.x-codegen-file}}
- {{/isByteArray}}{{/isDateTime}}
+ {{/isByteArray}}
+ {{/isDateTime}}
{{/isString}}
{{/required}}
{{/isPrimitiveType}}
@@ -513,8 +534,11 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart,
{{#isString}}
{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));
{{/isString}}
- {{#isByteArray}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));{{/isByteArray}}
- {{^isString}}{{^isByteArray}}
+ {{#isByteArray}}
+ {{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));
+ {{/isByteArray}}
+ {{^isString}}
+ {{^isByteArray}}
{{#isDateTime}}
{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));
{{/isDateTime}}
@@ -526,14 +550,19 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart,
{{setter}}( newItem );
}
{{/isDateTime}}
- {{/isByteArray}}{{/isString}}
+ {{/isByteArray}}
+ {{/isString}}
}
{{/required}}
{{#required}}
{{#isString}}
{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));
- {{/isString}}{{#isByteArray}}{{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));{{/isByteArray}}
- {{^isString}}{{^isByteArray}}
+ {{/isString}}
+ {{#isByteArray}}
+ {{setter}}(ModelBase::stringFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));
+ {{/isByteArray}}
+ {{^isString}}
+ {{^isByteArray}}
{{#isDateTime}}
{{setter}}(ModelBase::dateFromHttpContent(multipart->getContent(utility::conversions::to_string_t("{{baseName}}"))));
{{/isDateTime}}
@@ -547,7 +576,8 @@ void {{classname}}::fromMultiPart(std::shared_ptr multipart,
{{setter}}( new{{name}} );
{{/vendorExtensions.x-codegen-file}}
{{/isDateTime}}
- {{/isByteArray}}{{/isString}}
+ {{/isByteArray}}
+ {{/isString}}
{{/required}}
{{/isPrimitiveType}}
{{/isMapContainer}}
diff --git a/modules/openapi-generator/src/main/resources/dart/class.mustache b/modules/openapi-generator/src/main/resources/dart/class.mustache
index 4cd00eeb792..5090bc210d1 100644
--- a/modules/openapi-generator/src/main/resources/dart/class.mustache
+++ b/modules/openapi-generator/src/main/resources/dart/class.mustache
@@ -17,30 +17,35 @@ class {{classname}} {
if (json == null) return;
{{#vars}}
{{#isDateTime}}
- {{name}} = json['{{name}}'] == null ? null : DateTime.parse(json['{{name}}']);
+ {{name}} = json['{{baseName}}'] == null ? null : DateTime.parse(json['{{baseName}}']);
{{/isDateTime}}
+ {{#isDate}}
+ {{name}} = json['{{baseName}}'] == null ? null : DateTime.parse(json['{{baseName}}']);
+ {{/isDate}}
{{^isDateTime}}
+ {{^isDate}}
{{#complexType}}
{{#isListContainer}}
- {{name}} = {{complexType}}.listFromJson(json['{{name}}']);
+ {{name}} = {{complexType}}.listFromJson(json['{{baseName}}']);
{{/isListContainer}}
{{^isListContainer}}
{{#isMapContainer}}
- {{name}} = {{complexType}}.mapFromJson(json['{{name}}']);
+ {{name}} = {{complexType}}.mapFromJson(json['{{baseName}}']);
{{/isMapContainer}}
{{^isMapContainer}}
- {{name}} = new {{complexType}}.fromJson(json['{{name}}']);
+ {{name}} = new {{complexType}}.fromJson(json['{{baseName}}']);
{{/isMapContainer}}
{{/isListContainer}}
{{/complexType}}
{{^complexType}}
{{#isListContainer}}
- {{name}} = (json['{{name}}'] as List).map((item) => item as {{items.datatype}}).toList();
+ {{name}} = (json['{{baseName}}'] as List).map((item) => item as {{items.datatype}}).toList();
{{/isListContainer}}
{{^isListContainer}}
- {{name}} = json['{{name}}'];
+ {{name}} = json['{{baseName}}'];
{{/isListContainer}}
{{/complexType}}
+ {{/isDate}}
{{/isDateTime}}
{{/vars}}
}
@@ -49,10 +54,15 @@ class {{classname}} {
return {
{{#vars}}
{{#isDateTime}}
- '{{name}}': {{name}} == null ? '' : {{name}}.toUtc().toIso8601String(){{^-last}},{{/-last}}
+ '{{baseName}}': {{name}} == null ? '' : {{name}}.toUtc().toIso8601String(){{^-last}},{{/-last}}
{{/isDateTime}}
+ {{#isDate}}
+ '{{baseName}}': {{name}} == null ? '' : {{name}}.toUtc().toIso8601String(){{^-last}},{{/-last}}
+ {{/isDate}}
{{^isDateTime}}
- '{{name}}': {{name}}{{^-last}},{{/-last}}
+ {{^isDate}}
+ '{{baseName}}': {{name}}{{^-last}},{{/-last}}
+ {{/isDate}}
{{/isDateTime}}
{{/vars}}
};
diff --git a/modules/openapi-generator/src/main/resources/rust/api.mustache b/modules/openapi-generator/src/main/resources/rust/api.mustache
index 55604ca7933..3e59a5839db 100644
--- a/modules/openapi-generator/src/main/resources/rust/api.mustache
+++ b/modules/openapi-generator/src/main/resources/rust/api.mustache
@@ -1,17 +1,13 @@
{{>partial_header}}
use std::rc::Rc;
use std::borrow::Borrow;
-use std::borrow::Cow;
-use std::collections::HashMap;
use hyper;
use serde_json;
-use futures;
-use futures::{Future, Stream};
-
-use hyper::header::UserAgent;
+use futures::Future;
use super::{Error, configuration};
+use super::request as __internal_request;
pub struct {{{classname}}}Client {
configuration: Rc>,
@@ -38,129 +34,54 @@ impl{{classname}} for {{classname}}Client {
{{#operations}}
{{#operation}}
fn {{{operationId}}}(&self, {{#allParams}}{{paramName}}: {{#isString}}&str{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{#hasMore}}, {{/hasMore}}{{/allParams}}) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
-{{#hasAuthMethods}}
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
-{{#authMethods}}
-{{#isApiKey}}
- if let Some(ref apikey) = configuration.api_key {
- let key = apikey.key.clone();
- let val = match apikey.prefix {
- Some(ref prefix) => format!("{} {}", prefix, key),
- None => key,
- };
- {{#isKeyInHeader}}
- auth_headers.insert("{{keyParamName}}".to_owned(), val);
- {{/isKeyInHeader}}
- {{#isKeyInQuery}}
- auth_query.insert("{{keyParamName}}".to_owned(), val);
- {{/isKeyInQuery}}
- };
-{{/isApiKey}}
-{{#isBasic}}
- if let Some(ref auth_conf) = configuration.basic_auth {
- let auth = hyper::header::Authorization(
- hyper::header::Basic {
- username: auth_conf.0.to_owned(),
- password: auth_conf.1.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
-{{/isBasic}}
-{{#isOAuth}}
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
-{{/isOAuth}}
-{{/authMethods}}
-{{/hasAuthMethods}}
- let method = hyper::Method::{{httpMethod}};
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
-{{#queryParams}}
- query.append_pair("{{baseName}}", &{{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string());
-{{/queryParams}}
-{{#hasAuthMethods}}
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
-{{/hasAuthMethods}}
- query.finish()
- };
- let uri_str = format!("{}{{{path}}}?{}", configuration.base_path, query_string{{#pathParams}}, {{baseName}}={{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}}{{/pathParams}});
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
- {{#hasHeaderParams}}
- {
- let mut headers = req.headers_mut();
- {{#headerParams}}
- headers.set_raw("{{baseName}}", {{paramName}}{{#isListContainer}}.join(",").as_ref(){{/isListContainer}});
- {{/headerParams}}
- }
- {{/hasHeaderParams}}
-
+ __internal_request::Request::new(hyper::Method::{{httpMethod}}, "{{{path}}}".to_string())
{{#hasAuthMethods}}
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
+ {{#authMethods}}
+ {{#isApiKey}}
+ .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
+ in_header: {{#isKeyInHeader}}true{{/isKeyInHeader}}{{^isKeyInHeader}}false{{/isKeyInHeader}},
+ in_query: {{#isKeyInQuery}}true{{/isKeyInQuery}}{{^isKeyInQuery}}false{{/isKeyInQuery}},
+ param_name: "{{{keyParamName}}}".to_owned(),
+ }))
+ {{/isApiKey}}
+ {{#isBasic}}
+ .with_auth(__internal_request::Auth::Basic)
+ {{/isBasic}}
+ {{#isOAuth}}
+ .with_auth(__internal_request::Auth::Oauth)
+ {{/isOAuth}}
+ {{/authMethods}}
{{/hasAuthMethods}}
-
+ {{#queryParams}}
+ .with_query_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
+ {{/queryParams}}
+ {{#pathParams}}
+ .with_path_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
+ {{/pathParams}}
+ {{#hasHeaderParams}}
+ {{#headerParams}}
+ .with_header_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
+ {{/headerParams}}
+ {{/hasHeaderParams}}
+ {{#hasFormParams}}
+ {{#formParams}}
+ {{#isFile}}
+ .with_form_param("{{baseName}}".to_string(), unimplemented!())
+ {{/isFile}}
+ {{^isFile}}
+ .with_form_param("{{baseName}}".to_string(), {{paramName}}{{#isListContainer}}.join(","){{/isListContainer}}.to_string())
+ {{/isFile}}
+ {{/formParams}}
+ {{/hasFormParams}}
{{#hasBodyParam}}
{{#bodyParams}}
- let serialized = serde_json::to_string(&{{paramName}}).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
+ .with_body_param({{paramName}})
{{/bodyParams}}
{{/hasBodyParam}}
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- {{^returnType}}
- .and_then(|_| futures::future::ok(()))
- {{/returnType}}
- {{#returnType}}
- .and_then(|body| {
- let parsed: Result<{{{returnType}}}, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- {{/returnType}}
- )
+ {{^returnType}}
+ .returns_nothing()
+ {{/returnType}}
+ .execute(self.configuration.borrow())
}
{{/operation}}
diff --git a/modules/openapi-generator/src/main/resources/rust/api_mod.mustache b/modules/openapi-generator/src/main/resources/rust/api_mod.mustache
index 5c8f6b86a4d..1f587b0d52f 100644
--- a/modules/openapi-generator/src/main/resources/rust/api_mod.mustache
+++ b/modules/openapi-generator/src/main/resources/rust/api_mod.mustache
@@ -4,6 +4,7 @@ use serde_json;
#[derive(Debug)]
pub enum Error {
+ UriError(hyper::error::UriError),
Hyper(hyper::Error),
Serde(serde_json::Error),
ApiError(ApiError),
@@ -50,6 +51,8 @@ impl From for Error {
use super::models::*;
+mod request;
+
{{#apiInfo}}
{{#apis}}
mod {{classFilename}};
diff --git a/modules/openapi-generator/src/main/resources/rust/request.rs b/modules/openapi-generator/src/main/resources/rust/request.rs
new file mode 100644
index 00000000000..383a409542b
--- /dev/null
+++ b/modules/openapi-generator/src/main/resources/rust/request.rs
@@ -0,0 +1,238 @@
+use std::borrow::Cow;
+use std::collections::HashMap;
+
+use super::{configuration, Error};
+use futures;
+use futures::{Future, Stream};
+use hyper;
+use hyper::header::UserAgent;
+use serde;
+use serde_json;
+
+pub(crate) struct ApiKey {
+ pub in_header: bool,
+ pub in_query: bool,
+ pub param_name: String,
+}
+
+impl ApiKey {
+ fn key(&self, prefix: &Option, key: &str) -> String {
+ match prefix {
+ None => key.to_owned(),
+ Some(ref prefix) => format!("{} {}", prefix, key),
+ }
+ }
+}
+
+pub(crate) enum Auth {
+ None,
+ ApiKey(ApiKey),
+ Basic,
+ Oauth,
+}
+
+pub(crate) struct Request {
+ auth: Auth,
+ method: hyper::Method,
+ path: String,
+ query_params: HashMap,
+ no_return_type: bool,
+ path_params: HashMap,
+ form_params: HashMap,
+ header_params: HashMap,
+ // TODO: multiple body params are possible technically, but not supported here.
+ serialized_body: Option,
+}
+
+impl Request {
+ pub fn new(method: hyper::Method, path: String) -> Self {
+ Request {
+ auth: Auth::None,
+ method: method,
+ path: path,
+ query_params: HashMap::new(),
+ path_params: HashMap::new(),
+ form_params: HashMap::new(),
+ header_params: HashMap::new(),
+ serialized_body: None,
+ no_return_type: false,
+ }
+ }
+
+ pub fn with_body_param(mut self, param: T) -> Self {
+ self.serialized_body = Some(serde_json::to_string(¶m).unwrap());
+ self
+ }
+
+ pub fn with_header_param(mut self, basename: String, param: String) -> Self {
+ self.header_params.insert(basename, param);
+ self
+ }
+
+ pub fn with_query_param(mut self, basename: String, param: String) -> Self {
+ self.query_params.insert(basename, param);
+ self
+ }
+
+ pub fn with_path_param(mut self, basename: String, param: String) -> Self {
+ self.path_params.insert(basename, param);
+ self
+ }
+
+ pub fn with_form_param(mut self, basename: String, param: String) -> Self {
+ self.form_params.insert(basename, param);
+ self
+ }
+
+ pub fn returns_nothing(mut self) -> Self {
+ self.no_return_type = true;
+ self
+ }
+
+ pub fn with_auth(mut self, auth: Auth) -> Self {
+ self.auth = auth;
+ self
+ }
+
+ pub fn execute<'a, C, U>(
+ self,
+ conf: &configuration::Configuration,
+ ) -> Box> + 'a>
+ where
+ C: hyper::client::Connect,
+ U: Sized + 'a,
+ for<'de> U: serde::Deserialize<'de>,
+ {
+ let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned());
+ // raw_headers is for headers we don't know the proper type of (e.g. custom api key
+ // headers); headers is for ones we do know the type of.
+ let mut raw_headers = HashMap::new();
+ let mut headers: hyper::header::Headers = hyper::header::Headers::new();
+
+ let mut path = self.path;
+ for (k, v) in self.path_params {
+ // replace {id} with the value of the id path param
+ path = path.replace(&format!("{{{}}}", k), &v);
+ }
+
+ for (k, v) in self.header_params {
+ raw_headers.insert(k, v);
+ }
+
+ for (key, val) in self.query_params {
+ query_string.append_pair(&key, &val);
+ }
+
+ match self.auth {
+ Auth::ApiKey(apikey) => {
+ if let Some(ref key) = conf.api_key {
+ let val = apikey.key(&key.prefix, &key.key);
+ if apikey.in_query {
+ query_string.append_pair(&apikey.param_name, &val);
+ }
+ if apikey.in_header {
+ raw_headers.insert(apikey.param_name, val);
+ }
+ }
+ }
+ Auth::Basic => {
+ if let Some(ref auth_conf) = conf.basic_auth {
+ let auth = hyper::header::Authorization(hyper::header::Basic {
+ username: auth_conf.0.to_owned(),
+ password: auth_conf.1.to_owned(),
+ });
+ headers.set(auth);
+ }
+ }
+ Auth::Oauth => {
+ if let Some(ref token) = conf.oauth_access_token {
+ let auth = hyper::header::Authorization(hyper::header::Bearer {
+ token: token.to_owned(),
+ });
+ headers.set(auth);
+ }
+ }
+ Auth::None => {}
+ }
+
+ let mut uri_str = format!("{}{}", conf.base_path, path);
+
+ let query_string_str = query_string.finish();
+ if query_string_str != "" {
+ uri_str += "?";
+ uri_str += &query_string_str;
+ }
+ let uri: hyper::Uri = match uri_str.parse() {
+ Err(e) => {
+ return Box::new(futures::future::err(Error::UriError(e)));
+ }
+ Ok(u) => u,
+ };
+
+ let mut req = hyper::Request::new(self.method, uri);
+ {
+ let req_headers = req.headers_mut();
+ if let Some(ref user_agent) = conf.user_agent {
+ req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone())));
+ }
+
+ req_headers.extend(headers.iter());
+
+ for (key, val) in raw_headers {
+ req_headers.set_raw(key, val);
+ }
+ }
+
+ if self.form_params.len() > 0 {
+ req.headers_mut().set(hyper::header::ContentType::form_url_encoded());
+ let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned());
+ for (k, v) in self.form_params {
+ enc.append_pair(&k, &v);
+ }
+ req.set_body(enc.finish());
+ }
+
+ if let Some(body) = self.serialized_body {
+ req.headers_mut().set(hyper::header::ContentType::json());
+ req.headers_mut()
+ .set(hyper::header::ContentLength(body.len() as u64));
+ req.set_body(body);
+ }
+
+ let no_ret_type = self.no_return_type;
+ let res = conf.client
+ .request(req)
+ .map_err(|e| Error::from(e))
+ .and_then(|resp| {
+ let status = resp.status();
+ resp.body()
+ .concat2()
+ .and_then(move |body| Ok((status, body)))
+ .map_err(|e| Error::from(e))
+ })
+ .and_then(|(status, body)| {
+ if status.is_success() {
+ Ok(body)
+ } else {
+ Err(Error::from((status, &*body)))
+ }
+ });
+ Box::new(
+ res
+ .and_then(move |body| {
+ let parsed: Result = if no_ret_type {
+ // This is a hack; if there's no_ret_type, U is (), but serde_json gives an
+ // error when deserializing "" into (), so deserialize 'null' into it
+ // instead.
+ // An alternate option would be to require U: Default, and then return
+ // U::default() here instead since () implements that, but then we'd
+ // need to impl default for all models.
+ serde_json::from_str("null")
+ } else {
+ serde_json::from_slice(&body)
+ };
+ parsed.map_err(|e| Error::from(e))
+ })
+ )
+ }
+}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java
new file mode 100644
index 00000000000..47dbcffd9df
--- /dev/null
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultGeneratorTest.java
@@ -0,0 +1,50 @@
+package org.openapitools.codegen;
+
+import io.swagger.v3.oas.models.OpenAPI;
+import io.swagger.v3.oas.models.Operation;
+import io.swagger.v3.oas.models.PathItem;
+import io.swagger.v3.oas.models.Paths;
+import io.swagger.v3.oas.models.media.IntegerSchema;
+import io.swagger.v3.oas.models.media.StringSchema;
+import io.swagger.v3.oas.models.parameters.QueryParameter;
+import io.swagger.v3.oas.models.responses.ApiResponse;
+import io.swagger.v3.oas.models.responses.ApiResponses;
+
+import org.testng.Assert;
+import org.testng.annotations.Test;
+
+import java.util.List;
+import java.util.Map;
+
+public class DefaultGeneratorTest {
+
+ @Test
+ public void testProcessPaths() throws Exception {
+ OpenAPI openAPI = TestUtils.createOpenAPI();
+ openAPI.setPaths(new Paths());
+ openAPI.getPaths().addPathItem("path1/", new PathItem().get(new Operation().operationId("op1").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
+ openAPI.getPaths().addPathItem("path2/", new PathItem().get(new Operation().operationId("op2").addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
+ openAPI.getPaths().addPathItem("path3/", new PathItem().addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).get(new Operation().operationId("op3").addParametersItem(new QueryParameter().name("p2").schema(new IntegerSchema())).responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
+ openAPI.getPaths().addPathItem("path4/", new PathItem().addParametersItem(new QueryParameter().name("p1").schema(new StringSchema())).get(new Operation().operationId("op4").responses(new ApiResponses().addApiResponse("201", new ApiResponse().description("OK")))));
+
+ ClientOptInput opts = new ClientOptInput();
+ opts.setOpenAPI(openAPI);
+ opts.setConfig(new DefaultCodegen());
+ opts.setOpts(new ClientOpts());
+
+ DefaultGenerator generator = new DefaultGenerator();
+ generator.opts(opts);
+ Map> result = generator.processPaths(openAPI.getPaths());
+ Assert.assertEquals(result.size(), 1);
+ List defaultList = result.get("Default");
+ Assert.assertEquals(defaultList.size(), 4);
+ Assert.assertEquals(defaultList.get(0).path, "path1/");
+ Assert.assertEquals(defaultList.get(0).allParams.size(), 0);
+ Assert.assertEquals(defaultList.get(1).path, "path2/");
+ Assert.assertEquals(defaultList.get(1).allParams.size(), 1);
+ Assert.assertEquals(defaultList.get(2).path, "path3/");
+ Assert.assertEquals(defaultList.get(2).allParams.size(), 2);
+ Assert.assertEquals(defaultList.get(3).path, "path4/");
+ Assert.assertEquals(defaultList.get(3).allParams.size(), 1);
+ }
+}
diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java
index b54a8bf2ebb..54dc3b0cd63 100644
--- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java
+++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaModelTest.java
@@ -242,6 +242,31 @@ public class JavaModelTest {
Assert.assertTrue(property.isContainer);
}
+ @Test(description = "convert a model with restriced characters")
+ public void restrictedCharactersPropertiesTest() {
+ final Schema schema = new Schema()
+ .description("a sample model")
+ .addProperties("@Some:restricted%characters#to!handle+", new BooleanSchema());
+ final DefaultCodegen codegen = new JavaClientCodegen();
+ final CodegenModel cm = codegen.fromModel("sample", schema, Collections.singletonMap("sample", schema));
+
+ Assert.assertEquals(cm.name, "sample");
+ Assert.assertEquals(cm.classname, "Sample");
+ Assert.assertEquals(cm.description, "a sample model");
+ Assert.assertEquals(cm.vars.size(), 1);
+
+ final CodegenProperty property = cm.vars.get(0);
+ Assert.assertEquals(property.baseName, "@Some:restricted%characters#to!handle+");
+ Assert.assertEquals(property.getter, "getAtSomeColonRestrictedPercentCharactersHashToExclamationHandlePlus");
+ Assert.assertEquals(property.setter, "setAtSomeColonRestrictedPercentCharactersHashToExclamationHandlePlus");
+ Assert.assertEquals(property.dataType, "Boolean");
+ Assert.assertEquals(property.name, "atSomeColonRestrictedPercentCharactersHashToExclamationHandlePlus");
+ Assert.assertEquals(property.defaultValue, "null");
+ Assert.assertEquals(property.baseType, "Boolean");
+ Assert.assertFalse(property.required);
+ Assert.assertTrue(property.isNotContainer);
+ }
+
@Test(description = "convert a model with complex properties")
public void complexPropertiesTest() {
final Schema schema = new Schema()
diff --git a/samples/client/petstore/cpp-restsdk/.openapi-generator/VERSION b/samples/client/petstore/cpp-restsdk/.openapi-generator/VERSION
index 096bf47efe3..0f58aa04141 100644
--- a/samples/client/petstore/cpp-restsdk/.openapi-generator/VERSION
+++ b/samples/client/petstore/cpp-restsdk/.openapi-generator/VERSION
@@ -1 +1 @@
-3.0.0-SNAPSHOT
\ No newline at end of file
+3.1.2-SNAPSHOT
\ No newline at end of file
diff --git a/samples/client/petstore/cpp-restsdk/ApiClient.cpp b/samples/client/petstore/cpp-restsdk/ApiClient.cpp
index 448f377926e..dab66e0e6e1 100644
--- a/samples/client/petstore/cpp-restsdk/ApiClient.cpp
+++ b/samples/client/petstore/cpp-restsdk/ApiClient.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -44,14 +44,14 @@ utility::string_t ApiClient::parameterToString(utility::string_t value)
}
utility::string_t ApiClient::parameterToString(int64_t value)
{
- std::stringstream valueAsStringStream;
- valueAsStringStream << value;
+ std::stringstream valueAsStringStream;
+ valueAsStringStream << value;
return utility::conversions::to_string_t(valueAsStringStream.str());
}
utility::string_t ApiClient::parameterToString(int32_t value)
{
- std::stringstream valueAsStringStream;
- valueAsStringStream << value;
+ std::stringstream valueAsStringStream;
+ valueAsStringStream << value;
return utility::conversions::to_string_t(valueAsStringStream.str());
}
@@ -143,7 +143,7 @@ pplx::task ApiClient::callApi(
if (!formParams.empty())
{
request.set_body(body_data);
- }
+ }
}
else
{
diff --git a/samples/client/petstore/cpp-restsdk/ApiClient.h b/samples/client/petstore/cpp-restsdk/ApiClient.h
index 355a119f395..58d8e78ac07 100644
--- a/samples/client/petstore/cpp-restsdk/ApiClient.h
+++ b/samples/client/petstore/cpp-restsdk/ApiClient.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/ApiConfiguration.cpp b/samples/client/petstore/cpp-restsdk/ApiConfiguration.cpp
index 2d5d39513ec..0f91d7c2cba 100644
--- a/samples/client/petstore/cpp-restsdk/ApiConfiguration.cpp
+++ b/samples/client/petstore/cpp-restsdk/ApiConfiguration.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/ApiConfiguration.h b/samples/client/petstore/cpp-restsdk/ApiConfiguration.h
index c39b29fc61f..54dc39c26cf 100644
--- a/samples/client/petstore/cpp-restsdk/ApiConfiguration.h
+++ b/samples/client/petstore/cpp-restsdk/ApiConfiguration.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/ApiException.cpp b/samples/client/petstore/cpp-restsdk/ApiException.cpp
index bb41df86f97..1cceca2e6de 100644
--- a/samples/client/petstore/cpp-restsdk/ApiException.cpp
+++ b/samples/client/petstore/cpp-restsdk/ApiException.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/ApiException.h b/samples/client/petstore/cpp-restsdk/ApiException.h
index 6073db8d1ec..ffd7877f3a5 100644
--- a/samples/client/petstore/cpp-restsdk/ApiException.h
+++ b/samples/client/petstore/cpp-restsdk/ApiException.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/HttpContent.cpp b/samples/client/petstore/cpp-restsdk/HttpContent.cpp
index 8922e724304..a5823e01eff 100644
--- a/samples/client/petstore/cpp-restsdk/HttpContent.cpp
+++ b/samples/client/petstore/cpp-restsdk/HttpContent.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/HttpContent.h b/samples/client/petstore/cpp-restsdk/HttpContent.h
index 71b055aaadc..d3950dbd783 100644
--- a/samples/client/petstore/cpp-restsdk/HttpContent.h
+++ b/samples/client/petstore/cpp-restsdk/HttpContent.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/IHttpBody.h b/samples/client/petstore/cpp-restsdk/IHttpBody.h
index 88ce14a536d..26a846e5f75 100644
--- a/samples/client/petstore/cpp-restsdk/IHttpBody.h
+++ b/samples/client/petstore/cpp-restsdk/IHttpBody.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/JsonBody.cpp b/samples/client/petstore/cpp-restsdk/JsonBody.cpp
index e3fbd7b340b..1958337d03d 100644
--- a/samples/client/petstore/cpp-restsdk/JsonBody.cpp
+++ b/samples/client/petstore/cpp-restsdk/JsonBody.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/JsonBody.h b/samples/client/petstore/cpp-restsdk/JsonBody.h
index 5ec9da11d70..3159dfa94d0 100644
--- a/samples/client/petstore/cpp-restsdk/JsonBody.h
+++ b/samples/client/petstore/cpp-restsdk/JsonBody.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/ModelBase.cpp b/samples/client/petstore/cpp-restsdk/ModelBase.cpp
index d13dc7ac980..a4dc77d750c 100644
--- a/samples/client/petstore/cpp-restsdk/ModelBase.cpp
+++ b/samples/client/petstore/cpp-restsdk/ModelBase.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/ModelBase.h b/samples/client/petstore/cpp-restsdk/ModelBase.h
index 6b9818617bc..4d804a46013 100644
--- a/samples/client/petstore/cpp-restsdk/ModelBase.h
+++ b/samples/client/petstore/cpp-restsdk/ModelBase.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/MultipartFormData.cpp b/samples/client/petstore/cpp-restsdk/MultipartFormData.cpp
index fb9b11dfee1..7879d7afe44 100644
--- a/samples/client/petstore/cpp-restsdk/MultipartFormData.cpp
+++ b/samples/client/petstore/cpp-restsdk/MultipartFormData.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/MultipartFormData.h b/samples/client/petstore/cpp-restsdk/MultipartFormData.h
index 166ada330ca..8f03432efa8 100644
--- a/samples/client/petstore/cpp-restsdk/MultipartFormData.h
+++ b/samples/client/petstore/cpp-restsdk/MultipartFormData.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -12,7 +12,7 @@
/*
* MultipartFormData.h
*
- * This class represents a container for building a application/x-multipart-formdata requests.
+ * This class represents a container for building application/x-multipart-formdata requests.
*/
#ifndef ORG_OPENAPITOOLS_CLIENT_MODEL_MultipartFormData_H_
diff --git a/samples/client/petstore/cpp-restsdk/Object.cpp b/samples/client/petstore/cpp-restsdk/Object.cpp
index 326ada285e9..a0d392f8995 100644
--- a/samples/client/petstore/cpp-restsdk/Object.cpp
+++ b/samples/client/petstore/cpp-restsdk/Object.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/Object.h b/samples/client/petstore/cpp-restsdk/Object.h
index ec9505e194b..a6ce69a13ad 100644
--- a/samples/client/petstore/cpp-restsdk/Object.h
+++ b/samples/client/petstore/cpp-restsdk/Object.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/api/PetApi.cpp b/samples/client/petstore/cpp-restsdk/api/PetApi.cpp
index 69b595fc629..1e3f68f8229 100644
--- a/samples/client/petstore/cpp-restsdk/api/PetApi.cpp
+++ b/samples/client/petstore/cpp-restsdk/api/PetApi.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/api/PetApi.h b/samples/client/petstore/cpp-restsdk/api/PetApi.h
index 01cc1f218bc..477738c30b2 100644
--- a/samples/client/petstore/cpp-restsdk/api/PetApi.h
+++ b/samples/client/petstore/cpp-restsdk/api/PetApi.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -35,11 +35,16 @@ namespace api {
using namespace org::openapitools::client::model;
-class PetApi
+
+
+class PetApi
{
public:
- PetApi( std::shared_ptr apiClient );
- virtual ~PetApi();
+
+ explicit PetApi( std::shared_ptr apiClient );
+
+ virtual ~PetApi() = default;
+
///
/// Add a new pet to the store
///
diff --git a/samples/client/petstore/cpp-restsdk/api/StoreApi.cpp b/samples/client/petstore/cpp-restsdk/api/StoreApi.cpp
index 18873055580..c73c34e395c 100644
--- a/samples/client/petstore/cpp-restsdk/api/StoreApi.cpp
+++ b/samples/client/petstore/cpp-restsdk/api/StoreApi.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/api/StoreApi.h b/samples/client/petstore/cpp-restsdk/api/StoreApi.h
index 303345a8d7c..0f3e53e3d3b 100644
--- a/samples/client/petstore/cpp-restsdk/api/StoreApi.h
+++ b/samples/client/petstore/cpp-restsdk/api/StoreApi.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -34,11 +34,16 @@ namespace api {
using namespace org::openapitools::client::model;
-class StoreApi
+
+
+class StoreApi
{
public:
- StoreApi( std::shared_ptr apiClient );
- virtual ~StoreApi();
+
+ explicit StoreApi( std::shared_ptr apiClient );
+
+ virtual ~StoreApi() = default;
+
///
/// Delete purchase order by ID
///
diff --git a/samples/client/petstore/cpp-restsdk/api/UserApi.cpp b/samples/client/petstore/cpp-restsdk/api/UserApi.cpp
index 9c319adf023..9f97981f928 100644
--- a/samples/client/petstore/cpp-restsdk/api/UserApi.cpp
+++ b/samples/client/petstore/cpp-restsdk/api/UserApi.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/api/UserApi.h b/samples/client/petstore/cpp-restsdk/api/UserApi.h
index 2b198b383a8..e02bc2df54b 100644
--- a/samples/client/petstore/cpp-restsdk/api/UserApi.h
+++ b/samples/client/petstore/cpp-restsdk/api/UserApi.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -34,11 +34,16 @@ namespace api {
using namespace org::openapitools::client::model;
-class UserApi
+
+
+class UserApi
{
public:
- UserApi( std::shared_ptr apiClient );
- virtual ~UserApi();
+
+ explicit UserApi( std::shared_ptr apiClient );
+
+ virtual ~UserApi() = default;
+
///
/// Create user
///
diff --git a/samples/client/petstore/cpp-restsdk/model/ApiResponse.cpp b/samples/client/petstore/cpp-restsdk/model/ApiResponse.cpp
index 1d8ebbac8b7..b8a7e58a3b7 100644
--- a/samples/client/petstore/cpp-restsdk/model/ApiResponse.cpp
+++ b/samples/client/petstore/cpp-restsdk/model/ApiResponse.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -88,12 +88,10 @@ void ApiResponse::toMultipart(std::shared_ptr multipart, cons
if(m_TypeIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("type"), m_Type));
-
}
if(m_MessageIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("message"), m_Message));
-
}
}
diff --git a/samples/client/petstore/cpp-restsdk/model/ApiResponse.h b/samples/client/petstore/cpp-restsdk/model/ApiResponse.h
index 0514fcd38c9..bad10415676 100644
--- a/samples/client/petstore/cpp-restsdk/model/ApiResponse.h
+++ b/samples/client/petstore/cpp-restsdk/model/ApiResponse.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/model/Category.cpp b/samples/client/petstore/cpp-restsdk/model/Category.cpp
index 60f92843df0..e765cdccd08 100644
--- a/samples/client/petstore/cpp-restsdk/model/Category.cpp
+++ b/samples/client/petstore/cpp-restsdk/model/Category.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -78,7 +78,6 @@ void Category::toMultipart(std::shared_ptr multipart, const u
if(m_NameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
-
}
}
diff --git a/samples/client/petstore/cpp-restsdk/model/Category.h b/samples/client/petstore/cpp-restsdk/model/Category.h
index f77cf6c508b..93c2e24a51f 100644
--- a/samples/client/petstore/cpp-restsdk/model/Category.h
+++ b/samples/client/petstore/cpp-restsdk/model/Category.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/model/Order.cpp b/samples/client/petstore/cpp-restsdk/model/Order.cpp
index f23fd13926c..fdad2a0ef4e 100644
--- a/samples/client/petstore/cpp-restsdk/model/Order.cpp
+++ b/samples/client/petstore/cpp-restsdk/model/Order.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -126,12 +126,10 @@ void Order::toMultipart(std::shared_ptr multipart, const util
if(m_ShipDateIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("shipDate"), m_ShipDate));
-
}
if(m_StatusIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("status"), m_Status));
-
}
if(m_CompleteIsSet)
{
diff --git a/samples/client/petstore/cpp-restsdk/model/Order.h b/samples/client/petstore/cpp-restsdk/model/Order.h
index 43893a44fa4..b83944fc7e2 100644
--- a/samples/client/petstore/cpp-restsdk/model/Order.h
+++ b/samples/client/petstore/cpp-restsdk/model/Order.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/model/Pet.cpp b/samples/client/petstore/cpp-restsdk/model/Pet.cpp
index 3c477013b10..23b92949721 100644
--- a/samples/client/petstore/cpp-restsdk/model/Pet.cpp
+++ b/samples/client/petstore/cpp-restsdk/model/Pet.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -146,7 +146,6 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit
{
m_Category->toMultipart(multipart, utility::conversions::to_string_t("category."));
}
-
}
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
{
@@ -172,7 +171,6 @@ void Pet::toMultipart(std::shared_ptr multipart, const utilit
if(m_StatusIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("status"), m_Status));
-
}
}
diff --git a/samples/client/petstore/cpp-restsdk/model/Pet.h b/samples/client/petstore/cpp-restsdk/model/Pet.h
index d8392239766..6746c826ca8 100644
--- a/samples/client/petstore/cpp-restsdk/model/Pet.h
+++ b/samples/client/petstore/cpp-restsdk/model/Pet.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/model/Tag.cpp b/samples/client/petstore/cpp-restsdk/model/Tag.cpp
index 584a4b24cf5..91e608bec9e 100644
--- a/samples/client/petstore/cpp-restsdk/model/Tag.cpp
+++ b/samples/client/petstore/cpp-restsdk/model/Tag.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -78,7 +78,6 @@ void Tag::toMultipart(std::shared_ptr multipart, const utilit
if(m_NameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("name"), m_Name));
-
}
}
diff --git a/samples/client/petstore/cpp-restsdk/model/Tag.h b/samples/client/petstore/cpp-restsdk/model/Tag.h
index 663fe05cfcc..11c00f1bfe2 100644
--- a/samples/client/petstore/cpp-restsdk/model/Tag.h
+++ b/samples/client/petstore/cpp-restsdk/model/Tag.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/cpp-restsdk/model/User.cpp b/samples/client/petstore/cpp-restsdk/model/User.cpp
index a06e9f5aa4b..8484091ae8c 100644
--- a/samples/client/petstore/cpp-restsdk/model/User.cpp
+++ b/samples/client/petstore/cpp-restsdk/model/User.cpp
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
@@ -138,32 +138,26 @@ void User::toMultipart(std::shared_ptr multipart, const utili
if(m_UsernameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("username"), m_Username));
-
}
if(m_FirstNameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("firstName"), m_FirstName));
-
}
if(m_LastNameIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("lastName"), m_LastName));
-
}
if(m_EmailIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("email"), m_Email));
-
}
if(m_PasswordIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("password"), m_Password));
-
}
if(m_PhoneIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("phone"), m_Phone));
-
}
if(m_UserStatusIsSet)
{
diff --git a/samples/client/petstore/cpp-restsdk/model/User.h b/samples/client/petstore/cpp-restsdk/model/User.h
index 0e5f4dc0844..1a8271f26e6 100644
--- a/samples/client/petstore/cpp-restsdk/model/User.h
+++ b/samples/client/petstore/cpp-restsdk/model/User.h
@@ -4,7 +4,7 @@
*
* OpenAPI spec version: 1.0.0
*
- * NOTE: This class is auto generated by OpenAPI-Generator 3.0.0-SNAPSHOT.
+ * NOTE: This class is auto generated by OpenAPI-Generator 3.1.2-SNAPSHOT.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
diff --git a/samples/client/petstore/rust/.openapi-generator/VERSION b/samples/client/petstore/rust/.openapi-generator/VERSION
index 096bf47efe3..a0cd9f0ccb0 100644
--- a/samples/client/petstore/rust/.openapi-generator/VERSION
+++ b/samples/client/petstore/rust/.openapi-generator/VERSION
@@ -1 +1 @@
-3.0.0-SNAPSHOT
\ No newline at end of file
+3.1.0
\ No newline at end of file
diff --git a/samples/client/petstore/rust/examples/client.rs b/samples/client/petstore/rust/examples/client.rs
index 6afa7a900b0..a729ec297c5 100644
--- a/samples/client/petstore/rust/examples/client.rs
+++ b/samples/client/petstore/rust/examples/client.rs
@@ -3,10 +3,10 @@ extern crate hyper;
extern crate petstore_client;
extern crate tokio_core;
-use hyper::Client;
-use hyper::client::HttpConnector;
-use tokio_core::reactor::Core;
use futures::Future;
+use hyper::client::HttpConnector;
+use hyper::Client;
+use tokio_core::reactor::Core;
fn main() {
let mut core = Core::new().expect("failed to init core");
@@ -20,16 +20,16 @@ fn main() {
),
);
- let new_pet = petstore_client::models::Pet::new("barker".to_owned(), vec![]).with_id(1337);
+ let new_pet = petstore_client::models::Pet::new("ferris".to_owned(), vec![]).with_id(128149);
let work = apicli
.pet_api()
.add_pet(new_pet)
.and_then(|_| {
apicli
.pet_api()
- .update_pet_with_form(1337, "barko", "escaped")
+ .update_pet_with_form(128149, "ferris", "rusted")
})
- .and_then(|_| apicli.pet_api().get_pet_by_id(1337))
+ .and_then(|_| apicli.pet_api().get_pet_by_id(128149))
.and_then(|pet| {
println!("pet: {:?}", pet);
futures::future::ok(())
diff --git a/samples/client/petstore/rust/examples/error_handling.rs b/samples/client/petstore/rust/examples/error_handling.rs
index cb3a91d2833..dbd03d0e720 100644
--- a/samples/client/petstore/rust/examples/error_handling.rs
+++ b/samples/client/petstore/rust/examples/error_handling.rs
@@ -3,12 +3,12 @@ extern crate hyper;
extern crate petstore_client;
extern crate tokio_core;
-use hyper::Client;
-use hyper::client::HttpConnector;
-use tokio_core::reactor::Core;
use futures::Future;
+use hyper::client::HttpConnector;
+use hyper::Client;
use petstore_client::apis::client::APIClient;
use petstore_client::apis::Error;
+use tokio_core::reactor::Core;
fn main() {
let mut core = Core::new().expect("failed to init core");
diff --git a/samples/client/petstore/rust/src/apis/mod.rs b/samples/client/petstore/rust/src/apis/mod.rs
index 7199222c3f7..06935c28a93 100644
--- a/samples/client/petstore/rust/src/apis/mod.rs
+++ b/samples/client/petstore/rust/src/apis/mod.rs
@@ -4,6 +4,7 @@ use serde_json;
#[derive(Debug)]
pub enum Error {
+ UriError(hyper::error::UriError),
Hyper(hyper::Error),
Serde(serde_json::Error),
ApiError(ApiError),
@@ -50,6 +51,8 @@ impl From for Error {
use super::models::*;
+mod request;
+
mod pet_api;
pub use self::pet_api::{ PetApi, PetApiClient };
mod store_api;
diff --git a/samples/client/petstore/rust/src/apis/pet_api.rs b/samples/client/petstore/rust/src/apis/pet_api.rs
index 0191b7b87db..0e8a803c559 100644
--- a/samples/client/petstore/rust/src/apis/pet_api.rs
+++ b/samples/client/petstore/rust/src/apis/pet_api.rs
@@ -10,17 +10,13 @@
use std::rc::Rc;
use std::borrow::Borrow;
-use std::borrow::Cow;
-use std::collections::HashMap;
use hyper;
use serde_json;
-use futures;
-use futures::{Future, Stream};
-
-use hyper::header::UserAgent;
+use futures::Future;
use super::{Error, configuration};
+use super::request as __internal_request;
pub struct PetApiClient {
configuration: Rc>,
@@ -48,533 +44,72 @@ pub trait PetApi {
implPetApi for PetApiClient {
fn add_pet(&self, pet: ::models::Pet) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
- let serialized = serde_json::to_string(&pet).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Post, "/pet".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_body_param(pet)
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn delete_pet(&self, pet_id: i64, api_key: &str) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Delete;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
- {
- let mut headers = req.headers_mut();
- headers.set_raw("api_key", api_key);
- }
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Delete, "/pet/{petId}".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_path_param("petId".to_string(), pet_id.to_string())
+ .with_header_param("api_key".to_string(), api_key.to_string())
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn find_pets_by_status(&self, status: Vec) -> Box, Error = Error>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.append_pair("status", &status.join(",").to_string());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet/findByStatus?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/pet/findByStatus".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_query_param("status".to_string(), status.join(",").to_string())
+ .execute(self.configuration.borrow())
}
fn find_pets_by_tags(&self, tags: Vec) -> Box, Error = Error>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.append_pair("tags", &tags.join(",").to_string());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet/findByTags?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/pet/findByTags".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_query_param("tags".to_string(), tags.join(",").to_string())
+ .execute(self.configuration.borrow())
}
fn get_pet_by_id(&self, pet_id: i64) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref apikey) = configuration.api_key {
- let key = apikey.key.clone();
- let val = match apikey.prefix {
- Some(ref prefix) => format!("{} {}", prefix, key),
- None => key,
- };
- auth_headers.insert("api_key".to_owned(), val);
- };
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result<::models::Pet, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/pet/{petId}".to_string())
+ .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
+ in_header: true,
+ in_query: false,
+ param_name: "api_key".to_owned(),
+ }))
+ .with_path_param("petId".to_string(), pet_id.to_string())
+ .execute(self.configuration.borrow())
}
fn update_pet(&self, pet: ::models::Pet) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Put;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
- let serialized = serde_json::to_string(&pet).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Put, "/pet".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_body_param(pet)
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn update_pet_with_form(&self, pet_id: i64, name: &str, status: &str) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet/{petId}?{}", configuration.base_path, query_string, petId=pet_id);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_path_param("petId".to_string(), pet_id.to_string())
+ .with_form_param("name".to_string(), name.to_string())
+ .with_form_param("status".to_string(), status.to_string())
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn upload_file(&self, pet_id: i64, additional_metadata: &str, file: ::models::File) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref token) = configuration.oauth_access_token {
- let auth = hyper::header::Authorization(
- hyper::header::Bearer {
- token: token.to_owned(),
- }
- );
- auth_headers.insert("Authorization".to_owned(), auth.to_string());
- };
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/pet/{petId}/uploadImage?{}", configuration.base_path, query_string, petId=pet_id);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result<::models::ApiResponse, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}/uploadImage".to_string())
+ .with_auth(__internal_request::Auth::Oauth)
+ .with_path_param("petId".to_string(), pet_id.to_string())
+ .with_form_param("additionalMetadata".to_string(), additional_metadata.to_string())
+ .with_form_param("file".to_string(), unimplemented!())
+ .execute(self.configuration.borrow())
}
}
diff --git a/samples/client/petstore/rust/src/apis/request.rs b/samples/client/petstore/rust/src/apis/request.rs
new file mode 100644
index 00000000000..383a409542b
--- /dev/null
+++ b/samples/client/petstore/rust/src/apis/request.rs
@@ -0,0 +1,238 @@
+use std::borrow::Cow;
+use std::collections::HashMap;
+
+use super::{configuration, Error};
+use futures;
+use futures::{Future, Stream};
+use hyper;
+use hyper::header::UserAgent;
+use serde;
+use serde_json;
+
+pub(crate) struct ApiKey {
+ pub in_header: bool,
+ pub in_query: bool,
+ pub param_name: String,
+}
+
+impl ApiKey {
+ fn key(&self, prefix: &Option, key: &str) -> String {
+ match prefix {
+ None => key.to_owned(),
+ Some(ref prefix) => format!("{} {}", prefix, key),
+ }
+ }
+}
+
+pub(crate) enum Auth {
+ None,
+ ApiKey(ApiKey),
+ Basic,
+ Oauth,
+}
+
+pub(crate) struct Request {
+ auth: Auth,
+ method: hyper::Method,
+ path: String,
+ query_params: HashMap,
+ no_return_type: bool,
+ path_params: HashMap,
+ form_params: HashMap,
+ header_params: HashMap,
+ // TODO: multiple body params are possible technically, but not supported here.
+ serialized_body: Option,
+}
+
+impl Request {
+ pub fn new(method: hyper::Method, path: String) -> Self {
+ Request {
+ auth: Auth::None,
+ method: method,
+ path: path,
+ query_params: HashMap::new(),
+ path_params: HashMap::new(),
+ form_params: HashMap::new(),
+ header_params: HashMap::new(),
+ serialized_body: None,
+ no_return_type: false,
+ }
+ }
+
+ pub fn with_body_param(mut self, param: T) -> Self {
+ self.serialized_body = Some(serde_json::to_string(¶m).unwrap());
+ self
+ }
+
+ pub fn with_header_param(mut self, basename: String, param: String) -> Self {
+ self.header_params.insert(basename, param);
+ self
+ }
+
+ pub fn with_query_param(mut self, basename: String, param: String) -> Self {
+ self.query_params.insert(basename, param);
+ self
+ }
+
+ pub fn with_path_param(mut self, basename: String, param: String) -> Self {
+ self.path_params.insert(basename, param);
+ self
+ }
+
+ pub fn with_form_param(mut self, basename: String, param: String) -> Self {
+ self.form_params.insert(basename, param);
+ self
+ }
+
+ pub fn returns_nothing(mut self) -> Self {
+ self.no_return_type = true;
+ self
+ }
+
+ pub fn with_auth(mut self, auth: Auth) -> Self {
+ self.auth = auth;
+ self
+ }
+
+ pub fn execute<'a, C, U>(
+ self,
+ conf: &configuration::Configuration,
+ ) -> Box> + 'a>
+ where
+ C: hyper::client::Connect,
+ U: Sized + 'a,
+ for<'de> U: serde::Deserialize<'de>,
+ {
+ let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned());
+ // raw_headers is for headers we don't know the proper type of (e.g. custom api key
+ // headers); headers is for ones we do know the type of.
+ let mut raw_headers = HashMap::new();
+ let mut headers: hyper::header::Headers = hyper::header::Headers::new();
+
+ let mut path = self.path;
+ for (k, v) in self.path_params {
+ // replace {id} with the value of the id path param
+ path = path.replace(&format!("{{{}}}", k), &v);
+ }
+
+ for (k, v) in self.header_params {
+ raw_headers.insert(k, v);
+ }
+
+ for (key, val) in self.query_params {
+ query_string.append_pair(&key, &val);
+ }
+
+ match self.auth {
+ Auth::ApiKey(apikey) => {
+ if let Some(ref key) = conf.api_key {
+ let val = apikey.key(&key.prefix, &key.key);
+ if apikey.in_query {
+ query_string.append_pair(&apikey.param_name, &val);
+ }
+ if apikey.in_header {
+ raw_headers.insert(apikey.param_name, val);
+ }
+ }
+ }
+ Auth::Basic => {
+ if let Some(ref auth_conf) = conf.basic_auth {
+ let auth = hyper::header::Authorization(hyper::header::Basic {
+ username: auth_conf.0.to_owned(),
+ password: auth_conf.1.to_owned(),
+ });
+ headers.set(auth);
+ }
+ }
+ Auth::Oauth => {
+ if let Some(ref token) = conf.oauth_access_token {
+ let auth = hyper::header::Authorization(hyper::header::Bearer {
+ token: token.to_owned(),
+ });
+ headers.set(auth);
+ }
+ }
+ Auth::None => {}
+ }
+
+ let mut uri_str = format!("{}{}", conf.base_path, path);
+
+ let query_string_str = query_string.finish();
+ if query_string_str != "" {
+ uri_str += "?";
+ uri_str += &query_string_str;
+ }
+ let uri: hyper::Uri = match uri_str.parse() {
+ Err(e) => {
+ return Box::new(futures::future::err(Error::UriError(e)));
+ }
+ Ok(u) => u,
+ };
+
+ let mut req = hyper::Request::new(self.method, uri);
+ {
+ let req_headers = req.headers_mut();
+ if let Some(ref user_agent) = conf.user_agent {
+ req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone())));
+ }
+
+ req_headers.extend(headers.iter());
+
+ for (key, val) in raw_headers {
+ req_headers.set_raw(key, val);
+ }
+ }
+
+ if self.form_params.len() > 0 {
+ req.headers_mut().set(hyper::header::ContentType::form_url_encoded());
+ let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned());
+ for (k, v) in self.form_params {
+ enc.append_pair(&k, &v);
+ }
+ req.set_body(enc.finish());
+ }
+
+ if let Some(body) = self.serialized_body {
+ req.headers_mut().set(hyper::header::ContentType::json());
+ req.headers_mut()
+ .set(hyper::header::ContentLength(body.len() as u64));
+ req.set_body(body);
+ }
+
+ let no_ret_type = self.no_return_type;
+ let res = conf.client
+ .request(req)
+ .map_err(|e| Error::from(e))
+ .and_then(|resp| {
+ let status = resp.status();
+ resp.body()
+ .concat2()
+ .and_then(move |body| Ok((status, body)))
+ .map_err(|e| Error::from(e))
+ })
+ .and_then(|(status, body)| {
+ if status.is_success() {
+ Ok(body)
+ } else {
+ Err(Error::from((status, &*body)))
+ }
+ });
+ Box::new(
+ res
+ .and_then(move |body| {
+ let parsed: Result = if no_ret_type {
+ // This is a hack; if there's no_ret_type, U is (), but serde_json gives an
+ // error when deserializing "" into (), so deserialize 'null' into it
+ // instead.
+ // An alternate option would be to require U: Default, and then return
+ // U::default() here instead since () implements that, but then we'd
+ // need to impl default for all models.
+ serde_json::from_str("null")
+ } else {
+ serde_json::from_slice(&body)
+ };
+ parsed.map_err(|e| Error::from(e))
+ })
+ )
+ }
+}
diff --git a/samples/client/petstore/rust/src/apis/store_api.rs b/samples/client/petstore/rust/src/apis/store_api.rs
index e6e92e8a90a..dc05931697d 100644
--- a/samples/client/petstore/rust/src/apis/store_api.rs
+++ b/samples/client/petstore/rust/src/apis/store_api.rs
@@ -10,17 +10,13 @@
use std::rc::Rc;
use std::borrow::Borrow;
-use std::borrow::Cow;
-use std::collections::HashMap;
use hyper;
use serde_json;
-use futures;
-use futures::{Future, Stream};
-
-use hyper::header::UserAgent;
+use futures::Future;
use super::{Error, configuration};
+use super::request as __internal_request;
pub struct StoreApiClient {
configuration: Rc>,
@@ -44,220 +40,32 @@ pub trait StoreApi {
implStoreApi for StoreApiClient {
fn delete_order(&self, order_id: &str) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Delete;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Delete, "/store/order/{orderId}".to_string())
+ .with_path_param("orderId".to_string(), order_id.to_string())
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn get_inventory(&self, ) -> Box, Error = Error>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let mut auth_headers = HashMap::::new();
- let mut auth_query = HashMap::::new();
- if let Some(ref apikey) = configuration.api_key {
- let key = apikey.key.clone();
- let val = match apikey.prefix {
- Some(ref prefix) => format!("{} {}", prefix, key),
- None => key,
- };
- auth_headers.insert("api_key".to_owned(), val);
- };
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- for (key, val) in &auth_query {
- query.append_pair(key, val);
- }
- query.finish()
- };
- let uri_str = format!("{}/store/inventory?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
- for (key, val) in auth_headers {
- req.headers_mut().set_raw(key, val);
- }
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result<::std::collections::HashMap, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/store/inventory".to_string())
+ .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{
+ in_header: true,
+ in_query: false,
+ param_name: "api_key".to_owned(),
+ }))
+ .execute(self.configuration.borrow())
}
fn get_order_by_id(&self, order_id: i64) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/store/order/{orderId}?{}", configuration.base_path, query_string, orderId=order_id);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result<::models::Order, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/store/order/{orderId}".to_string())
+ .with_path_param("orderId".to_string(), order_id.to_string())
+ .execute(self.configuration.borrow())
}
fn place_order(&self, order: ::models::Order) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/store/order?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
- let serialized = serde_json::to_string(&order).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result<::models::Order, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Post, "/store/order".to_string())
+ .with_body_param(order)
+ .execute(self.configuration.borrow())
}
}
diff --git a/samples/client/petstore/rust/src/apis/user_api.rs b/samples/client/petstore/rust/src/apis/user_api.rs
index 60646085a53..f0976f80ee1 100644
--- a/samples/client/petstore/rust/src/apis/user_api.rs
+++ b/samples/client/petstore/rust/src/apis/user_api.rs
@@ -10,17 +10,13 @@
use std::rc::Rc;
use std::borrow::Borrow;
-use std::borrow::Cow;
-use std::collections::HashMap;
use hyper;
use serde_json;
-use futures;
-use futures::{Future, Stream};
-
-use hyper::header::UserAgent;
+use futures::Future;
use super::{Error, configuration};
+use super::request as __internal_request;
pub struct UserApiClient {
configuration: Rc>,
@@ -48,403 +44,58 @@ pub trait UserApi {
implUserApi for UserApiClient {
fn create_user(&self, user: ::models::User) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
- let serialized = serde_json::to_string(&user).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Post, "/user".to_string())
+ .with_body_param(user)
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn create_users_with_array_input(&self, user: Vec<::models::User>) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user/createWithArray?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
- let serialized = serde_json::to_string(&user).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Post, "/user/createWithArray".to_string())
+ .with_body_param(user)
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn create_users_with_list_input(&self, user: Vec<::models::User>) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Post;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user/createWithList?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
- let serialized = serde_json::to_string(&user).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Post, "/user/createWithList".to_string())
+ .with_body_param(user)
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn delete_user(&self, username: &str) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Delete;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Delete, "/user/{username}".to_string())
+ .with_path_param("username".to_string(), username.to_string())
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn get_user_by_name(&self, username: &str) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result<::models::User, _> = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/user/{username}".to_string())
+ .with_path_param("username".to_string(), username.to_string())
+ .execute(self.configuration.borrow())
}
fn login_user(&self, username: &str, password: &str) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.append_pair("username", &username.to_string());
- query.append_pair("password", &password.to_string());
- query.finish()
- };
- let uri_str = format!("{}/user/login?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|body| {
- let parsed: Result = serde_json::from_slice(&body);
- parsed.map_err(|e| Error::from(e))
- })
- )
+ __internal_request::Request::new(hyper::Method::Get, "/user/login".to_string())
+ .with_query_param("username".to_string(), username.to_string())
+ .with_query_param("password".to_string(), password.to_string())
+ .execute(self.configuration.borrow())
}
fn logout_user(&self, ) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Get;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user/logout?{}", configuration.base_path, query_string);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Get, "/user/logout".to_string())
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
fn update_user(&self, username: &str, user: ::models::User) -> Box>> {
- let configuration: &configuration::Configuration = self.configuration.borrow();
-
- let method = hyper::Method::Put;
-
- let query_string = {
- let mut query = ::url::form_urlencoded::Serializer::new(String::new());
- query.finish()
- };
- let uri_str = format!("{}/user/{username}?{}", configuration.base_path, query_string, username=username);
-
- // TODO(farcaller): handle error
- // if let Err(e) = uri {
- // return Box::new(futures::future::err(e));
- // }
- let mut uri: hyper::Uri = uri_str.parse().unwrap();
-
- let mut req = hyper::Request::new(method, uri);
-
- if let Some(ref user_agent) = configuration.user_agent {
- req.headers_mut().set(UserAgent::new(Cow::Owned(user_agent.clone())));
- }
-
-
-
- let serialized = serde_json::to_string(&user).unwrap();
- req.headers_mut().set(hyper::header::ContentType::json());
- req.headers_mut().set(hyper::header::ContentLength(serialized.len() as u64));
- req.set_body(serialized);
-
- // send request
- Box::new(
- configuration.client.request(req)
- .map_err(|e| Error::from(e))
- .and_then(|resp| {
- let status = resp.status();
- resp.body().concat2()
- .and_then(move |body| Ok((status, body)))
- .map_err(|e| Error::from(e))
- })
- .and_then(|(status, body)| {
- if status.is_success() {
- Ok(body)
- } else {
- Err(Error::from((status, &*body)))
- }
- })
- .and_then(|_| futures::future::ok(()))
- )
+ __internal_request::Request::new(hyper::Method::Put, "/user/{username}".to_string())
+ .with_path_param("username".to_string(), username.to_string())
+ .with_body_param(user)
+ .returns_nothing()
+ .execute(self.configuration.borrow())
}
}
diff --git a/scripts/openapi-generator-cli-completion.bash b/scripts/openapi-generator-cli-completion.bash
new file mode 100644
index 00000000000..96233fb22ed
--- /dev/null
+++ b/scripts/openapi-generator-cli-completion.bash
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+
+###
+# Provides completion assistance for openapi-generator-cli
+# Install
+# Mac:
+# brew install bash-completion
+# cp openapi-generator-cli-completion.bash `brew --prefix`/etc/bash_completion.d
+# Linux: many distributions include this automatically. Search for your distro-specific instructions.
+# When in doubt, try sourcing this file:
+# type complete && source openapi-generator-cli
+#
+# see http://tldp.org/LDP/abs/html/tabexpansion.html
+###
+
+_openapi_generator_cli_completions() {
+ COMPREPLY=()
+ local IFS=$' \t\n'
+ local options=()
+
+ options+=("$($1 completion ${COMP_WORDS[@]:1})")
+
+ case "${COMP_WORDS[1]}" in
+ generate)
+ case "${COMP_WORDS[@]:2}" in
+ -l|--lang|-g|--generator-name)
+ # TODO: This is a nice-to-have and not required.
+ # Apply generator-specific options to additional properties. These can be queried via:
+ # openapi-generator-cli config-help -l YOUR_LANG | grep '^\t' | grep -v '^\t\s\s\s\s' | tr -d '\t'
+ # where YOUR_LANG would need to be evaluated as the value after the current switch.
+ # but rather than switching on 'generate' maybe switch on --additional-properties?
+ ;;
+ esac
+ ;;
+ *)
+ # ignore
+ ;;
+ esac
+
+ # printf '%s\n' "${options[@]}"
+ if [[ -n "${options[@]}" ]]; then
+ COMPREPLY=( $(compgen -W "${options}" -- ${2}) )
+ fi
+}
+
+complete -F _openapi_generator_cli_completions openapi-generator-cli