From 86bcd18532f8303b2fbe4cf627e374d600df5727 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 18 Dec 2018 12:07:36 +0000 Subject: [PATCH] [Rust Server] Improve XML support - Restore XML namespace support - Remove non snake case rust warning for xml wrap_in methods - Add XML rust-server tests - Fix wrapping XML arrays when a property of another object - Run all tests, not just those for OpenAPI 2.0 - Force wrapping for rust-server --- bin/rust-server-petstore.sh | 12 +- .../codegen/languages/RustServerCodegen.java | 114 ++-- .../resources/rust-server/client-mod.mustache | 42 +- .../rust-server/example-server_lib.mustache | 2 + .../resources/rust-server/models.mustache | 51 +- .../resources/rust-server/server-mod.mustache | 2 +- .../2_0/rust-server/rust-server-test.yaml | 1 + .../resources/3_0/rust-server/openapi-v3.yaml | 136 ++++ .../output/openapi-v3/.cargo/config | 18 + .../rust-server/output/openapi-v3/.gitignore | 2 + .../openapi-v3/.openapi-generator-ignore | 23 + .../openapi-v3/.openapi-generator/VERSION | 1 + .../rust-server/output/openapi-v3/Cargo.toml | 48 ++ .../rust-server/output/openapi-v3/README.md | 141 ++++ .../output/openapi-v3/api/openapi.yaml | 132 ++++ .../output/openapi-v3/docs/AnotherXmlArray.md | 9 + .../output/openapi-v3/docs/AnotherXmlInner.md | 9 + .../openapi-v3/docs/AnotherXmlObject.md | 10 + .../openapi-v3/docs/DuplicateXmlObject.md | 11 + .../output/openapi-v3/docs/XmlArray.md | 9 + .../output/openapi-v3/docs/XmlInner.md | 9 + .../output/openapi-v3/docs/XmlObject.md | 11 + .../output/openapi-v3/docs/default_api.md | 173 +++++ .../output/openapi-v3/examples/ca.pem | 17 + .../output/openapi-v3/examples/client.rs | 110 +++ .../openapi-v3/examples/server-chain.pem | 66 ++ .../output/openapi-v3/examples/server-key.pem | 28 + .../output/openapi-v3/examples/server.rs | 75 ++ .../openapi-v3/examples/server_lib/mod.rs | 37 + .../openapi-v3/examples/server_lib/server.rs | 70 ++ .../output/openapi-v3/src/client/mod.rs | 642 ++++++++++++++++++ .../rust-server/output/openapi-v3/src/lib.rs | 178 +++++ .../output/openapi-v3/src/mimetypes.rs | 33 + .../output/openapi-v3/src/models.rs | 364 ++++++++++ .../output/openapi-v3/src/server/context.rs | 91 +++ .../output/openapi-v3/src/server/mod.rs | 580 ++++++++++++++++ .../README.md | 1 + .../docs/AnimalFarm.md | 9 + .../docs/fake_api.md | 6 +- .../examples/client.rs | 6 +- .../examples/server_lib/server.rs | 6 +- .../src/client/mod.rs | 54 +- .../src/lib.rs | 18 +- .../src/models.rs | 388 ++++++++++- .../src/server/mod.rs | 6 +- .../output/rust-server-test/README.md | 1 + .../docs/AdditionalPropertiesObject.md | 9 + .../examples/server_lib/mod.rs | 1 - .../output/rust-server-test/src/client/mod.rs | 6 - .../output/rust-server-test/src/models.rs | 18 +- 50 files changed, 3625 insertions(+), 161 deletions(-) create mode 100644 modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/.cargo/config create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/.gitignore create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/README.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlArray.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlInner.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlObject.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/DuplicateXmlObject.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/XmlArray.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/XmlInner.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/ca.pem create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/src/models.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/src/server/context.rs create mode 100644 samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs create mode 100644 samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AnimalFarm.md create mode 100644 samples/server/petstore/rust-server/output/rust-server-test/docs/AdditionalPropertiesObject.md diff --git a/bin/rust-server-petstore.sh b/bin/rust-server-petstore.sh index 5d76464ace38..2542d31b1238 100755 --- a/bin/rust-server-petstore.sh +++ b/bin/rust-server-petstore.sh @@ -25,10 +25,16 @@ then mvn -B clean package fi -for spec_path in modules/openapi-generator/src/test/resources/2_0/rust-server/* ; do +for spec_path in modules/openapi-generator/src/test/resources/*/rust-server/* ; do export JAVA_OPTS="${JAVA_OPTS} -XX:MaxPermSize=256M -Xmx1024M -DloggerPath=conf/log4j.properties" spec=$(basename "$spec_path" | sed 's/.yaml//') - ags="generate -t modules/openapi-generator/src/main/resources/rust-server -i $spec_path -g rust-server -o samples/server/petstore/rust-server/output/$spec -DpackageName=$spec --additional-properties hideGenerationTimestamp=true $@" + args="generate --template-dir modules/openapi-generator/src/main/resources/rust-server + --input-spec $spec_path + --generator-name rust-server + --output samples/server/petstore/rust-server/output/$spec + -DpackageName=$spec + --additional-properties hideGenerationTimestamp=true + $@" - java $JAVA_OPTS -jar $executable $ags + java $JAVA_OPTS -jar $executable $args done diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index b8a14c5218c2..084650b0603d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -17,14 +17,17 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.FileSchema; import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.media.XML; import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.servers.Server; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; @@ -64,6 +67,9 @@ public class RustServerCodegen extends DefaultCodegen implements CodegenConfig { public RustServerCodegen() { super(); + // Force generating models for wrapping types + ModelUtils.setGenerateAliasAsModel(true); + // Show the generation timestamp by default hideGenerationTimestamp = Boolean.FALSE; @@ -742,6 +748,39 @@ public boolean isDataTypeFile(final String dataType) { return dataType != null && dataType.equals(typeMapping.get("File").toString()); } + // This is a really terrible hack. We're working around the fact that the + // base version of `fromRequestBody` checks to see whether the body is a + // ref. If so, it unwraps the reference and replaces it with its inner + // type. This causes problems in rust-server, as it means that we use inner + // types in the API, rather than the correct outer type. + // + // Thus, we grab the inner schema beforehand, and then tinker afterwards to + // restore things to sensible values. + @Override + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + Schema original_schema = ModelUtils.getSchemaFromRequestBody(body); + CodegenParameter codegenParameter = super.fromRequestBody(body, imports, bodyParameterName); + + if (StringUtils.isNotBlank(original_schema.get$ref())) { + // Undo the mess `super.fromRequestBody` made - re-wrap the inner + // type. + codegenParameter.dataType = getTypeDeclaration(original_schema); + codegenParameter.isPrimitiveType = false; + codegenParameter.isListContainer = false; + codegenParameter.isString = false; + + // This is a model, so should only have an example if explicitly + // defined. + if (codegenParameter.vendorExtensions != null && codegenParameter.vendorExtensions.containsKey("x-example")) { + codegenParameter.example = Json.pretty(codegenParameter.vendorExtensions.get("x-example")); + } else { + codegenParameter.example = null; + } + } + + return codegenParameter; + } + @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isArraySchema(p)) { @@ -779,35 +818,6 @@ public String getTypeDeclaration(Schema p) { return super.getTypeDeclaration(p); } - private boolean isNonPrimitive(CodegenParameter parameter) { - return !parameter.isString && !parameter.isNumeric && !parameter.isByteArray && - !parameter.isBinary && !parameter.isFile && !parameter.isBoolean && - !parameter.isDate && !parameter.isDateTime && !parameter.isUuid && - !parameter.isListContainer && !parameter.isMapContainer && - !languageSpecificPrimitives.contains(parameter.dataType); - } - - @Override - public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter parameter = super.fromParameter(param, imports); - if (isNonPrimitive(parameter)) { - String name = "models::" + getTypeDeclaration(parameter.dataType); - parameter.dataType = name; - } - - return parameter; - } - - @Override - public void postProcessParameter(CodegenParameter parameter) { - // If this parameter is not a primitive type, prefix it with "models::" - // to ensure it's namespaced correctly in the Rust code. - if (isNonPrimitive(parameter)) { - String name = "models::" + getTypeDeclaration(parameter.dataType); - parameter.dataType = name; - } - } - @Override public String toInstantiationType(Schema p) { if (ModelUtils.isArraySchema(p)) { @@ -833,17 +843,34 @@ public CodegenModel fromModel(String name, Schema model) { } if (ModelUtils.isArraySchema(model)) { ArraySchema am = (ArraySchema) model; + String xmlName = null; + + // Detect XML list where the inner item is defined directly. if ((am.getItems() != null) && (am.getItems().getXml() != null)) { + xmlName = am.getItems().getXml().getName(); + } - // If this model's items require wrapping in xml, squirrel - // away the xml name so we can insert it into the relevant model fields. - String xmlName = am.getItems().getXml().getName(); - if (xmlName != null) { - mdl.vendorExtensions.put("itemXmlName", xmlName); - modelXmlNames.put("models::" + mdl.classname, xmlName); + // Detect XML list where the inner item is a reference. + if (am.getXml() != null && am.getXml().getWrapped() && + am.getItems() != null && + !StringUtils.isEmpty(am.getItems().get$ref())) { + Schema inner_schema = allDefinitions.get( + ModelUtils.getSimpleRef(am.getItems().get$ref())); + + if (inner_schema.getXml() != null && + inner_schema.getXml().getName() != null) { + xmlName = inner_schema.getXml().getName(); } } + + // If this model's items require wrapping in xml, squirrel away the + // xml name so we can insert it into the relevant model fields. + if (xmlName != null) { + mdl.vendorExtensions.put("itemXmlName", xmlName); + modelXmlNames.put("models::" + mdl.classname, xmlName); + } + mdl.arrayModelType = toModelName(mdl.arrayModelType); } @@ -1076,23 +1103,6 @@ public Map postProcessModels(Map objs) { return super.postProcessModelsEnum(objs); } - private boolean paramHasXmlNamespace(CodegenParameter param, Map definitions) { - Object refName = param.vendorExtensions.get("refName"); - - if ((refName != null) && (refName instanceof String)) { - String name = (String) refName; - Schema model = definitions.get(ModelUtils.getSimpleRef(name)); - - if (model != null) { - XML xml = model.getXml(); - if ((xml != null) && (xml.getNamespace() != null)) { - return true; - } - } - } - return false; - } - private void processParam(CodegenParameter param, CodegenOperation op) { String example = null; diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache index 3bba307bea08..36d7d5403d62 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache @@ -280,23 +280,31 @@ impl Api for Client where request.headers_mut().set(ContentType(mimetypes::requests::{{#vendorExtensions}}{{{uppercase_operation_id}}}{{/vendorExtensions}}.clone())); request.set_body(body.into_bytes());{{/-last}}{{/formParams}}{{/vendorExtensions}}{{#bodyParam}}{{#-first}} // Body parameter -{{/-first}}{{#vendorExtensions}}{{#required}}{{#consumesPlainText}} let body = param_{{{paramName}}};{{/consumesPlainText}}{{#consumesXml}} -{{^has_namespace}} let body = serde_xml_rs::to_string(¶m_{{{paramName}}}).expect("impossible to fail to serialize");{{/has_namespace}}{{#has_namespace}} - let mut namespaces = BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::{{{uppercase_data_type}}}.clone()); - let body = serde_xml_rs::to_string_with_namespaces(¶m_{{{paramName}}}, namespaces).expect("impossible to fail to serialize");{{/has_namespace}}{{/consumesXml}}{{#consumesJson}} - let body = serde_json::to_string(¶m_{{{paramName}}}).expect("impossible to fail to serialize");{{/consumesJson}} -{{/required}}{{^required}}{{#consumesPlainText}} let body = param_{{{paramName}}}; -{{/consumesPlainText}}{{^consumesPlainText}} let body = param_{{{paramName}}}.map(|ref body| { -{{#consumesXml}} -{{^has_namespace}} serde_xml_rs::to_string(body).expect("impossible to fail to serialize"){{/has_namespace}}{{#has_namespace}} - let mut namespaces = BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::{{{uppercase_data_type}}}.clone()); - serde_xml_rs::to_string_with_namespaces(body, namespaces).expect("impossible to fail to serialize"){{/has_namespace}}{{/consumesXml}}{{#consumesJson}} - serde_json::to_string(body).expect("impossible to fail to serialize"){{/consumesJson}} - });{{/consumesPlainText}}{{/required}}{{/vendorExtensions}}{{/bodyParam}} + {{/-first}} + {{#vendorExtensions}} + {{#consumesPlainText}} + let body = param_{{{paramName}}}; + {{/consumesPlainText}} + {{#required}} + {{#consumesXml}} + let body = param_{{{paramName}}}.to_xml(); + {{/consumesXml}} + {{#consumesJson}} + let body = serde_json::to_string(¶m_{{{paramName}}}).expect("impossible to fail to serialize"); + {{/consumesJson}} + {{/required}} + {{^required}} + let body = param_{{{paramName}}}.map(|ref body| { + {{#consumesXml}} + body.to_xml() + {{/consumesXml}} + {{#consumesJson}} + serde_json::to_string(body).expect("impossible to fail to serialize") + {{/consumesJson}} + }); + {{/required}} + {{/vendorExtensions}} + {{/bodyParam}} {{#bodyParam}}{{^required}}if let Some(body) = body { {{/required}} request.set_body(body.into_bytes()); diff --git a/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache index 036d1a2911f8..edb2aad9d451 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache @@ -13,7 +13,9 @@ use std::marker::PhantomData; use hyper; use {{{externCrateName}}}; use swagger::{Has, XSpanIdString}; +{{#hasAuthMethods}} use swagger::auth::Authorization; +{{/hasAuthMethods}} pub struct NewService{ marker: PhantomData diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index aa106c2b7009..eb8f0892b98a 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -2,10 +2,17 @@ extern crate chrono; extern crate uuid; -{{#usesXml}}use serde_xml_rs;{{/usesXml}} +{{#usesXml}} +use serde_xml_rs; +{{/usesXml}} use serde::ser::Serializer; +{{#usesXml}} +use std::collections::{HashMap, BTreeMap}; +{{/usesXml}} +{{^usesXml}} use std::collections::HashMap; +{{/usesXml}} use models; use swagger; @@ -70,6 +77,7 @@ impl ::std::ops::DerefMut for {{{classname}}} { } {{/dataType}}{{^dataType}}{{#arrayModelType}}{{#vendorExtensions}}{{#itemXmlName}}// Utility function for wrapping list elements when serializing xml +#[allow(non_snake_case)] fn wrap_in_{{{itemXmlName}}}(item: &Vec<{{{arrayModelType}}}>, serializer: S) -> Result where S: Serializer, @@ -78,7 +86,7 @@ where } {{/itemXmlName}}{{/vendorExtensions}}{{! vec}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct {{{classname}}}(Vec<{{{arrayModelType}}}>); +pub struct {{{classname}}}({{#vendorExtensions}}{{#itemXmlName}}#[serde(serialize_with = "wrap_in_{{{itemXmlName}}}")]{{/itemXmlName}}{{/vendorExtensions}}Vec<{{{arrayModelType}}}>); impl ::std::convert::From> for {{{classname}}} { fn from(x: Vec<{{{arrayModelType}}}>) -> Self { @@ -164,12 +172,37 @@ impl {{{classname}}} { } } } -{{/arrayModelType}}{{/dataType}}{{/isEnum}}{{/model}}{{/models}}{{#usesXmlNamespaces}} -//XML namespaces -pub mod namespaces { - lazy_static!{ - {{#models}}{{#model}}{{#xmlNamespace}}pub static ref {{#vendorExtensions}}{{{upperCaseName}}}{{/vendorExtensions}}: String = "{{{xmlNamespace}}}".to_string(); - {{/xmlNamespace}}{{/model}}{{/models}} - } +{{/arrayModelType}} +{{/dataType}} +{{/isEnum}} + +{{#usesXml}} +{{#usesXmlNamespaces}} +{{#xmlNamespace}} +impl {{{classname}}} { + /// Associated constant for this model's XML namespace. + #[allow(dead_code)] + pub const NAMESPACE: &'static str = "{{{xmlNamespace}}}"; } + +{{/xmlNamespace}} {{/usesXmlNamespaces}} +impl {{{classname}}} { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + {{#xmlNamespace}} + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); + serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + {{/xmlNamespace}} + {{^xmlNamespace}} + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + {{/xmlNamespace}} + } +} +{{/usesXml}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache index 887d1e468f1f..e33501d84838 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-mod.mustache @@ -331,7 +331,7 @@ where {{/has_namespace}}{{#has_namespace}} let mut namespaces = BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::{{{uppercase_data_type}}}.clone()); + namespaces.insert("".to_string(), {{{dataType}}}::NAMESPACE.to_string()); let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); {{/has_namespace}}{{/producesXml}}{{#producesJson}} let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); diff --git a/modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml b/modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml index e8065080038f..3a4579da13f2 100644 --- a/modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml @@ -52,6 +52,7 @@ paths: description: Success schema: type: object + # Requests with arbitrary JSON currently fail. # post: # summary: Send an arbitrary JSON blob diff --git a/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml new file mode 100644 index 000000000000..c25db3511508 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml @@ -0,0 +1,136 @@ +# Test the mainline function of the XML part of the OpenAPI specification, +# as found here : https://swagger.io/docs/specification/data-models/representing-xml/ +# +# Specifically, these tests are intended to include: +# - namespaces +# - arrays +# - as the whole response body +# - within another object +# - wrapping and renaming to and from camelCase and snake_case +# - objects +# - renaming to and from camelCase and snake_case + +openapi: 3.0.1 +info: + title: My title + description: API under test + version: 1.0.7 +paths: + /xml: + post: + summary: Post an array + description: '' + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/xml_array' + responses: + '201': + description: 'OK' + '400': + description: Bad Request + put: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/xml_object' + responses: + '201': + description: 'OK' + '400': + description: Bad Request + /xml_other: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/anotherXmlObject' + responses: + '201': + description: 'OK' + '400': + description: Bad Request + put: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/anotherXmlArray' + responses: + '201': + description: 'OK' + '400': + description: Bad Request + /xml_extra: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/duplicate_xml_object' + responses: + '201': + description: 'OK' + '400': + description: Bad Request +components: + schemas: + xml_array: + xml: + name: CamelXmlArray + wrapped: true + type: array + items: + $ref: '#/components/schemas/xml_inner' + xml_inner: + type: string + xml: + name: camelXmlInner + xml_object: + title: an XML object + description: An XML object + type: object + properties: + innerString: + type: string + other_inner_rename: + type: integer + xml: + name: camelXmlObject + namespace: http://foo.bar + duplicate_xml_object: + description: An XML object + type: object + required: + - inner_array + properties: + inner_string: + type: string + inner_array: + $ref: '#/components/schemas/xml_array' + xml: + name: camelDuplicateXmlObject + namespace: http://different.bar + anotherXmlArray: + type: array + xml: + wrapped: true + name: snake_another_xml_array + items: + $ref: '#/components/schemas/anotherXmlInner' + anotherXmlInner: + type: string + xml: + name: snake_another_xml_inner + anotherXmlObject: + description: An XML object + type: object + properties: + inner_string: + type: string + xml: + name: snake_another_xml_object + namespace: http://foo.bar diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.cargo/config b/samples/server/petstore/rust-server/output/openapi-v3/.cargo/config new file mode 100644 index 000000000000..b8acc9c00c8c --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.cargo/config @@ -0,0 +1,18 @@ +[build] +rustflags = [ + "-W", "missing_docs", # detects missing documentation for public members + + "-W", "trivial_casts", # detects trivial casts which could be removed + + "-W", "trivial_numeric_casts", # detects trivial casts of numeric types which could be removed + + "-W", "unsafe_code", # usage of `unsafe` code + + "-W", "unused_qualifications", # detects unnecessarily qualified names + + "-W", "unused_extern_crates", # extern crates that are never used + + "-W", "unused_import_braces", # unnecessary braces around an imported item + + "-D", "warnings", # all warnings should be denied +] diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.gitignore b/samples/server/petstore/rust-server/output/openapi-v3/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION new file mode 100644 index 000000000000..afa636560641 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml new file mode 100644 index 000000000000..b2edca9c74bd --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "openapi-v3" +version = "1.0.7" +authors = [] +description = "API under test" +license = "Unlicense" + +[features] +default = ["client", "server"] +client = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"] +server = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"] + +[dependencies] +# Required by example server. +# +chrono = { version = "0.4", features = ["serde"] } +futures = "0.1" +hyper = {version = "0.11", optional = true} +hyper-tls = {version = "0.1.2", optional = true} +swagger = "2" + +# Not required by example server. +# +lazy_static = "0.2" +log = "0.3.0" +mime = "0.3.3" +multipart = {version = "0.13.3", optional = true} +native-tls = {version = "0.1.4", optional = true} +openssl = {version = "0.9.14", optional = true} +percent-encoding = {version = "1.0.0", optional = true} +regex = {version = "0.2", optional = true} +serde = "1.0" +serde_derive = "1.0" +serde_ignored = {version = "0.0.4", optional = true} +serde_json = {version = "1.0", optional = true} +serde_urlencoded = {version = "0.5.1", optional = true} +tokio-core = {version = "0.1.6", optional = true} +tokio-proto = {version = "0.1.1", optional = true} +tokio-tls = {version = "0.1.3", optional = true, features = ["tokio-proto"]} +url = {version = "1.5", optional = true} +uuid = {version = "0.5", optional = true, features = ["serde", "v4"]} +# ToDo: this should be updated to point at the official crate once +# https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream +serde-xml-rs = {git = "git://github.com/Metaswitch/serde-xml-rs.git" , branch = "master", optional = true} + +[dev-dependencies] +clap = "2.25" +error-chain = "0.12" diff --git a/samples/server/petstore/rust-server/output/openapi-v3/README.md b/samples/server/petstore/rust-server/output/openapi-v3/README.md new file mode 100644 index 000000000000..25f257405763 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/README.md @@ -0,0 +1,141 @@ +# Rust API for openapi-v3 + +API under test + +## Overview +This client/server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate a server stub. +- + +To see how to make this your own, look here: + +[README]((https://openapi-generator.tech)) + +- API version: 1.0.7 + +This autogenerated project defines an API crate `openapi-v3` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* A `Client` type which implements `Api` and issues HTTP requests for each operation. +* A router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + +It also contains an example server and client which make use of `openapi-v3`: +* The example server starts up a web server using the `openapi-v3` router, + and supplies a trivial implementation of `Api` which returns failure for every operation. +* The example client provides a CLI which lets you invoke any single operation on the + `openapi-v3` client by passing appropriate arguments on the command line. + +You can use the example server and client as a basis for your own code. +See below for [more detail on implementing a server](#writing-a-server). + + +## Examples + +Run examples with: + +``` +cargo run --example +``` + +To pass in arguments to the examples, put them after `--`, for example: + +``` +cargo run --example client -- --help +``` + +### Running the server +To run the server, follow these simple steps: + +``` +cargo run --example server +``` + +### Running a client +To run a client, follow one of the following simple steps: + +``` +cargo run --example client XmlExtraPost +cargo run --example client XmlOtherPost +cargo run --example client XmlOtherPut +cargo run --example client XmlPost +cargo run --example client XmlPut +``` + +### HTTPS +The examples can be run in HTTPS mode by passing in the flag `--https`, for example: + +``` +cargo run --example server -- --https +``` + +This will use the keys/certificates from the examples directory. Note that the server chain is signed with +`CN=localhost`. + + +## Writing a server + +The server example is designed to form the basis for implementing your own server. Simply follow these steps. + +* Set up a new Rust project, e.g., with `cargo init --bin`. +* Insert `openapi-v3` into the `members` array under [workspace] in the root `Cargo.toml`, e.g., `members = [ "openapi-v3" ]`. +* Add `openapi-v3 = {version = "1.0.7", path = "openapi-v3"}` under `[dependencies]` in the root `Cargo.toml`. +* Copy the `[dependencies]` and `[dev-dependencies]` from `openapi-v3/Cargo.toml` into the root `Cargo.toml`'s `[dependencies]` section. + * Copy all of the `[dev-dependencies]`, but only the `[dependencies]` that are required by the example server. These should be clearly indicated by comments. + * Remove `"optional = true"` from each of these lines if present. + +Each autogenerated API will contain an implementation stub and main entry point, which should be copied into your project the first time: +``` +cp openapi-v3/examples/server.rs src/main.rs +cp openapi-v3/examples/server_lib/mod.rs src/lib.rs +cp openapi-v3/examples/server_lib/server.rs src/server.rs +``` + +Now + +* From `src/main.rs`, remove the `mod server_lib;` line, and uncomment and fill in the `extern crate` line with the name of this server crate. +* Move the block of imports "required by the service library" from `src/main.rs` to `src/lib.rs` and uncomment. +* Change the `let server = server::Server {};` line to `let server = SERVICE_NAME::server().unwrap();` where `SERVICE_NAME` is the name of the server crate. +* Run `cargo build` to check it builds. +* Run `cargo fmt` to reformat the code. +* Commit the result before making any further changes (lest format changes get confused with your own updates). + +Now replace the implementations in `src/server.rs` with your own code as required. + +## Updating your server to track API changes + +Later, if the API changes, you can copy new sections from the autogenerated API stub into your implementation. +Alternatively, implement the now-missing methods based on the compiler's error messages. + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[****](docs/default_api.md#) | **POST** /xml_extra | +[****](docs/default_api.md#) | **POST** /xml_other | +[****](docs/default_api.md#) | **PUT** /xml_other | +[****](docs/default_api.md#) | **POST** /xml | Post an array +[****](docs/default_api.md#) | **PUT** /xml | + + +## Documentation For Models + + - [AnotherXmlArray](docs/AnotherXmlArray.md) + - [AnotherXmlInner](docs/AnotherXmlInner.md) + - [AnotherXmlObject](docs/AnotherXmlObject.md) + - [DuplicateXmlObject](docs/DuplicateXmlObject.md) + - [XmlArray](docs/XmlArray.md) + - [XmlInner](docs/XmlInner.md) + - [XmlObject](docs/XmlObject.md) + + +## Documentation For Authorization + Endpoints do not require authorization. + + +## Author + + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml new file mode 100644 index 000000000000..61ba273c4e41 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -0,0 +1,132 @@ +openapi: 3.0.1 +info: + description: API under test + title: My title + version: 1.0.7 +servers: +- url: / +paths: + /xml: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/xml_array' + responses: + 201: + description: OK + 400: + description: Bad Request + summary: Post an array + put: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/xml_object' + responses: + 201: + description: OK + 400: + description: Bad Request + /xml_other: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/anotherXmlObject' + responses: + 201: + description: OK + 400: + description: Bad Request + put: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/anotherXmlArray' + responses: + 201: + description: OK + 400: + description: Bad Request + /xml_extra: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/duplicate_xml_object' + responses: + 201: + description: OK + 400: + description: Bad Request +components: + schemas: + xml_array: + items: + $ref: '#/components/schemas/xml_inner' + type: array + xml: + name: CamelXmlArray + wrapped: true + xml_inner: + type: string + xml: + name: camelXmlInner + xml_object: + description: An XML object + properties: + innerString: + type: string + other_inner_rename: + format: int32 + type: integer + title: an XML object + type: object + xml: + name: camelXmlObject + namespace: http://foo.bar + duplicate_xml_object: + description: An XML object + properties: + inner_string: + type: string + inner_array: + items: + $ref: '#/components/schemas/xml_inner' + type: array + xml: + name: CamelXmlArray + wrapped: true + required: + - inner_array + type: object + xml: + name: camelDuplicateXmlObject + namespace: http://different.bar + anotherXmlArray: + items: + $ref: '#/components/schemas/anotherXmlInner' + type: array + xml: + name: snake_another_xml_array + wrapped: true + anotherXmlInner: + type: string + xml: + name: snake_another_xml_inner + anotherXmlObject: + description: An XML object + properties: + inner_string: + type: string + type: object + xml: + name: snake_another_xml_object + namespace: http://foo.bar + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlArray.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlArray.md new file mode 100644 index 000000000000..aa3674f8a248 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlArray.md @@ -0,0 +1,9 @@ +# AnotherXmlArray + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlInner.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlInner.md new file mode 100644 index 000000000000..8901bb75ccb4 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlInner.md @@ -0,0 +1,9 @@ +# AnotherXmlInner + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlObject.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlObject.md new file mode 100644 index 000000000000..9bf2745b5233 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/AnotherXmlObject.md @@ -0,0 +1,10 @@ +# AnotherXmlObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**inner_string** | **String** | | [optional] [default to None] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/DuplicateXmlObject.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/DuplicateXmlObject.md new file mode 100644 index 000000000000..6211ee39c5d8 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/DuplicateXmlObject.md @@ -0,0 +1,11 @@ +# DuplicateXmlObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**inner_string** | **String** | | [optional] [default to None] +**inner_array** | **Vec** | | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlArray.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlArray.md new file mode 100644 index 000000000000..e58358c6a790 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlArray.md @@ -0,0 +1,9 @@ +# XmlArray + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlInner.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlInner.md new file mode 100644 index 000000000000..99b76bc3a613 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlInner.md @@ -0,0 +1,9 @@ +# XmlInner + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md new file mode 100644 index 000000000000..49ab2bec0e79 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/XmlObject.md @@ -0,0 +1,11 @@ +# XmlObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**inner_string** | **String** | | [optional] [default to None] +**other_inner_rename** | **i32** | | [optional] [default to None] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md new file mode 100644 index 000000000000..baf8c265cfb9 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/default_api.md @@ -0,0 +1,173 @@ +# default_api + +All URIs are relative to *http://localhost* + +Method | HTTP request | Description +------------- | ------------- | ------------- +****](default_api.md#) | **POST** /xml_extra | +****](default_api.md#) | **POST** /xml_other | +****](default_api.md#) | **PUT** /xml_other | +****](default_api.md#) | **POST** /xml | Post an array +****](default_api.md#) | **PUT** /xml | + + +# **** +> (optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **duplicate_xml_object** | [**DuplicateXmlObject**](DuplicateXmlObject.md)| | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **** +> (optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **another_xml_object** | [**AnotherXmlObject**](AnotherXmlObject.md)| | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **** +> (optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **string** | [**array**](array.md)| | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **** +> (optional) +Post an array + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **string** | [**array**](array.md)| | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **** +> (optional) + + +### Required Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **optional** | **map[string]interface{}** | optional parameters | nil if no parameters + +### Optional Parameters +Optional parameters are passed through a map[string]interface{}. + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **xml_object** | [**XmlObject**](XmlObject.md)| | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/xml + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/ca.pem b/samples/server/petstore/rust-server/output/openapi-v3/examples/ca.pem new file mode 100644 index 000000000000..d2317fb5db7d --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/ca.pem @@ -0,0 +1,17 @@ +-----BEGIN CERTIFICATE----- +MIICtjCCAZ4CCQDpKecRERZ0xDANBgkqhkiG9w0BAQsFADAdMQswCQYDVQQGEwJV +UzEOMAwGA1UEAxMFTXkgQ0EwHhcNMTcwNTIzMTYwMDIzWhcNMTcwNjIyMTYwMDIz +WjAdMQswCQYDVQQGEwJVUzEOMAwGA1UEAxMFTXkgQ0EwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQCt66py3x7sCSASRF2D05L5wkNDxAUjQKYx23W8Gbwv +GMGykk89BIdU5LX1JB1cKiUOkoIxfwAYuWc2V/wzTvVV7+11besnk3uX1c9KiqUF +LIX7kn/z5hzS4aelhKvH+MJlSZCSlp1ytpZbwo5GB5Pi2SGH56jDBiBoDRNBVdWL +z4wH7TdrQjqWwNxIZumD5OGMtcfJyuX08iPiEOaslOeoMqzObhvjc9aUgjVjhqyA +FkJGTXsi0oaD7oml+NE+mTNfEeZvEJQpLSjBY0OvQHzuHkyGBShBnfu/9x7/NRwd +WaqsLiF7/re9KDGYdJwP7Cu6uxYfKAyWarp6h2mG/GIdAgMBAAEwDQYJKoZIhvcN +AQELBQADggEBAGIl/VVIafeq/AJOQ9r7TzzB2ABJYr7NZa6bTu5O1jSp1Fonac15 +SZ8gvRxODgH22ZYSqghPG4xzq4J3hkytlQqm57ZEt2I2M3OqIp17Ndcc1xDYzpLl +tA0FrVn6crQTM8vQkTDtGesaCWX+7Fir5dK7HnYWzfpSmsOpST07PfbNisEXKOxG +Dj4lBL1OnhTjsJeymVS1pFvkKkrcEJO+IxFiHL3CDsWjcXB0Z+E1zBtPoYyYsNsO +rBrjUxcZewF4xqWZhpW90Mt61fY2nRgU0uUwHcvDQUqvmzKcsqYa4mPKzfBI5mxo +01Ta96cDD6pS5Y1hOflZ0g84f2g/7xBLLDA= +-----END CERTIFICATE----- diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs new file mode 100644 index 000000000000..2d88c04aebe7 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs @@ -0,0 +1,110 @@ +#![allow(missing_docs, unused_variables, trivial_casts)] + +extern crate openapi_v3; +#[allow(unused_extern_crates)] +extern crate futures; +#[allow(unused_extern_crates)] +#[macro_use] +extern crate swagger; +#[allow(unused_extern_crates)] +extern crate uuid; +extern crate clap; +extern crate tokio_core; + +use swagger::{ContextBuilder, EmptyContext, XSpanIdString, Has, Push, AuthData}; + +#[allow(unused_imports)] +use futures::{Future, future, Stream, stream}; +use tokio_core::reactor; +#[allow(unused_imports)] +use openapi_v3::{ApiNoContext, ContextWrapperExt, + ApiError, + XmlExtraPostResponse, + XmlOtherPostResponse, + XmlOtherPutResponse, + XmlPostResponse, + XmlPutResponse + }; +use clap::{App, Arg}; + +fn main() { + let matches = App::new("client") + .arg(Arg::with_name("operation") + .help("Sets the operation to run") + .possible_values(&[ + "XmlExtraPost", + "XmlOtherPost", + "XmlOtherPut", + "XmlPost", + "XmlPut", +]) + .required(true) + .index(1)) + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .arg(Arg::with_name("host") + .long("host") + .takes_value(true) + .default_value("localhost") + .help("Hostname to contact")) + .arg(Arg::with_name("port") + .long("port") + .takes_value(true) + .default_value("80") + .help("Port to contact")) + .get_matches(); + + let mut core = reactor::Core::new().unwrap(); + let is_https = matches.is_present("https"); + let base_url = format!("{}://{}:{}", + if is_https { "https" } else { "http" }, + matches.value_of("host").unwrap(), + matches.value_of("port").unwrap()); + let client = if matches.is_present("https") { + // Using Simple HTTPS + openapi_v3::Client::try_new_https(core.handle(), &base_url, "examples/ca.pem") + .expect("Failed to create HTTPS client") + } else { + // Using HTTP + openapi_v3::Client::try_new_http(core.handle(), &base_url) + .expect("Failed to create HTTP client") + }; + + let context: make_context_ty!(ContextBuilder, EmptyContext, Option, XSpanIdString) = + make_context!(ContextBuilder, EmptyContext, None as Option, XSpanIdString(self::uuid::Uuid::new_v4().to_string())); + let client = client.with_context(context); + + match matches.value_of("operation") { + + Some("XmlExtraPost") => { + let result = core.run(client.xml_extra_post(None)); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, + + Some("XmlOtherPost") => { + let result = core.run(client.xml_other_post(None)); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, + + Some("XmlOtherPut") => { + let result = core.run(client.xml_other_put(None)); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, + + Some("XmlPost") => { + let result = core.run(client.xml_post(None)); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, + + Some("XmlPut") => { + let result = core.run(client.xml_put(None)); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, + + _ => { + panic!("Invalid operation provided") + } + } +} + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem new file mode 100644 index 000000000000..47d7e2014046 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem @@ -0,0 +1,66 @@ +Certificate: + Data: + Version: 1 (0x0) + Serial Number: 4096 (0x1000) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=US, CN=My CA + Validity + Not Before: May 23 16:00:23 2017 GMT + Not After : Apr 29 16:00:23 2117 GMT + Subject: CN=localhost, C=US + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c9:d4:43:60:50:fc:d6:0f:38:4d:5d:5e:aa:7c: + c0:5e:a9:ec:d9:93:78:d3:93:72:28:41:f5:08:a5: + ea:ac:67:07:d7:1f:f7:7d:74:69:7e:46:89:20:4b: + 7a:2d:9b:02:08:e7:6f:0f:1d:0c:0f:c7:60:69:19: + 4b:df:7e:ca:75:94:0b:49:71:e3:6d:f2:e8:79:fd: + ed:0a:94:67:55:f3:ca:6b:61:ba:58:b7:2e:dd:7b: + ca:b9:02:9f:24:36:ac:26:8f:04:8f:81:c8:35:10: + f4:aa:33:b2:24:16:f8:f7:1e:ea:f7:16:fe:fa:34: + c3:dd:bb:2c:ba:7a:df:4d:e2:da:1e:e5:d2:28:44: + 6e:c8:96:e0:fd:09:0c:14:0c:31:dc:e0:ca:c1:a7: + 9b:bf:16:8c:f7:36:3f:1b:2e:dd:90:eb:45:78:51: + bf:59:22:1e:c6:8c:0a:69:88:e5:03:5e:73:b7:fc: + 93:7f:1b:46:1b:97:68:c5:c0:8b:35:1f:bb:1e:67: + 7f:55:b7:3b:55:3f:ea:f2:ca:db:cc:52:cd:16:89: + db:15:47:bd:f2:cd:6c:7a:d7:b4:1a:ac:c8:15:6c: + 6a:fb:77:c4:e9:f2:30:e0:14:24:66:65:6f:2a:e5: + 2d:cc:f6:81:ae:57:c8:d1:9b:38:90:dc:60:93:02: + 5e:cb + Exponent: 65537 (0x10001) + Signature Algorithm: sha256WithRSAEncryption + 1c:7c:39:e8:3d:49:b2:09:1e:68:5a:2f:74:18:f4:63:b5:8c: + f6:e6:a1:e3:4d:95:90:99:ef:32:5c:34:40:e8:55:13:0e:e0: + 1c:be:cd:ab:3f:64:38:99:5e:2b:c1:81:53:a0:18:a8:f6:ee: + 6a:33:73:6c:9a:73:9d:86:08:5d:c7:11:38:46:4c:cd:a0:47: + 37:8f:fe:a6:50:a9:02:21:99:42:86:5e:47:fe:65:56:60:1d: + 16:53:86:bd:e4:63:c5:69:cf:fa:30:51:ab:a1:c3:50:53:cc: + 66:1c:4c:ff:3f:2a:39:4d:a2:8f:9d:d1:a7:8b:22:e4:78:69: + 24:06:83:4d:cc:0a:c0:87:69:9b:bc:80:a9:d2:b7:a5:23:84: + 7e:a2:32:26:7c:78:0e:bd:db:cd:3b:69:18:33:b8:44:ef:96: + b4:99:86:ee:06:bd:51:1c:c7:a1:a4:0c:c4:4c:51:a0:df:ac: + 14:07:88:8e:d7:39:45:fe:52:e0:a3:4c:db:5d:7a:ab:4d:e4: + ca:06:e8:bd:74:6f:46:e7:93:4a:4f:1b:67:e7:a5:9f:ef:9c: + 02:49:d1:f2:d5:e9:53:ee:09:21:ac:08:c8:15:f7:af:35:b9: + 4f:11:0f:43:ae:46:8e:fd:5b:8d:a3:4e:a7:2c:b7:25:ed:e4: + e5:94:1d:e3 +-----BEGIN CERTIFICATE----- +MIICtTCCAZ0CAhAAMA0GCSqGSIb3DQEBCwUAMB0xCzAJBgNVBAYTAlVTMQ4wDAYD +VQQDEwVNeSBDQTAgFw0xNzA1MjMxNjAwMjNaGA8yMTE3MDQyOTE2MDAyM1owITES +MBAGA1UEAxMJbG9jYWxob3N0MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBAMnUQ2BQ/NYPOE1dXqp8wF6p7NmTeNOTcihB9Qil6qxn +B9cf9310aX5GiSBLei2bAgjnbw8dDA/HYGkZS99+ynWUC0lx423y6Hn97QqUZ1Xz +ymthuli3Lt17yrkCnyQ2rCaPBI+ByDUQ9KozsiQW+Pce6vcW/vo0w927LLp6303i +2h7l0ihEbsiW4P0JDBQMMdzgysGnm78WjPc2Pxsu3ZDrRXhRv1kiHsaMCmmI5QNe +c7f8k38bRhuXaMXAizUfux5nf1W3O1U/6vLK28xSzRaJ2xVHvfLNbHrXtBqsyBVs +avt3xOnyMOAUJGZlbyrlLcz2ga5XyNGbOJDcYJMCXssCAwEAATANBgkqhkiG9w0B +AQsFAAOCAQEAHHw56D1JsgkeaFovdBj0Y7WM9uah402VkJnvMlw0QOhVEw7gHL7N +qz9kOJleK8GBU6AYqPbuajNzbJpznYYIXccROEZMzaBHN4/+plCpAiGZQoZeR/5l +VmAdFlOGveRjxWnP+jBRq6HDUFPMZhxM/z8qOU2ij53Rp4si5HhpJAaDTcwKwIdp +m7yAqdK3pSOEfqIyJnx4Dr3bzTtpGDO4RO+WtJmG7ga9URzHoaQMxExRoN+sFAeI +jtc5Rf5S4KNM2116q03kygbovXRvRueTSk8bZ+eln++cAknR8tXpU+4JIawIyBX3 +rzW5TxEPQ65Gjv1bjaNOpyy3Je3k5ZQd4w== +-----END CERTIFICATE----- diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem new file mode 100644 index 000000000000..29c006829229 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJ1ENgUPzWDzhN +XV6qfMBeqezZk3jTk3IoQfUIpeqsZwfXH/d9dGl+RokgS3otmwII528PHQwPx2Bp +GUvffsp1lAtJceNt8uh5/e0KlGdV88prYbpYty7de8q5Ap8kNqwmjwSPgcg1EPSq +M7IkFvj3Hur3Fv76NMPduyy6et9N4toe5dIoRG7IluD9CQwUDDHc4MrBp5u/Foz3 +Nj8bLt2Q60V4Ub9ZIh7GjAppiOUDXnO3/JN/G0Ybl2jFwIs1H7seZ39VtztVP+ry +ytvMUs0WidsVR73yzWx617QarMgVbGr7d8Tp8jDgFCRmZW8q5S3M9oGuV8jRmziQ +3GCTAl7LAgMBAAECggEBAKEd1q9j14KWYc64s6KLthGbutyxsinMMbxbct11fdIk +6YhdF3fJ35ETg9IJDr6rWEN9ZRX+jStncNpVfFEs6ThVd3Eo/nI+EEGaaIkikR93 +X2a7fEPn7/yVHu70XdBN6L1bPDvHUeiy4W2hmRrgT90OjGm1rNRWHOm7yugOwIZu +HclzbR9Ca7EInFnotUiDQm9sw9VKHbJHqWx6OORdZrxR2ytYs0Qkq0XpGMvti2HW +7WAmKTg5QM8myXW7+/4iqb/u68wVBR2BBalShKmIf7lim9O3W2a1RjDdsvm/wNe9 +I+D+Iq825vpqkKXcrxYlpVg7hYiaQaW/MNsEb7lQRjECgYEA/RJYby0POW+/k0Jn +jO8UmJVEMiuGa8WIUu/JJWMOmzRCukjSRNQOkt7niQrZPJYE8W6clM6RJTolWf9L +IL6mIb+mRaoudUk8SHGDq7ho1iMg9GK8lhYxvKh1Q6uv8EyVSkgLknAEY0NANKC1 +zNdU5Dhven9aRX2gq9vP4XwMz2MCgYEAzCogQ7IFk+gkp3k491dOZnrGRoRCfuzo +4CJtyKFgOSd7BjmpcKkj0IPfVBjw6GjMIxfQRMTQmxAjjWevH45vG8l0Iiwz/gSp +81b5nsDEX5uv2Olcmcz5zxRFy36jOZ9ihMWinxcIlT2oDbyCdbruDKZq9ieJ9S8g +4qGx0OkwE3kCgYEA7CmAiU89U9YqqttfEq/RQoqY91CSwmO10d+ej9seuEtOsdRf +FIfnibulycdr7hP5TOxyBpO1802NqayJiWcgVYIpQf2MGTtcnCYCP+95NcvWZvj1 +EAJqK6nwtFO1fcOZ1ZXh5qfOEGujsPkAbsXLnKXlsiTCMvMHSxl3pu5Cbg0CgYBf +JjbZNctRrjv+7Qj2hPLd4dQsIxGWc7ToWENP4J2mpVa5hQAJqFovoHXhjKohtk2F +AWEn243Y5oGbMjo0e74edhmwn2cvuF64MM2vBem/ISCn98IXT6cQskMA3qkVfsl8 +VVs/x41ReGWs2TD3y0GMFbb9t1mdMfSiincDhNnKCQKBgGfeT4jKyYeCoCw4OLI1 +G75Gd0METt/IkppwODPpNwj3Rp9I5jctWZFA/3wCX/zk0HgBeou5AFNS4nQZ/X/L +L9axbSdR7UJTGkT1r4gu3rLkPV4Tk+8XM03/JT2cofMlzQBuhvl1Pn4SgKowz7hl +lS76ECw4Av3T0S34VW9Z5oye +-----END PRIVATE KEY----- diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs new file mode 100644 index 000000000000..a13062a00f43 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs @@ -0,0 +1,75 @@ +//! Main binary entry point for openapi_v3 implementation. + +#![allow(missing_docs)] + +// Imports required by this file. +// extern crate ; +extern crate openapi_v3; +extern crate swagger; +extern crate hyper; +extern crate openssl; +extern crate native_tls; +extern crate tokio_proto; +extern crate tokio_tls; +extern crate clap; + +// Imports required by server library. +// extern crate openapi_v3; +// extern crate swagger; +extern crate futures; +extern crate chrono; +#[macro_use] +extern crate error_chain; + + +use openssl::x509::X509_FILETYPE_PEM; +use openssl::ssl::{SslAcceptorBuilder, SslMethod}; +use openssl::error::ErrorStack; +use hyper::server::Http; +use tokio_proto::TcpServer; +use clap::{App, Arg}; +use swagger::auth::AllowAllAuthenticator; +use swagger::EmptyContext; + +mod server_lib; + +// Builds an SSL implementation for Simple HTTPS from some hard-coded file names +fn ssl() -> Result { + let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?; + + // Server authentication + ssl.set_private_key_file("examples/server-key.pem", X509_FILETYPE_PEM)?; + ssl.set_certificate_chain_file("examples/server-chain.pem")?; + ssl.check_private_key()?; + + Ok(ssl) +} + +/// Create custom server, wire it to the autogenerated router, +/// and pass it to the web server. +fn main() { + let matches = App::new("server") + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .get_matches(); + + let service_fn = + openapi_v3::server::context::NewAddContext::<_, EmptyContext>::new( + AllowAllAuthenticator::new( + server_lib::NewService::new(), + "cosmo" + ) + ); + + let addr = "127.0.0.1:80".parse().expect("Failed to parse bind address"); + if matches.is_present("https") { + let ssl = ssl().expect("Failed to load SSL keys"); + let builder: native_tls::TlsAcceptorBuilder = native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl); + let tls_acceptor = builder.build().expect("Failed to build TLS acceptor"); + TcpServer::new(tokio_tls::proto::Server::new(Http::new(), tls_acceptor), addr).serve(service_fn); + } else { + // Using HTTP + TcpServer::new(Http::new(), addr).serve(service_fn); + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs new file mode 100644 index 000000000000..ad8904ca16bd --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs @@ -0,0 +1,37 @@ +//! Main library entry point for openapi_v3 implementation. + +mod server; + +mod errors { + error_chain!{} +} + +pub use self::errors::*; +use std::io; +use std::clone::Clone; +use std::marker::PhantomData; +use hyper; +use openapi_v3; +use swagger::{Has, XSpanIdString}; + +pub struct NewService{ + marker: PhantomData +} + +impl NewService{ + pub fn new() -> Self { + NewService{marker:PhantomData} + } +} + +impl hyper::server::NewService for NewService where C: Has + Clone + 'static { + type Request = (hyper::Request, C); + type Response = hyper::Response; + type Error = hyper::Error; + type Instance = openapi_v3::server::Service, C>; + + /// Instantiate a new server. + fn new_service(&self) -> io::Result { + Ok(openapi_v3::server::Service::new(server::Server::new())) + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs new file mode 100644 index 000000000000..1a2c6ff38219 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs @@ -0,0 +1,70 @@ +//! Server implementation of openapi_v3. + +#![allow(unused_imports)] + +use futures::{self, Future}; +use chrono; +use std::collections::HashMap; +use std::marker::PhantomData; + +use swagger; +use swagger::{Has, XSpanIdString}; + +use openapi_v3::{Api, ApiError, + XmlExtraPostResponse, + XmlOtherPostResponse, + XmlOtherPutResponse, + XmlPostResponse, + XmlPutResponse +}; +use openapi_v3::models; + +#[derive(Copy, Clone)] +pub struct Server { + marker: PhantomData, +} + +impl Server { + pub fn new() -> Self { + Server{marker: PhantomData} + } +} + +impl Api for Server where C: Has{ + + + fn xml_extra_post(&self, duplicate_xml_object: Option, context: &C) -> Box> { + let context = context.clone(); + println!("xml_extra_post({:?}) - X-Span-ID: {:?}", duplicate_xml_object, context.get().0.clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn xml_other_post(&self, another_xml_object: Option, context: &C) -> Box> { + let context = context.clone(); + println!("xml_other_post({:?}) - X-Span-ID: {:?}", another_xml_object, context.get().0.clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn xml_other_put(&self, string: Option, context: &C) -> Box> { + let context = context.clone(); + println!("xml_other_put({:?}) - X-Span-ID: {:?}", string, context.get().0.clone()); + Box::new(futures::failed("Generic failure".into())) + } + + /// Post an array + fn xml_post(&self, string: Option, context: &C) -> Box> { + let context = context.clone(); + println!("xml_post({:?}) - X-Span-ID: {:?}", string, context.get().0.clone()); + Box::new(futures::failed("Generic failure".into())) + } + + + fn xml_put(&self, xml_object: Option, context: &C) -> Box> { + let context = context.clone(); + println!("xml_put({:?}) - X-Span-ID: {:?}", xml_object, context.get().0.clone()); + Box::new(futures::failed("Generic failure".into())) + } + +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs new file mode 100644 index 000000000000..dd266e898f9d --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs @@ -0,0 +1,642 @@ +#![allow(unused_extern_crates)] +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +extern crate chrono; +extern crate url; + + + +use hyper; +use hyper::header::{Headers, ContentType}; +use hyper::Uri; +use self::url::percent_encoding::{utf8_percent_encode, PATH_SEGMENT_ENCODE_SET, QUERY_ENCODE_SET}; +use futures; +use futures::{Future, Stream}; +use futures::{future, stream}; +use self::tokio_core::reactor::Handle; +use std::borrow::Cow; +use std::io::{Read, Error, ErrorKind}; +use std::error; +use std::fmt; +use std::path::Path; +use std::sync::Arc; +use std::str; +use std::str::FromStr; +use std::string::ToString; + +use mimetypes; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData}; + +use {Api, + XmlExtraPostResponse, + XmlOtherPostResponse, + XmlOtherPutResponse, + XmlPostResponse, + XmlPutResponse + }; +use models; + +define_encode_set! { + /// This encode set is used for object IDs + /// + /// Aside from the special characters defined in the `PATH_SEGMENT_ENCODE_SET`, + /// the vertical bar (|) is encoded. + pub ID_ENCODE_SET = [PATH_SEGMENT_ENCODE_SET] | {'|'} +} + +/// Convert input into a base path, e.g. "http://example:123". Also checks the scheme as it goes. +fn into_base_path(input: &str, correct_scheme: Option<&'static str>) -> Result { + // First convert to Uri, since a base path is a subset of Uri. + let uri = Uri::from_str(input)?; + + let scheme = uri.scheme().ok_or(ClientInitError::InvalidScheme)?; + + // Check the scheme if necessary + if let Some(correct_scheme) = correct_scheme { + if scheme != correct_scheme { + return Err(ClientInitError::InvalidScheme); + } + } + + let host = uri.host().ok_or_else(|| ClientInitError::MissingHost)?; + let port = uri.port().map(|x| format!(":{}", x)).unwrap_or_default(); + Ok(format!("{}://{}{}", scheme, host, port)) +} + +/// A client that implements the API by making HTTP calls out to a server. +pub struct Client where + F: Future + 'static { + client_service: Arc, Response=hyper::Response, Error=hyper::Error, Future=F>>>, + base_path: String, +} + +impl fmt::Debug for Client where + F: Future + 'static { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "Client {{ base_path: {} }}", self.base_path) + } +} + +impl Clone for Client where + F: Future + 'static { + fn clone(&self) -> Self { + Client { + client_service: self.client_service.clone(), + base_path: self.base_path.clone() + } + } +} + +impl Client { + + /// Create an HTTP client. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + pub fn try_new_http(handle: Handle, base_path: &str) -> Result, ClientInitError> { + let http_connector = swagger::http_connector(); + Self::try_new_with_connector::( + handle, + base_path, + Some("http"), + http_connector, + ) + } + + /// Create a client with a TLS connection to the server. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `ca_certificate` - Path to CA certificate used to authenticate the server + pub fn try_new_https( + handle: Handle, + base_path: &str, + ca_certificate: CA, + ) -> Result, ClientInitError> + where + CA: AsRef, + { + let https_connector = swagger::https_connector(ca_certificate); + Self::try_new_with_connector::>( + handle, + base_path, + Some("https"), + https_connector, + ) + } + + /// Create a client with a mutually authenticated TLS connection to the server. + /// + /// # Arguments + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `ca_certificate` - Path to CA certificate used to authenticate the server + /// * `client_key` - Path to the client private key + /// * `client_certificate` - Path to the client's public certificate associated with the private key + pub fn try_new_https_mutual( + handle: Handle, + base_path: &str, + ca_certificate: CA, + client_key: K, + client_certificate: C, + ) -> Result, ClientInitError> + where + CA: AsRef, + K: AsRef, + C: AsRef, + { + let https_connector = + swagger::https_mutual_connector(ca_certificate, client_key, client_certificate); + Self::try_new_with_connector::>( + handle, + base_path, + Some("https"), + https_connector, + ) + } + + /// Create a client with a custom implementation of hyper::client::Connect. + /// + /// Intended for use with custom implementations of connect for e.g. protocol logging + /// or similar functionality which requires wrapping the transport layer. When wrapping a TCP connection, + /// this function should be used in conjunction with + /// `swagger::{http_connector, https_connector, https_mutual_connector}`. + /// + /// For ordinary tcp connections, prefer the use of `try_new_http`, `try_new_https` + /// and `try_new_https_mutual`, to avoid introducing a dependency on the underlying transport layer. + /// + /// # Arguments + /// + /// * `handle` - tokio reactor handle to use for execution + /// * `base_path` - base path of the client API, i.e. "www.my-api-implementation.com" + /// * `protocol` - Which protocol to use when constructing the request url, e.g. `Some("http")` + /// * `connector_fn` - Function which returns an implementation of `hyper::client::Connect` + pub fn try_new_with_connector( + handle: Handle, + base_path: &str, + protocol: Option<&'static str>, + connector_fn: Box C + Send + Sync>, + ) -> Result, ClientInitError> + where + C: hyper::client::Connect + hyper::client::Service, + { + let connector = connector_fn(&handle); + let client_service = Box::new(hyper::Client::configure().connector(connector).build( + &handle, + )); + + Ok(Client { + client_service: Arc::new(client_service), + base_path: into_base_path(base_path, protocol)?, + }) + } + + /// Constructor for creating a `Client` by passing in a pre-made `hyper` client. + /// + /// One should avoid relying on this function if possible, since it adds a dependency on the underlying transport + /// implementation, which it would be better to abstract away. Therefore, using this function may lead to a loss of + /// code generality, which may make it harder to move the application to a serverless environment, for example. + /// + /// The reason for this function's existence is to support legacy test code, which did mocking at the hyper layer. + /// This is not a recommended way to write new tests. If other reasons are found for using this function, they + /// should be mentioned here. + #[deprecated(note="Use try_new_with_client_service instead")] + pub fn try_new_with_hyper_client( + hyper_client: Arc, Response=hyper::Response, Error=hyper::Error, Future=hyper::client::FutureResponse>>>, + handle: Handle, + base_path: &str + ) -> Result, ClientInitError> + { + Ok(Client { + client_service: hyper_client, + base_path: into_base_path(base_path, None)?, + }) + } +} + +impl Client where + F: Future + 'static +{ + /// Constructor for creating a `Client` by passing in a pre-made `hyper` client Service. + /// + /// This allows adding custom wrappers around the underlying transport, for example for logging. + pub fn try_new_with_client_service(client_service: Arc, Response=hyper::Response, Error=hyper::Error, Future=F>>>, + handle: Handle, + base_path: &str) + -> Result, ClientInitError> + { + Ok(Client { + client_service: client_service, + base_path: into_base_path(base_path, None)?, + }) + } +} + +impl Api for Client where + F: Future + 'static, + C: Has { + + fn xml_extra_post(&self, param_duplicate_xml_object: Option, context: &C) -> Box> { + let mut uri = format!( + "{}/xml_extra", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + + // Body parameter + let body = param_duplicate_xml_object.map(|ref body| { + body.to_xml() + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::XML_EXTRA_POST.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + + + Box::new(self.client_service.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 201 => { + let body = response.body(); + Box::new( + + future::ok( + XmlExtraPostResponse::OK + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + XmlExtraPostResponse::BadRequest + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn xml_other_post(&self, param_another_xml_object: Option, context: &C) -> Box> { + let mut uri = format!( + "{}/xml_other", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let body = param_another_xml_object.map(|ref body| { + body.to_xml() + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::XML_OTHER_POST.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + + + Box::new(self.client_service.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 201 => { + let body = response.body(); + Box::new( + + future::ok( + XmlOtherPostResponse::OK + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + XmlOtherPostResponse::BadRequest + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn xml_other_put(&self, param_string: Option, context: &C) -> Box> { + let mut uri = format!( + "{}/xml_other", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Put, uri); + + let body = param_string.map(|ref body| { + body.to_xml() + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::XML_OTHER_PUT.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + + + Box::new(self.client_service.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 201 => { + let body = response.body(); + Box::new( + + future::ok( + XmlOtherPutResponse::OK + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + XmlOtherPutResponse::BadRequest + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn xml_post(&self, param_string: Option, context: &C) -> Box> { + let mut uri = format!( + "{}/xml", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Post, uri); + + let body = param_string.map(|ref body| { + body.to_xml() + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::XML_POST.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + + + Box::new(self.client_service.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 201 => { + let body = response.body(); + Box::new( + + future::ok( + XmlPostResponse::OK + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + XmlPostResponse::BadRequest + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + + fn xml_put(&self, param_xml_object: Option, context: &C) -> Box> { + let mut uri = format!( + "{}/xml", + self.base_path + ); + + let uri = match Uri::from_str(&uri) { + Ok(uri) => uri, + Err(err) => return Box::new(futures::done(Err(ApiError(format!("Unable to build URI: {}", err))))), + }; + + let mut request = hyper::Request::new(hyper::Method::Put, uri); + + let body = param_xml_object.map(|ref body| { + body.to_xml() + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::XML_PUT.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + + + Box::new(self.client_service.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 201 => { + let body = response.body(); + Box::new( + + future::ok( + XmlPutResponse::OK + ) + ) as Box> + }, + 400 => { + let body = response.body(); + Box::new( + + future::ok( + XmlPutResponse::BadRequest + ) + ) as Box> + }, + code => { + let headers = response.headers().clone(); + Box::new(response.body() + .take(100) + .concat2() + .then(move |body| + future::err(ApiError(format!("Unexpected response code {}:\n{:?}\n\n{}", + code, + headers, + match body { + Ok(ref body) => match str::from_utf8(body) { + Ok(body) => Cow::from(body), + Err(e) => Cow::from(format!("", e)), + }, + Err(e) => Cow::from(format!("", e)), + }))) + ) + ) as Box> + } + } + })) + + } + +} + +#[derive(Debug)] +pub enum ClientInitError { + InvalidScheme, + InvalidUri(hyper::error::UriError), + MissingHost, + SslError(openssl::error::ErrorStack) +} + +impl From for ClientInitError { + fn from(err: hyper::error::UriError) -> ClientInitError { + ClientInitError::InvalidUri(err) + } +} + +impl From for ClientInitError { + fn from(err: openssl::error::ErrorStack) -> ClientInitError { + ClientInitError::SslError(err) + } +} + +impl fmt::Display for ClientInitError { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + (self as &fmt::Debug).fmt(f) + } +} + +impl error::Error for ClientInitError { + fn description(&self) -> &str { + "Failed to produce a hyper client." + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs new file mode 100644 index 000000000000..88ecd9b8b448 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -0,0 +1,178 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +extern crate serde; +#[macro_use] +extern crate serde_derive; +extern crate serde_json; + +extern crate serde_xml_rs; +extern crate futures; +extern crate chrono; +#[macro_use] +extern crate lazy_static; +#[macro_use] +extern crate log; + +// Logically this should be in the client and server modules, but rust doesn't allow `macro_use` from a module. +#[cfg(any(feature = "client", feature = "server"))] +#[macro_use] +extern crate hyper; + +extern crate swagger; + +#[macro_use] +extern crate url; + +use futures::Stream; +use std::io::Error; + +#[allow(unused_imports)] +use std::collections::HashMap; + +pub use futures::Future; + +#[cfg(any(feature = "client", feature = "server"))] +mod mimetypes; + +pub use swagger::{ApiError, ContextWrapper}; + +pub const BASE_PATH: &'static str = ""; +pub const API_VERSION: &'static str = "1.0.7"; + + +#[derive(Debug, PartialEq)] +pub enum XmlExtraPostResponse { + /// OK + OK , + /// Bad Request + BadRequest , +} + +#[derive(Debug, PartialEq)] +pub enum XmlOtherPostResponse { + /// OK + OK , + /// Bad Request + BadRequest , +} + +#[derive(Debug, PartialEq)] +pub enum XmlOtherPutResponse { + /// OK + OK , + /// Bad Request + BadRequest , +} + +#[derive(Debug, PartialEq)] +pub enum XmlPostResponse { + /// OK + OK , + /// Bad Request + BadRequest , +} + +#[derive(Debug, PartialEq)] +pub enum XmlPutResponse { + /// OK + OK , + /// Bad Request + BadRequest , +} + + +/// API +pub trait Api { + + + fn xml_extra_post(&self, duplicate_xml_object: Option, context: &C) -> Box>; + + + fn xml_other_post(&self, another_xml_object: Option, context: &C) -> Box>; + + + fn xml_other_put(&self, string: Option, context: &C) -> Box>; + + /// Post an array + fn xml_post(&self, string: Option, context: &C) -> Box>; + + + fn xml_put(&self, xml_object: Option, context: &C) -> Box>; + +} + +/// API without a `Context` +pub trait ApiNoContext { + + + fn xml_extra_post(&self, duplicate_xml_object: Option) -> Box>; + + + fn xml_other_post(&self, another_xml_object: Option) -> Box>; + + + fn xml_other_put(&self, string: Option) -> Box>; + + /// Post an array + fn xml_post(&self, string: Option) -> Box>; + + + fn xml_put(&self, xml_object: Option) -> Box>; + +} + +/// Trait to extend an API to make it easy to bind it to a context. +pub trait ContextWrapperExt<'a, C> where Self: Sized { + /// Binds this API to a context. + fn with_context(self: &'a Self, context: C) -> ContextWrapper<'a, Self, C>; +} + +impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { + fn with_context(self: &'a T, context: C) -> ContextWrapper<'a, T, C> { + ContextWrapper::::new(self, context) + } +} + +impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { + + + fn xml_extra_post(&self, duplicate_xml_object: Option) -> Box> { + self.api().xml_extra_post(duplicate_xml_object, &self.context()) + } + + + fn xml_other_post(&self, another_xml_object: Option) -> Box> { + self.api().xml_other_post(another_xml_object, &self.context()) + } + + + fn xml_other_put(&self, string: Option) -> Box> { + self.api().xml_other_put(string, &self.context()) + } + + /// Post an array + fn xml_post(&self, string: Option) -> Box> { + self.api().xml_post(string, &self.context()) + } + + + fn xml_put(&self, xml_object: Option) -> Box> { + self.api().xml_put(xml_object, &self.context()) + } + +} + +#[cfg(feature = "client")] +pub mod client; + +// Re-export Client as a top-level name +#[cfg(feature = "client")] +pub use self::client::Client; + +#[cfg(feature = "server")] +pub mod server; + +// Re-export router() as a top-level name +#[cfg(feature = "server")] +pub use self::server::Service; + +pub mod models; diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs new file mode 100644 index 000000000000..92a7cd5812e5 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs @@ -0,0 +1,33 @@ +/// mime types for requests and responses + +pub mod responses { + use hyper::mime::*; + + // The macro is called per-operation to beat the recursion limit + +} + +pub mod requests { + use hyper::mime::*; + /// Create Mime objects for the request content types for XmlExtraPost + lazy_static! { + pub static ref XML_EXTRA_POST: Mime = "application/xml".parse().unwrap(); + } + /// Create Mime objects for the request content types for XmlOtherPost + lazy_static! { + pub static ref XML_OTHER_POST: Mime = "application/xml".parse().unwrap(); + } + /// Create Mime objects for the request content types for XmlOtherPut + lazy_static! { + pub static ref XML_OTHER_PUT: Mime = "application/xml".parse().unwrap(); + } + /// Create Mime objects for the request content types for XmlPost + lazy_static! { + pub static ref XML_POST: Mime = "application/xml".parse().unwrap(); + } + /// Create Mime objects for the request content types for XmlPut + lazy_static! { + pub static ref XML_PUT: Mime = "application/xml".parse().unwrap(); + } + +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs new file mode 100644 index 000000000000..37c6e48a860e --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -0,0 +1,364 @@ +#![allow(unused_imports, unused_qualifications, unused_extern_crates)] +extern crate chrono; +extern crate uuid; + +use serde_xml_rs; +use serde::ser::Serializer; + +use std::collections::{HashMap, BTreeMap}; +use models; +use swagger; + + +// Utility function for wrapping list elements when serializing xml +fn wrap_another_xml_array_in_xml_name(item: &Vec, serializer: S) -> Result +where + S: Serializer, +{ + serde_xml_rs::wrap_primitives(item, serializer, "snake_another_xml_inner") +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AnotherXmlArray(#[serde(serialize_with = "wrap_another_xml_array_in_xml_name")]Vec); + +impl ::std::convert::From> for AnotherXmlArray { + fn from(x: Vec) -> Self { + AnotherXmlArray(x) + } +} + +impl ::std::convert::From for Vec { + fn from(x: AnotherXmlArray) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator for AnotherXmlArray { + fn from_iter>(u: U) -> Self { + AnotherXmlArray(Vec::::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for AnotherXmlArray { + type Item = String; + type IntoIter = ::std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a AnotherXmlArray { + type Item = &'a String; + type IntoIter = ::std::slice::Iter<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a mut AnotherXmlArray { + type Item = &'a mut String; + type IntoIter = ::std::slice::IterMut<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + (&mut self.0).into_iter() + } +} + +impl ::std::ops::Deref for AnotherXmlArray { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for AnotherXmlArray { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + + +impl AnotherXmlArray { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] +#[serde(rename = "snake_another_xml_inner")] +pub struct AnotherXmlInner(String); + +impl ::std::convert::From for AnotherXmlInner { + fn from(x: String) -> Self { + AnotherXmlInner(x) + } +} + +impl ::std::convert::From for String { + fn from(x: AnotherXmlInner) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for AnotherXmlInner { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl ::std::ops::DerefMut for AnotherXmlInner { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + +impl AnotherXmlInner { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +/// An XML object +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "snake_another_xml_object")] +pub struct AnotherXmlObject { + #[serde(rename = "inner_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner_string: Option, + +} + +impl AnotherXmlObject { + pub fn new() -> AnotherXmlObject { + AnotherXmlObject { + inner_string: None, + } + } +} + +impl AnotherXmlObject { + /// Associated constant for this model's XML namespace. + #[allow(dead_code)] + pub const NAMESPACE: &'static str = "http://foo.bar"; +} + +impl AnotherXmlObject { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); + serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + } +} + +/// An XML object +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "camelDuplicateXmlObject")] +pub struct DuplicateXmlObject { + #[serde(rename = "inner_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner_string: Option, + + #[serde(rename = "inner_array")] + pub inner_array: Vec, + +} + +impl DuplicateXmlObject { + pub fn new(inner_array: Vec, ) -> DuplicateXmlObject { + DuplicateXmlObject { + inner_string: None, + inner_array: inner_array, + } + } +} + +impl DuplicateXmlObject { + /// Associated constant for this model's XML namespace. + #[allow(dead_code)] + pub const NAMESPACE: &'static str = "http://different.bar"; +} + +impl DuplicateXmlObject { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); + serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + } +} + +// Utility function for wrapping list elements when serializing xml +fn wrap_xml_array_in_xml_name(item: &Vec, serializer: S) -> Result +where + S: Serializer, +{ + serde_xml_rs::wrap_primitives(item, serializer, "camelXmlInner") +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct XmlArray(#[serde(serialize_with = "wrap_xml_array_in_xml_name")]Vec); + +impl ::std::convert::From> for XmlArray { + fn from(x: Vec) -> Self { + XmlArray(x) + } +} + +impl ::std::convert::From for Vec { + fn from(x: XmlArray) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator for XmlArray { + fn from_iter>(u: U) -> Self { + XmlArray(Vec::::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for XmlArray { + type Item = String; + type IntoIter = ::std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a XmlArray { + type Item = &'a String; + type IntoIter = ::std::slice::Iter<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a mut XmlArray { + type Item = &'a mut String; + type IntoIter = ::std::slice::IterMut<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + (&mut self.0).into_iter() + } +} + +impl ::std::ops::Deref for XmlArray { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for XmlArray { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + + +impl XmlArray { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] +#[serde(rename = "camelXmlInner")] +pub struct XmlInner(String); + +impl ::std::convert::From for XmlInner { + fn from(x: String) -> Self { + XmlInner(x) + } +} + +impl ::std::convert::From for String { + fn from(x: XmlInner) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for XmlInner { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl ::std::ops::DerefMut for XmlInner { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + +impl XmlInner { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +/// An XML object +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "camelXmlObject")] +pub struct XmlObject { + #[serde(rename = "innerString")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner_string: Option, + + #[serde(rename = "other_inner_rename")] + #[serde(skip_serializing_if="Option::is_none")] + pub other_inner_rename: Option, + +} + +impl XmlObject { + pub fn new() -> XmlObject { + XmlObject { + inner_string: None, + other_inner_rename: None, + } + } +} + +impl XmlObject { + /// Associated constant for this model's XML namespace. + #[allow(dead_code)] + pub const NAMESPACE: &'static str = "http://foo.bar"; +} + +impl XmlObject { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), Self::NAMESPACE.to_string()); + serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/context.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/context.rs new file mode 100644 index 000000000000..6f2900b3d70c --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/context.rs @@ -0,0 +1,91 @@ +use std::io; +use std::marker::PhantomData; +use std::default::Default; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use server::url::form_urlencoded; +use swagger::auth::{Authorization, AuthData, Scopes}; +use swagger::{Has, Pop, Push, XSpanIdString}; +use Api; + +pub struct NewAddContext +{ + inner: T, + marker: PhantomData, +} + +impl NewAddContext + where + A: Default + Push, + B: Push, Result=C>, + C: Push, Result=D>, + T: hyper::server::NewService + 'static, +{ + pub fn new(inner: T) -> NewAddContext { + NewAddContext { + inner, + marker: PhantomData, + } + } +} + +impl hyper::server::NewService for NewAddContext + where + A: Default + Push, + B: Push, Result=C>, + C: Push, Result=D>, + T: hyper::server::NewService + 'static, +{ + type Request = Request; + type Response = Response; + type Error = Error; + type Instance = AddContext; + + fn new_service(&self) -> Result { + self.inner.new_service().map(|s| AddContext::new(s)) + } +} + +/// Middleware to extract authentication data from request +pub struct AddContext +{ + inner: T, + marker: PhantomData, +} + +impl AddContext + where + A: Default + Push, + B: Push, Result=C>, + C: Push, Result=D>, + T: hyper::server::Service, +{ + pub fn new(inner: T) -> AddContext { + AddContext { + inner, + marker: PhantomData, + } + } +} + +impl hyper::server::Service for AddContext + where + A: Default + Push, + B: Push, Result=C>, + C: Push, Result=D>, + T: hyper::server::Service, +{ + type Request = Request; + type Response = Response; + type Error = Error; + type Future = T::Future; + + fn call(&self, req: Self::Request) -> Self::Future { + let context = A::default().push(XSpanIdString::get_or_generate(&req)); + + + let context = context.push(None::); + let context = context.push(None::); + return self.inner.call((req, context)); + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs new file mode 100644 index 000000000000..f86af16049bc --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -0,0 +1,580 @@ +#![allow(unused_extern_crates)] +extern crate serde_ignored; +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +extern crate uuid; +extern crate chrono; +extern crate percent_encoding; +extern crate url; + + +use std::sync::Arc; +use std::marker::PhantomData; +use futures::{Future, future, Stream, stream}; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use hyper::header::{Headers, ContentType}; +use self::url::form_urlencoded; +use mimetypes; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; +use std::io; + +#[allow(unused_imports)] +use std::collections::BTreeSet; + +pub use swagger::auth::Authorization; +use swagger::{ApiError, XSpanId, XSpanIdString, Has, RequestParser}; +use swagger::auth::Scopes; + +use {Api, + XmlExtraPostResponse, + XmlOtherPostResponse, + XmlOtherPutResponse, + XmlPostResponse, + XmlPutResponse + }; +#[allow(unused_imports)] +use models; + +pub mod context; + +header! { (Warning, "Warning") => [String] } + +mod paths { + extern crate regex; + + lazy_static! { + pub static ref GLOBAL_REGEX_SET: regex::RegexSet = regex::RegexSet::new(&[ + r"^/xml$", + r"^/xml_extra$", + r"^/xml_other$" + ]).unwrap(); + } + pub static ID_XML: usize = 0; + pub static ID_XML_EXTRA: usize = 1; + pub static ID_XML_OTHER: usize = 2; +} + +pub struct NewService { + api_impl: Arc, + marker: PhantomData, +} + +impl NewService +where + T: Api + Clone + 'static, + C: Has + 'static +{ + pub fn new>>(api_impl: U) -> NewService { + NewService{api_impl: api_impl.into(), marker: PhantomData} + } +} + +impl hyper::server::NewService for NewService +where + T: Api + Clone + 'static, + C: Has + 'static +{ + type Request = (Request, C); + type Response = Response; + type Error = Error; + type Instance = Service; + + fn new_service(&self) -> Result { + Ok(Service::new(self.api_impl.clone())) + } +} + +pub struct Service { + api_impl: Arc, + marker: PhantomData, +} + +impl Service +where + T: Api + Clone + 'static, + C: Has + 'static { + pub fn new>>(api_impl: U) -> Service { + Service{api_impl: api_impl.into(), marker: PhantomData} + } +} + +impl hyper::server::Service for Service +where + T: Api + Clone + 'static, + C: Has + 'static +{ + type Request = (Request, C); + type Response = Response; + type Error = Error; + type Future = Box>; + + fn call(&self, (req, mut context): Self::Request) -> Self::Future { + let api_impl = self.api_impl.clone(); + let (method, uri, _, headers, body) = req.deconstruct(); + let path = paths::GLOBAL_REGEX_SET.matches(uri.path()); + + // This match statement is duplicated below in `parse_operation_id()`. + // Please update both places if changing how this code is autogenerated. + match &method { + + // XmlExtraPost - POST /xml_extra + &hyper::Method::Post if path.matched(paths::ID_XML_EXTRA) => { + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_duplicate_xml_object: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_duplicate_xml_object) => param_duplicate_xml_object, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.xml_extra_post(param_duplicate_xml_object, &context) + .then(move |result| { + let mut response = Response::new(); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + XmlExtraPostResponse::OK + + + => { + response.set_status(StatusCode::try_from(201).unwrap()); + + }, + XmlExtraPostResponse::BadRequest + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter DuplicateXmlObject: {}", e)))), + } + }) + ) as Box> + + }, + + + // XmlOtherPost - POST /xml_other + &hyper::Method::Post if path.matched(paths::ID_XML_OTHER) => { + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_another_xml_object: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_another_xml_object) => param_another_xml_object, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.xml_other_post(param_another_xml_object, &context) + .then(move |result| { + let mut response = Response::new(); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + XmlOtherPostResponse::OK + + + => { + response.set_status(StatusCode::try_from(201).unwrap()); + + }, + XmlOtherPostResponse::BadRequest + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter AnotherXmlObject: {}", e)))), + } + }) + ) as Box> + + }, + + + // XmlOtherPut - PUT /xml_other + &hyper::Method::Put if path.matched(paths::ID_XML_OTHER) => { + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_string: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_string) => param_string, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.xml_other_put(param_string, &context) + .then(move |result| { + let mut response = Response::new(); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + XmlOtherPutResponse::OK + + + => { + response.set_status(StatusCode::try_from(201).unwrap()); + + }, + XmlOtherPutResponse::BadRequest + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter string: {}", e)))), + } + }) + ) as Box> + + }, + + + // XmlPost - POST /xml + &hyper::Method::Post if path.matched(paths::ID_XML) => { + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_string: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_string) => param_string, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.xml_post(param_string, &context) + .then(move |result| { + let mut response = Response::new(); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + XmlPostResponse::OK + + + => { + response.set_status(StatusCode::try_from(201).unwrap()); + + }, + XmlPostResponse::BadRequest + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter string: {}", e)))), + } + }) + ) as Box> + + }, + + + // XmlPut - PUT /xml + &hyper::Method::Put if path.matched(paths::ID_XML) => { + + + + + + + // Body parameters (note that non-required body parameters will ignore garbage + // values, rather than causing a 400 response). Produce warning header and logs for + // any unused fields. + Box::new(body.concat2() + .then(move |result| -> Box> { + match result { + Ok(body) => { + + let mut unused_elements = Vec::new(); + let param_xml_object: Option = if !body.is_empty() { + let deserializer = &mut serde_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_xml_object) => param_xml_object, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.xml_put(param_xml_object, &context) + .then(move |result| { + let mut response = Response::new(); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + XmlPutResponse::OK + + + => { + response.set_status(StatusCode::try_from(201).unwrap()); + + }, + XmlPutResponse::BadRequest + + + => { + response.set_status(StatusCode::try_from(400).unwrap()); + + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.set_status(StatusCode::InternalServerError); + response.set_body("An internal error occurred"); + }, + } + + future::ok(response) + } + )) + + + }, + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter XmlObject: {}", e)))), + } + }) + ) as Box> + + }, + + + _ => Box::new(future::ok(Response::new().with_status(StatusCode::NotFound))) as Box>, + } + } +} + +impl Clone for Service +{ + fn clone(&self) -> Self { + Service { + api_impl: self.api_impl.clone(), + marker: self.marker.clone(), + } + } +} + +/// Request parser for `Api`. +pub struct ApiRequestParser; +impl RequestParser for ApiRequestParser { + fn parse_operation_id(request: &Request) -> Result<&'static str, ()> { + let path = paths::GLOBAL_REGEX_SET.matches(request.uri().path()); + match request.method() { + + // XmlExtraPost - POST /xml_extra + &hyper::Method::Post if path.matched(paths::ID_XML_EXTRA) => Ok("XmlExtraPost"), + + // XmlOtherPost - POST /xml_other + &hyper::Method::Post if path.matched(paths::ID_XML_OTHER) => Ok("XmlOtherPost"), + + // XmlOtherPut - PUT /xml_other + &hyper::Method::Put if path.matched(paths::ID_XML_OTHER) => Ok("XmlOtherPut"), + + // XmlPost - POST /xml + &hyper::Method::Post if path.matched(paths::ID_XML) => Ok("XmlPost"), + + // XmlPut - PUT /xml + &hyper::Method::Put if path.matched(paths::ID_XML) => Ok("XmlPut"), + _ => Err(()), + } + } +} diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md index 55b9c86e03b4..cf523bfaa750 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/README.md @@ -178,6 +178,7 @@ Method | HTTP request | Description - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AnimalFarm.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AnimalFarm.md new file mode 100644 index 000000000000..df6bab21dae8 --- /dev/null +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md index cdeba8866ffa..372dc14d335b 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md @@ -33,7 +33,7 @@ Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | **bool**| Input boolean as post body | + **body** | [**boolean**](boolean.md)| Input boolean as post body | ### Return type @@ -101,7 +101,7 @@ Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | **f64**| Input number as post body | + **body** | [**number**](number.md)| Input number as post body | ### Return type @@ -135,7 +135,7 @@ Optional parameters are passed through a map[string]interface{}. Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- - **body** | **String**| Input string as post body | + **body** | [**string**](string.md)| Input string as post body | ### Return type diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/client.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/client.rs index ec92f8636131..b5803ba34c39 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/client.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/client.rs @@ -128,7 +128,7 @@ fn main() { // }, Some("FakeOuterBooleanSerialize") => { - let result = core.run(client.fake_outer_boolean_serialize(Some(true))); + let result = core.run(client.fake_outer_boolean_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, @@ -138,12 +138,12 @@ fn main() { }, Some("FakeOuterNumberSerialize") => { - let result = core.run(client.fake_outer_number_serialize(Some(8.14))); + let result = core.run(client.fake_outer_number_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterStringSerialize") => { - let result = core.run(client.fake_outer_string_serialize(Some("body_example".to_string()))); + let result = core.run(client.fake_outer_string_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server_lib/server.rs index 4dc7ac8c862c..f0ee591cf95a 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server_lib/server.rs @@ -67,7 +67,7 @@ impl Api for Server where C: Has{ } - fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) @@ -81,14 +81,14 @@ impl Api for Server where C: Has{ } - fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs index 32e2db969d9e..1be563787c6e 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs @@ -292,10 +292,8 @@ impl Api for Client where // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -350,7 +348,7 @@ impl Api for Client where } - fn fake_outer_boolean_serialize(&self, param_body: Option, context: &C) -> Box> { + fn fake_outer_boolean_serialize(&self, param_body: Option, context: &C) -> Box> { let mut uri = format!( "{}/v2/fake/outer/boolean", self.base_path @@ -366,7 +364,6 @@ impl Api for Client where // Body parameter let body = param_body.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -439,7 +436,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); let body = param_body.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -498,7 +494,7 @@ if let Some(body) = body { } - fn fake_outer_number_serialize(&self, param_body: Option, context: &C) -> Box> { + fn fake_outer_number_serialize(&self, param_body: Option, context: &C) -> Box> { let mut uri = format!( "{}/v2/fake/outer/number", self.base_path @@ -512,7 +508,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); let body = param_body.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -571,7 +566,7 @@ if let Some(body) = body { } - fn fake_outer_string_serialize(&self, param_body: Option, context: &C) -> Box> { + fn fake_outer_string_serialize(&self, param_body: Option, context: &C) -> Box> { let mut uri = format!( "{}/v2/fake/outer/string", self.base_path @@ -585,7 +580,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); let body = param_body.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -667,10 +661,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -728,10 +720,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Patch, uri); - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -819,7 +809,6 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_ENDPOINT_PARAMETERS.clone())); request.set_body(body.into_bytes()); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); (context as &Has>).get().as_ref().map(|auth_data| { if let &AuthData::Basic(ref basic_header) = auth_data { @@ -916,7 +905,6 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_ENUM_PARAMETERS.clone())); request.set_body(body.into_bytes()); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); // Header parameters @@ -985,10 +973,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_param).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -1054,7 +1040,6 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::TEST_JSON_FORM_DATA.clone())); request.set_body(body.into_bytes()); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1110,10 +1095,8 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -1183,9 +1166,7 @@ if let Some(body) = body { // Body parameter - - let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); - + let body = param_body.to_xml(); request.set_body(body.into_bytes()); @@ -1245,7 +1226,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Delete, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); // Header parameters @@ -1314,7 +1294,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1400,7 +1379,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1476,7 +1454,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1560,9 +1537,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - - let body = serde_xml_rs::to_string(¶m_body).expect("impossible to fail to serialize"); - + let body = param_body.to_xml(); request.set_body(body.into_bytes()); @@ -1647,7 +1622,6 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::UPDATE_PET_WITH_FORM.clone())); request.set_body(body.into_bytes()); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1709,7 +1683,6 @@ if let Some(body) = body { request.headers_mut().set(ContentType(mimetypes::requests::UPLOAD_FILE.clone())); request.set_body(body.into_bytes()); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1774,7 +1747,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Delete, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1838,7 +1810,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1903,7 +1874,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -1987,10 +1957,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2071,10 +2039,8 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2132,10 +2098,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2193,10 +2157,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2255,7 +2217,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Delete, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -2319,7 +2280,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -2415,7 +2375,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -2501,7 +2460,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -2555,10 +2513,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs index 2f2b4878e73c..026ca6ef5de7 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs @@ -273,16 +273,16 @@ pub trait Api { fn test_special_tags(&self, body: models::Client, context: &C) -> Box>; - fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box>; + fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box>; fn fake_outer_composite_serialize(&self, body: Option, context: &C) -> Box>; - fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box>; + fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box>; - fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box>; + fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box>; fn test_body_with_query_params(&self, query: String, body: models::User, context: &C) -> Box>; @@ -374,16 +374,16 @@ pub trait ApiNoContext { fn test_special_tags(&self, body: models::Client) -> Box>; - fn fake_outer_boolean_serialize(&self, body: Option) -> Box>; + fn fake_outer_boolean_serialize(&self, body: Option) -> Box>; fn fake_outer_composite_serialize(&self, body: Option) -> Box>; - fn fake_outer_number_serialize(&self, body: Option) -> Box>; + fn fake_outer_number_serialize(&self, body: Option) -> Box>; - fn fake_outer_string_serialize(&self, body: Option) -> Box>; + fn fake_outer_string_serialize(&self, body: Option) -> Box>; fn test_body_with_query_params(&self, query: String, body: models::User) -> Box>; @@ -488,7 +488,7 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn fake_outer_boolean_serialize(&self, body: Option) -> Box> { + fn fake_outer_boolean_serialize(&self, body: Option) -> Box> { self.api().fake_outer_boolean_serialize(body, &self.context()) } @@ -498,12 +498,12 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn fake_outer_number_serialize(&self, body: Option) -> Box> { + fn fake_outer_number_serialize(&self, body: Option) -> Box> { self.api().fake_outer_number_serialize(body, &self.context()) } - fn fake_outer_string_serialize(&self, body: Option) -> Box> { + fn fake_outer_string_serialize(&self, body: Option) -> Box> { self.api().fake_outer_string_serialize(body, &self.context()) } diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index 0daa05e4dbf3..b04e3de61b16 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs @@ -5,7 +5,7 @@ extern crate uuid; use serde_xml_rs; use serde::ser::Serializer; -use std::collections::HashMap; +use std::collections::{HashMap, BTreeMap}; use models; use swagger; @@ -31,6 +31,15 @@ impl AdditionalPropertiesClass { } } +impl AdditionalPropertiesClass { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Animal { #[serde(rename = "className")] @@ -51,6 +60,86 @@ impl Animal { } } +impl Animal { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AnimalFarm(Vec); + +impl ::std::convert::From> for AnimalFarm { + fn from(x: Vec) -> Self { + AnimalFarm(x) + } +} + +impl ::std::convert::From for Vec { + fn from(x: AnimalFarm) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator for AnimalFarm { + fn from_iter>(u: U) -> Self { + AnimalFarm(Vec::::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for AnimalFarm { + type Item = Animal; + type IntoIter = ::std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a AnimalFarm { + type Item = &'a Animal; + type IntoIter = ::std::slice::Iter<'a, Animal>; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a mut AnimalFarm { + type Item = &'a mut Animal; + type IntoIter = ::std::slice::IterMut<'a, Animal>; + + fn into_iter(self) -> Self::IntoIter { + (&mut self.0).into_iter() + } +} + +impl ::std::ops::Deref for AnimalFarm { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for AnimalFarm { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + + +impl AnimalFarm { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ApiResponse { #[serde(rename = "code")] @@ -77,6 +166,15 @@ impl ApiResponse { } } +impl ApiResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ArrayOfArrayOfNumberOnly { #[serde(rename = "ArrayArrayNumber")] @@ -93,6 +191,15 @@ impl ArrayOfArrayOfNumberOnly { } } +impl ArrayOfArrayOfNumberOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ArrayOfNumberOnly { #[serde(rename = "ArrayNumber")] @@ -109,6 +216,15 @@ impl ArrayOfNumberOnly { } } +impl ArrayOfNumberOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ArrayTest { #[serde(rename = "array_of_string")] @@ -141,6 +257,15 @@ impl ArrayTest { } } +impl ArrayTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Capitalization { #[serde(rename = "smallCamel")] @@ -183,6 +308,15 @@ impl Capitalization { } } +impl Capitalization { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Cat { #[serde(rename = "className")] @@ -208,6 +342,15 @@ impl Cat { } } +impl Cat { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Category")] pub struct Category { @@ -230,6 +373,15 @@ impl Category { } } +impl Category { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + /// Model for testing model with \"_class\" property #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ClassModel { @@ -247,6 +399,15 @@ impl ClassModel { } } +impl ClassModel { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Client { #[serde(rename = "client")] @@ -263,6 +424,15 @@ impl Client { } } +impl Client { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Dog { #[serde(rename = "className")] @@ -288,6 +458,15 @@ impl Dog { } } +impl Dog { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct EnumArrays { // Note: inline enums are not fully supported by openapi-generator @@ -317,6 +496,15 @@ impl EnumArrays { } } +impl EnumArrays { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + /// Enumeration of values. /// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` /// which helps with FFI. @@ -354,6 +542,15 @@ impl ::std::str::FromStr for EnumClass { } } +impl EnumClass { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct EnumTest { // Note: inline enums are not fully supported by openapi-generator @@ -393,6 +590,15 @@ impl EnumTest { } } +impl EnumTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FormatTest { #[serde(rename = "integer")] @@ -465,6 +671,15 @@ impl FormatTest { } } +impl FormatTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct HasOnlyReadOnly { #[serde(rename = "bar")] @@ -486,6 +701,15 @@ impl HasOnlyReadOnly { } } +impl HasOnlyReadOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct List { #[serde(rename = "123-list")] @@ -502,6 +726,15 @@ impl List { } } +impl List { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MapTest { #[serde(rename = "map_map_of_string")] @@ -530,6 +763,15 @@ impl MapTest { } } +impl MapTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MixedPropertiesAndAdditionalPropertiesClass { #[serde(rename = "uuid")] @@ -556,6 +798,15 @@ impl MixedPropertiesAndAdditionalPropertiesClass { } } +impl MixedPropertiesAndAdditionalPropertiesClass { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + /// Model for testing model name starting with number #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Name")] @@ -579,6 +830,15 @@ impl Model200Response { } } +impl Model200Response { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + /// Model for testing reserved words #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Return")] @@ -597,6 +857,15 @@ impl ModelReturn { } } +impl ModelReturn { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + /// Model for testing model name same as property name #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Name")] @@ -629,6 +898,15 @@ impl Name { } } +impl Name { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct NumberOnly { #[serde(rename = "JustNumber")] @@ -645,6 +923,15 @@ impl NumberOnly { } } +impl NumberOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Order")] pub struct Order { @@ -689,6 +976,15 @@ impl Order { } } +impl Order { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct OuterBoolean(bool); @@ -719,6 +1015,15 @@ impl ::std::ops::DerefMut for OuterBoolean { } +impl OuterBoolean { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct OuterComposite { #[serde(rename = "my_number")] @@ -745,6 +1050,15 @@ impl OuterComposite { } } +impl OuterComposite { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + /// Enumeration of values. /// Since this enum's variants do not hold data, we can easily define them them as `#[repr(C)]` /// which helps with FFI. @@ -782,6 +1096,15 @@ impl ::std::str::FromStr for OuterEnum { } } +impl OuterEnum { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct OuterNumber(f64); @@ -812,6 +1135,15 @@ impl ::std::ops::DerefMut for OuterNumber { } +impl OuterNumber { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct OuterString(String); @@ -842,6 +1174,15 @@ impl ::std::ops::DerefMut for OuterString { } +impl OuterString { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Pet")] pub struct Pet { @@ -884,6 +1225,15 @@ impl Pet { } } +impl Pet { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ReadOnlyFirst { #[serde(rename = "bar")] @@ -905,6 +1255,15 @@ impl ReadOnlyFirst { } } +impl ReadOnlyFirst { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "$special[model.name]")] pub struct SpecialModelName { @@ -922,6 +1281,15 @@ impl SpecialModelName { } } +impl SpecialModelName { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Tag")] pub struct Tag { @@ -944,6 +1312,15 @@ impl Tag { } } +impl Tag { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "User")] pub struct User { @@ -996,3 +1373,12 @@ impl User { } } } + +impl User { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code)] + pub(crate) fn to_xml(&self) -> String { + serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") + } +} diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs index 30bd11d25f69..72694a9cef1d 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs @@ -313,7 +313,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -481,7 +481,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -565,7 +565,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); diff --git a/samples/server/petstore/rust-server/output/rust-server-test/README.md b/samples/server/petstore/rust-server/output/rust-server-test/README.md index d8012a35b174..7a1e577f2e49 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/README.md +++ b/samples/server/petstore/rust-server/output/rust-server-test/README.md @@ -123,6 +123,7 @@ Method | HTTP request | Description ## Documentation For Models - [ANullableContainer](docs/ANullableContainer.md) + - [AdditionalPropertiesObject](docs/AdditionalPropertiesObject.md) - [InlineObject](docs/InlineObject.md) - [ObjectOfObjects](docs/ObjectOfObjects.md) - [ObjectOfObjectsInner](docs/ObjectOfObjectsInner.md) diff --git a/samples/server/petstore/rust-server/output/rust-server-test/docs/AdditionalPropertiesObject.md b/samples/server/petstore/rust-server/output/rust-server-test/docs/AdditionalPropertiesObject.md new file mode 100644 index 000000000000..add2259d383e --- /dev/null +++ b/samples/server/petstore/rust-server/output/rust-server-test/docs/AdditionalPropertiesObject.md @@ -0,0 +1,9 @@ +# AdditionalPropertiesObject + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs index 3b3f990979f6..c4cf55812a7d 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs @@ -13,7 +13,6 @@ use std::marker::PhantomData; use hyper; use rust_server_test; use swagger::{Has, XSpanIdString}; -use swagger::auth::Authorization; pub struct NewService{ marker: PhantomData diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index 8c1d19610916..3340ba7bbec3 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs @@ -264,7 +264,6 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -318,10 +317,8 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_nested_response).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -380,7 +377,6 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); @@ -446,7 +442,6 @@ impl Api for Client where let body = param_body; - request.set_body(body.into_bytes()); @@ -514,7 +509,6 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Get, uri); - request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs index a4d5b838c108..36051fd4b7a9 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs @@ -2,7 +2,6 @@ extern crate chrono; extern crate uuid; - use serde::ser::Serializer; use std::collections::HashMap; @@ -32,6 +31,20 @@ impl ANullableContainer { } } + +/// An additionalPropertiesObject +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AdditionalPropertiesObject { +} + +impl AdditionalPropertiesObject { + pub fn new() -> AdditionalPropertiesObject { + AdditionalPropertiesObject { + } + } +} + + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct InlineObject { #[serde(rename = "id")] @@ -52,6 +65,7 @@ impl InlineObject { } } + /// An object of objects #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjects { @@ -69,6 +83,7 @@ impl ObjectOfObjects { } } + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjectsInner { #[serde(rename = "optional_thing")] @@ -88,3 +103,4 @@ impl ObjectOfObjectsInner { } } } +