From 8db7e6caff04ee4541631383620ea34d8ef23a9c Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 27 Nov 2018 18:02:53 +0000 Subject: [PATCH 01/17] Move XML namespace handling to the models --- .../codegen/languages/RustServerCodegen.java | 32 +- .../resources/rust-server/client-mod.mustache | 42 +- .../resources/rust-server/models.mustache | 32 +- .../2_0/rust-server/rust-server-test.yaml | 6 + .../src/client/mod.rs | 48 +-- .../src/models.rs | 387 +++++++++++++++++- .../output/rust-server-test/api/openapi.yaml | 6 + .../output/rust-server-test/src/client/mod.rs | 5 - .../output/rust-server-test/src/models.rs | 98 ++++- 9 files changed, 566 insertions(+), 90 deletions(-) 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 b86dd81324e1..6d43a4c534e9 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 @@ -1067,22 +1067,22 @@ 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 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 ec0c88692d13..a84d5e6e48e6 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 @@ -273,23 +273,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/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index aa106c2b7009..f391d05aff0c 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -5,7 +5,7 @@ extern crate uuid; {{#usesXml}}use serde_xml_rs;{{/usesXml}} use serde::ser::Serializer; -use std::collections::HashMap; +use std::collections::{HashMap, BTreeMap}; use models; use swagger; @@ -164,12 +164,36 @@ impl {{{classname}}} { } } } -{{/arrayModelType}}{{/dataType}}{{/isEnum}}{{/model}}{{/models}}{{#usesXmlNamespaces}} +{{/arrayModelType}}{{/dataType}}{{/isEnum}} + +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(), models::namespaces::{{#vendorExtensions}}{{{upperCaseName}}}{{/vendorExtensions}}.clone()); + 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}} + } +} + +{{/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}} + {{#models}} + {{#model}} + {{#xmlNamespace}} + pub static ref {{#vendorExtensions}}{{{upperCaseName}}}{{/vendorExtensions}}: String = "{{{xmlNamespace}}}".to_string(); + {{/xmlNamespace}} + {{/model}} + {{/models}} } } {{/usesXmlNamespaces}} 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..d3019c47ff95 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 @@ -114,6 +114,12 @@ definitions: type: string optional_thing: type: integer + XmlObject: + description: An XML object + type: string + xml: + name: an_xml_object + namespace: foo.bar # Currently broken - see https://github.com/OpenAPITools/openapi-generator/issues/8 # ArrayOfObjects: # description: An array of objects 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 3f873a33749d..33fa4a10774a 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 @@ -293,10 +293,8 @@ impl Api for Client where // Body parameter - let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -369,7 +367,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") }); @@ -444,7 +441,6 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); let body = param_outer_composite.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -519,7 +515,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") }); @@ -594,7 +589,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") }); @@ -672,10 +666,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -735,10 +727,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Patch, uri); - let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -828,7 +818,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 @@ -987,10 +975,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_request_body).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -1058,7 +1044,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())); @@ -1116,10 +1101,8 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -1191,9 +1174,7 @@ if let Some(body) = body { // Body parameter - - let body = serde_xml_rs::to_string(¶m_pet).expect("impossible to fail to serialize"); - + let body = param_pet.to_xml(); request.set_body(body.into_bytes()); @@ -1255,7 +1236,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 @@ -1320,7 +1300,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())); @@ -1402,7 +1381,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())); @@ -1480,7 +1458,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())); @@ -1566,9 +1543,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - - let body = serde_xml_rs::to_string(¶m_pet).expect("impossible to fail to serialize"); - + let body = param_pet.to_xml(); request.set_body(body.into_bytes()); @@ -1655,7 +1630,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())); @@ -1719,7 +1693,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())); @@ -1786,7 +1759,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())); @@ -1852,7 +1824,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())); @@ -1919,7 +1890,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())); @@ -2005,10 +1975,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_order).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2091,10 +2059,8 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2154,10 +2120,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2217,10 +2181,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); - request.set_body(body.into_bytes()); @@ -2281,7 +2243,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())); @@ -2347,7 +2308,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())); @@ -2440,7 +2400,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())); @@ -2528,7 +2487,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())); @@ -2584,10 +2542,8 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_user).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/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index 0daa05e4dbf3..d5745e49925b 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,17 @@ 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 +62,17 @@ 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 ApiResponse { #[serde(rename = "code")] @@ -77,6 +99,17 @@ 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 +126,17 @@ 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 +153,17 @@ 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 +196,17 @@ 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 +249,17 @@ 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 +285,17 @@ 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 +318,17 @@ 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 +346,17 @@ 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 +373,17 @@ 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 +409,17 @@ 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 +449,17 @@ 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 +497,17 @@ 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 +547,17 @@ 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 +630,17 @@ 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 +662,17 @@ 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 +689,17 @@ 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 +728,17 @@ 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 +765,17 @@ 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 +799,17 @@ 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 +828,17 @@ 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 +871,17 @@ 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 +898,17 @@ 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 +953,17 @@ 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 +994,17 @@ 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 +1031,17 @@ 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 +1079,17 @@ 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 +1120,17 @@ 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 +1161,17 @@ 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 +1214,17 @@ 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 +1246,17 @@ 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 +1274,17 @@ 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 +1307,17 @@ 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 +1370,14 @@ 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/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index 10a6a87b9ddb..4fbe5e4664d5 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -113,6 +113,12 @@ components: inner: $ref: '#/components/schemas/ObjectOfObjects_inner' type: object + XmlObject: + description: An XML object + type: string + xml: + name: an_xml_object + namespace: foo.bar inline_object: properties: id: 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 a487915c49eb..1f88433461f2 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 @@ -265,7 +265,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())); @@ -322,7 +321,6 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Put, uri); let body = param_inline_object.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -387,7 +385,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())); @@ -455,7 +452,6 @@ if let Some(body) = body { let body = param_body; - request.set_body(body.into_bytes()); @@ -525,7 +521,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())); 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..d7dd2589984a 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 @@ -5,7 +5,7 @@ extern crate uuid; use serde::ser::Serializer; -use std::collections::HashMap; +use std::collections::{HashMap, BTreeMap}; use models; use swagger; @@ -32,6 +32,17 @@ impl ANullableContainer { } } + +impl ANullableContainer { + /// 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 InlineObject { #[serde(rename = "id")] @@ -52,6 +63,17 @@ impl InlineObject { } } + +impl InlineObject { + /// 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 object of objects #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjects { @@ -69,6 +91,17 @@ impl ObjectOfObjects { } } + +impl ObjectOfObjects { + /// 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 ObjectOfObjectsInner { #[serde(rename = "optional_thing")] @@ -88,3 +121,66 @@ impl ObjectOfObjectsInner { } } } + + +impl ObjectOfObjectsInner { + /// 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, PartialOrd, Serialize, Deserialize)] +#[serde(rename = "an_xml_object")] +pub struct XmlObject(String); + +impl ::std::convert::From for XmlObject { + fn from(x: String) -> Self { + XmlObject(x) + } +} + +impl ::std::convert::From for String { + fn from(x: XmlObject) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for XmlObject { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl ::std::ops::DerefMut for XmlObject { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +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(), models::namespaces::XMLOBJECT.clone()); + serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + } +} + + +//XML namespaces +pub mod namespaces { + lazy_static!{ + pub static ref XMLOBJECT: String = "foo.bar".to_string(); + } +} From 6c96cb227f35e8aab307d17ce41c3e9047feea01 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Wed, 28 Nov 2018 11:45:49 +0000 Subject: [PATCH 02/17] Expand XML example --- .../2_0/rust-server/rust-server-test.yaml | 24 ++++- .../output/rust-server-test/Cargo.toml | 6 +- .../output/rust-server-test/README.md | 1 + .../output/rust-server-test/api/openapi.yaml | 21 +++- .../rust-server-test/examples/client.rs | 9 +- .../examples/server_lib/server.rs | 10 +- .../output/rust-server-test/src/client/mod.rs | 78 +++++++++++++- .../output/rust-server-test/src/lib.rs | 19 +++- .../output/rust-server-test/src/mimetypes.rs | 8 ++ .../output/rust-server-test/src/models.rs | 35 ++---- .../output/rust-server-test/src/server/mod.rs | 101 +++++++++++++++++- 11 files changed, 275 insertions(+), 37 deletions(-) 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 d3019c47ff95..70e32b232105 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,25 @@ paths: description: Success schema: type: object + /xml: + post: + summary: Test XML + consumes: + - application/xml + produces: + - application/xml + parameters: + - in: body + name: body + required: true + schema: + $ref: '#/definitions/XmlObject' + responses: + 200: + description: Success + schema: + $ref: '#/definitions/XmlObject' + # Requests with arbitrary JSON currently fail. # post: # summary: Send an arbitrary JSON blob @@ -116,7 +135,10 @@ definitions: type: integer XmlObject: description: An XML object - type: string + type: object + properties: + inner: + type: string xml: name: an_xml_object namespace: foo.bar diff --git a/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml b/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml index 3a837e477ea4..948a9bb42b80 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml +++ b/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml @@ -7,8 +7,8 @@ license = "Unlicense" [features] default = ["client", "server"] -client = ["serde_json", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"] -server = ["serde_json", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"] +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. @@ -41,7 +41,7 @@ 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" 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 49af89f0718f..c38ed5a32efc 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 @@ -60,6 +60,7 @@ cargo run --example client DummyPut cargo run --example client FileResponseGet cargo run --example client HtmlPost cargo run --example client RawJsonGet +cargo run --example client XmlPost ``` ### HTTPS diff --git a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index 4fbe5e4664d5..8e5c278d1b14 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -69,6 +69,22 @@ paths: type: object description: Success summary: Get an arbitrary JSON blob. + /xml: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlObject' + required: true + responses: + 200: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlObject' + description: Success + summary: Test XML components: requestBodies: nested_response: @@ -115,7 +131,10 @@ components: type: object XmlObject: description: An XML object - type: string + properties: + inner: + type: string + type: object xml: name: an_xml_object namespace: foo.bar diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs index 54377a219dc1..fe4ac02db826 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs @@ -23,7 +23,8 @@ use rust_server_test::{ApiNoContext, ContextWrapperExt, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse + RawJsonGetResponse, + XmlPostResponse }; use clap::{App, Arg}; @@ -102,6 +103,12 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, + // Disabled because there's no example. + // Some("XmlPost") => { + // let result = core.run(client.xml_post(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, + _ => { panic!("Invalid operation provided") } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs index a1067282c4b3..b2dd8c281dfa 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs @@ -15,7 +15,8 @@ use rust_server_test::{Api, ApiError, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse + RawJsonGetResponse, + XmlPostResponse }; use rust_server_test::models; @@ -67,4 +68,11 @@ impl Api for Server where C: Has{ Box::new(futures::failed("Generic failure".into())) } + /// Test XML + fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box> { + let context = context.clone(); + println!("xml_post({:?}) - 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/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index 1f88433461f2..f6c3b0ebfd99 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 @@ -29,7 +29,7 @@ use std::str::FromStr; use mimetypes; use serde_json; - +use serde_xml_rs; #[allow(unused_imports)] use std::collections::{HashMap, BTreeMap}; @@ -43,7 +43,8 @@ use {Api, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse + RawJsonGetResponse, + XmlPostResponse }; use models; @@ -571,6 +572,79 @@ if let Some(body) = body { } + fn xml_post(&self, param_xml_object: models::XmlObject, context: &C) -> Box> { + + + let 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_xml_object.to_xml(); + + 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() { + 200 => { + let body = response.body(); + Box::new( + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + XmlPostResponse::Success(body) + ) + ) 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)] diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs index b319918858d2..b0e454caa8c2 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs @@ -4,7 +4,7 @@ extern crate serde; extern crate serde_derive; extern crate serde_json; - +extern crate serde_xml_rs; extern crate futures; extern crate chrono; #[macro_use] @@ -69,6 +69,12 @@ pub enum RawJsonGetResponse { Success ( serde_json::Value ) , } +#[derive(Debug, PartialEq)] +pub enum XmlPostResponse { + /// Success + Success ( models::XmlObject ) , +} + /// API pub trait Api { @@ -88,6 +94,9 @@ pub trait Api { /// Get an arbitrary JSON blob. fn raw_json_get(&self, context: &C) -> Box>; + /// Test XML + fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box>; + } /// API without a `Context` @@ -108,6 +117,9 @@ pub trait ApiNoContext { /// Get an arbitrary JSON blob. fn raw_json_get(&self) -> Box>; + /// Test XML + fn xml_post(&self, xml_object: models::XmlObject) -> Box>; + } /// Trait to extend an API to make it easy to bind it to a context. @@ -149,6 +161,11 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { self.api().raw_json_get(&self.context()) } + /// Test XML + fn xml_post(&self, xml_object: models::XmlObject) -> Box> { + self.api().xml_post(xml_object, &self.context()) + } + } #[cfg(feature = "client")] diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs index 01fdce1e9025..a980535131e3 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs @@ -16,6 +16,10 @@ pub mod responses { lazy_static! { pub static ref RAW_JSON_GET_SUCCESS: Mime = "*/*".parse().unwrap(); } + /// Create Mime objects for the response content types for XmlPost + lazy_static! { + pub static ref XML_POST_SUCCESS: Mime = "application/xml".parse().unwrap(); + } } @@ -29,5 +33,9 @@ pub mod requests { lazy_static! { pub static ref HTML_POST: Mime = "text/html".parse().unwrap(); } + /// Create Mime objects for the request content types for XmlPost + lazy_static! { + pub static ref XML_POST: Mime = "application/xml".parse().unwrap(); + } } 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 d7dd2589984a..f5fbaa23f049 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,7 @@ extern crate chrono; extern crate uuid; - +use serde_xml_rs; use serde::ser::Serializer; use std::collections::{HashMap, BTreeMap}; @@ -134,37 +134,24 @@ impl ObjectOfObjectsInner { /// An XML object -#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "an_xml_object")] -pub struct XmlObject(String); - -impl ::std::convert::From for XmlObject { - fn from(x: String) -> Self { - XmlObject(x) - } -} - -impl ::std::convert::From for String { - fn from(x: XmlObject) -> Self { - x.0 - } -} +pub struct XmlObject { + #[serde(rename = "inner")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner: Option, -impl ::std::ops::Deref for XmlObject { - type Target = String; - fn deref(&self) -> &String { - &self.0 - } } -impl ::std::ops::DerefMut for XmlObject { - fn deref_mut(&mut self) -> &mut String { - &mut self.0 +impl XmlObject { + pub fn new() -> XmlObject { + XmlObject { + inner: None, + } } } - impl XmlObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index 852da4aab3b8..e688eb47a669 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -21,7 +21,7 @@ use self::url::form_urlencoded; use mimetypes; use serde_json; - +use serde_xml_rs; #[allow(unused_imports)] use std::collections::{HashMap, BTreeMap}; @@ -41,7 +41,8 @@ use {Api, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse + RawJsonGetResponse, + XmlPostResponse }; #[allow(unused_imports)] use models; @@ -58,13 +59,15 @@ mod paths { r"^/dummy$", r"^/file_response$", r"^/html$", - r"^/raw_json$" + r"^/raw_json$", + r"^/xml$" ]).unwrap(); } pub static ID_DUMMY: usize = 0; pub static ID_FILE_RESPONSE: usize = 1; pub static ID_HTML: usize = 2; pub static ID_RAW_JSON: usize = 3; + pub static ID_XML: usize = 4; } pub struct NewService { @@ -434,6 +437,95 @@ where }, + // 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_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(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter XmlObject - doesn't match schema: {}", e)))), + } + + } else { + None + }; + let param_xml_object = match param_xml_object { + Some(param_xml_object) => param_xml_object, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter XmlObject"))), + }; + + + Box::new(api_impl.xml_post(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 { + XmlPostResponse::Success + + (body) + + + => { + response.set_status(StatusCode::try_from(200).unwrap()); + + response.headers_mut().set(ContentType(mimetypes::responses::XML_POST_SUCCESS.clone())); + + + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::XMLOBJECT.clone()); + let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + + response.set_body(body); + }, + }, + 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>, } } @@ -470,6 +562,9 @@ impl RequestParser for ApiRequestParser { // RawJsonGet - GET /raw_json &hyper::Method::Get if path.matched(paths::ID_RAW_JSON) => Ok("RawJsonGet"), + + // XmlPost - POST /xml + &hyper::Method::Post if path.matched(paths::ID_XML) => Ok("XmlPost"), _ => Err(()), } } From 549dcacbd0f8f084f0e96bc03659fa13a1d06454 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Wed, 28 Nov 2018 11:49:33 +0000 Subject: [PATCH 03/17] Remove dead code --- .../codegen/languages/RustServerCodegen.java | 17 ----------------- 1 file changed, 17 deletions(-) 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 6d43a4c534e9..0ea99bae6ceb 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 @@ -1067,23 +1067,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; From e931d3782969d882e18408bccef69842a0ba57df Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Wed, 28 Nov 2018 11:51:58 +0000 Subject: [PATCH 04/17] Only add `to_xml` when we actually need it --- .../src/main/resources/rust-server/models.mustache | 2 ++ 1 file changed, 2 insertions(+) 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 f391d05aff0c..580ddf86bcc0 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -166,6 +166,7 @@ impl {{{classname}}} { } {{/arrayModelType}}{{/dataType}}{{/isEnum}} +{{#usesXml}} impl {{{classname}}} { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -182,6 +183,7 @@ impl {{{classname}}} { {{/xmlNamespace}} } } +{{/usesXml}} {{/model}}{{/models}}{{#usesXmlNamespaces}} //XML namespaces From f91d183d1a0a65c567e1079ecf329d8d2a206297 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Fri, 30 Nov 2018 13:17:39 +0000 Subject: [PATCH 05/17] Add more XML samples --- .../resources/2_0/rust-server/openapi-v3.yaml | 29 ++ .../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 | 104 ++++++ .../output/openapi-v3/api/openapi.yaml | 31 ++ .../output/openapi-v3/examples/ca.pem | 17 + .../output/openapi-v3/examples/client.rs | 82 +++++ .../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 | 38 ++ .../openapi-v3/examples/server_lib/server.rs | 38 ++ .../output/openapi-v3/src/client/mod.rs | 346 ++++++++++++++++++ .../rust-server/output/openapi-v3/src/lib.rs | 100 +++++ .../output/openapi-v3/src/mimetypes.rs | 17 + .../output/openapi-v3/src/models.rs | 109 ++++++ .../output/openapi-v3/src/server/context.rs | 91 +++++ .../output/openapi-v3/src/server/mod.rs | 226 ++++++++++++ 21 files changed, 1489 insertions(+) create mode 100644 modules/openapi-generator/src/test/resources/2_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/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 diff --git a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml new file mode 100644 index 000000000000..43318951f7b4 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.1 +info: + title: My title + description: API under test + version: 1.0.7 +paths: + /xml: + post: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/XmlArray' + responses: + 201: + description: OK +components: + schemas: + XmlArray: + type: array + xml: + wrapped: true + items: + $ref: '#/components/schemas/XmlInner' + XmlInner: + type: string + xml: + name: another + 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..46c29b11a1f5 --- /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_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"] +server = ["serde_json", "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 + + +[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..75d368f2fd25 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/README.md @@ -0,0 +1,104 @@ +# 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 XmlPost +``` + +### 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. 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..8c7b56000e84 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -0,0 +1,31 @@ +openapi: 3.0.1 +info: + description: API under test + title: My title + version: 1.0.7 +servers: +- url: / +paths: + /xml: + post: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/XmlArray' + responses: + 201: + description: OK +components: + schemas: + XmlArray: + items: + $ref: '#/components/schemas/XmlInner' + type: array + xml: + wrapped: true + XmlInner: + type: string + xml: + name: another + 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..bfdeae4e3990 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs @@ -0,0 +1,82 @@ +#![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, + XmlPostResponse + }; +use clap::{App, Arg}; + +fn main() { + let matches = App::new("client") + .arg(Arg::with_name("operation") + .help("Sets the operation to run") + .possible_values(&[ + "XmlPost", +]) + .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("XmlPost") => { + let result = core.run(client.xml_post(Some(&Vec::new()))); + 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..03346a327137 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs @@ -0,0 +1,38 @@ +//! 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}; +use swagger::auth::Authorization; + +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..b820d1d188a2 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs @@ -0,0 +1,38 @@ +//! 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, + XmlPostResponse +}; +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_post(&self, string: Option<&Vec>, 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())) + } + +} 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..a7f74b3bc09e --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs @@ -0,0 +1,346 @@ +#![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 mimetypes; + +use serde_json; + + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData}; + +use {Api, + XmlPostResponse + }; +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_post(&self, param_string: Option<&Vec>, context: &C) -> Box> { + + + let 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); + + + // Body parameter + let body = param_string.map(|ref body| { + serde_json::to_string(body).expect("impossible to fail to serialize") + }); + +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> + }, + 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..1964b81f8721 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -0,0 +1,100 @@ +#![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 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 XmlPostResponse { + /// OK + OK , +} + + +/// API +pub trait Api { + + + fn xml_post(&self, string: Option<&Vec>, context: &C) -> Box>; + +} + +/// API without a `Context` +pub trait ApiNoContext { + + + fn xml_post(&self, string: Option<&Vec>) -> 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_post(&self, string: Option<&Vec>) -> Box> { + self.api().xml_post(string, &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..8c43b176c1c9 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs @@ -0,0 +1,17 @@ +/// 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 XmlPost + lazy_static! { + pub static ref XML_POST: Mime = "application/json".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..3a1bb8e03a49 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -0,0 +1,109 @@ +#![allow(unused_imports, unused_qualifications, unused_extern_crates)] +extern crate chrono; +extern crate uuid; + + +use serde::ser::Serializer; + +use std::collections::{HashMap, BTreeMap}; +use models; +use swagger; + + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct XmlArray(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 + } +} + + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] +#[serde(rename = "another")] +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 + } +} + + + + 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..7a76919e7c55 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -0,0 +1,226 @@ +#![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; + + +#[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, + XmlPostResponse + }; +#[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$" + ]).unwrap(); + } + pub static ID_XML: usize = 0; +} + +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 { + + // 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_json::Deserializer::from_slice(&*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.as_ref(), &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()); + + }, + }, + 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> + + }, + + + _ => 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() { + + // XmlPost - POST /xml + &hyper::Method::Post if path.matched(paths::ID_XML) => Ok("XmlPost"), + _ => Err(()), + } + } +} From 2578884a63ca714fc2f94757c59a196ac6d33509 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Fri, 30 Nov 2018 14:13:30 +0000 Subject: [PATCH 06/17] Add yet more XML tests --- .../2_0/rust-server/rust-server-test.yaml | 20 ++ .../output/rust-server-test/api/openapi.yaml | 16 ++ .../output/rust-server-test/src/models.rs | 197 ++++++++++++++++++ 3 files changed, 233 insertions(+) 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 70e32b232105..c8a4d8fd3806 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 @@ -142,6 +142,26 @@ definitions: xml: name: an_xml_object namespace: foo.bar + XmlList: + description: An XML list with items directly defined + type: array + xml: + wrapped: true + items: + type: string + xml: + name: xml_list_inner + XmlListRef: + description: An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. + type: array + xml: + wrapped: true + items: + $ref: '#/definitions/XmlInner' + XmlListRefInner: + type: string + xml: + name: xml_list_ref_inner # Currently broken - see https://github.com/OpenAPITools/openapi-generator/issues/8 # ArrayOfObjects: # description: An array of objects diff --git a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index 8e5c278d1b14..e36c812e6ce4 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -129,6 +129,10 @@ components: inner: $ref: '#/components/schemas/ObjectOfObjects_inner' type: object + XmlListRefInner: + type: string + xml: + name: xml_list_ref_inner XmlObject: description: An XML object properties: @@ -155,4 +159,16 @@ components: type: string required: - required_thing + XmlListRef: + description: An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. + items: + $ref: '#/components/schemas/XmlInner' + type: array + XmlList: + description: An XML list with items directly defined + items: + type: string + xml: + name: xml_list_inner + type: array 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 f5fbaa23f049..2bdb25f96736 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 @@ -133,6 +133,203 @@ impl ObjectOfObjectsInner { } +/// An XML list with items directly defined +// Utility function for wrapping list elements when serializing xml +fn wrap_in_xml_list_inner(item: &Vec, serializer: S) -> Result +where + S: Serializer, +{ + serde_xml_rs::wrap_primitives(item, serializer, "xml_list_inner") +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct XmlList(Vec); + +impl ::std::convert::From> for XmlList { + fn from(x: Vec) -> Self { + XmlList(x) + } +} + +impl ::std::convert::From for Vec { + fn from(x: XmlList) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator for XmlList { + fn from_iter>(u: U) -> Self { + XmlList(Vec::::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for XmlList { + 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 XmlList { + 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 XmlList { + 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 XmlList { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for XmlList { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + + + +impl XmlList { + /// 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 list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct XmlListRef(Vec); + +impl ::std::convert::From> for XmlListRef { + fn from(x: Vec) -> Self { + XmlListRef(x) + } +} + +impl ::std::convert::From for Vec { + fn from(x: XmlListRef) -> Self { + x.0 + } +} + +impl ::std::iter::FromIterator for XmlListRef { + fn from_iter>(u: U) -> Self { + XmlListRef(Vec::::from_iter(u)) + } +} + +impl ::std::iter::IntoIterator for XmlListRef { + type Item = XmlInner; + type IntoIter = ::std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a XmlListRef { + type Item = &'a XmlInner; + type IntoIter = ::std::slice::Iter<'a, XmlInner>; + + fn into_iter(self) -> Self::IntoIter { + (&self.0).into_iter() + } +} + +impl<'a> ::std::iter::IntoIterator for &'a mut XmlListRef { + type Item = &'a mut XmlInner; + type IntoIter = ::std::slice::IterMut<'a, XmlInner>; + + fn into_iter(self) -> Self::IntoIter { + (&mut self.0).into_iter() + } +} + +impl ::std::ops::Deref for XmlListRef { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl ::std::ops::DerefMut for XmlListRef { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + + + +impl XmlListRef { + /// 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 = "xml_list_ref_inner")] +pub struct XmlListRefInner(String); + +impl ::std::convert::From for XmlListRefInner { + fn from(x: String) -> Self { + XmlListRefInner(x) + } +} + +impl ::std::convert::From for String { + fn from(x: XmlListRefInner) -> Self { + x.0 + } +} + +impl ::std::ops::Deref for XmlListRefInner { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl ::std::ops::DerefMut for XmlListRefInner { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +impl XmlListRefInner { + /// 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 = "an_xml_object")] From f927241ea8e75e9a8f0eb07e680a3a5600248955 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Fri, 30 Nov 2018 15:00:08 +0000 Subject: [PATCH 07/17] Handle wrapped XML objects in lists --- .../codegen/languages/RustServerCodegen.java | 29 +++++++++++++++---- .../output/openapi-v3/src/models.rs | 8 +++++ 2 files changed, 31 insertions(+), 6 deletions(-) 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 0ea99bae6ceb..ae1bd450be95 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 @@ -827,17 +827,34 @@ public CodegenModel fromModel(String name, Schema model, Map all } 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); } 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 index 3a1bb8e03a49..9c1dd7243b7d 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -10,6 +10,14 @@ use models; use swagger; +// Utility function for wrapping list elements when serializing xml +fn wrap_in_another(item: &Vec, serializer: S) -> Result +where + S: Serializer, +{ + serde_xml_rs::wrap_primitives(item, serializer, "another") +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct XmlArray(Vec); From 952322b126d54d8217070fedb04fa537c94cefe2 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Fri, 30 Nov 2018 15:19:02 +0000 Subject: [PATCH 08/17] XML example is XML --- .../resources/2_0/rust-server/openapi-v3.yaml | 2 +- .../rust-server/output/openapi-v3/Cargo.toml | 6 +++--- .../output/openapi-v3/api/openapi.yaml | 2 +- .../output/openapi-v3/src/client/mod.rs | 4 ++-- .../rust-server/output/openapi-v3/src/lib.rs | 2 +- .../output/openapi-v3/src/mimetypes.rs | 2 +- .../output/openapi-v3/src/models.rs | 18 +++++++++++++++++- .../output/openapi-v3/src/server/mod.rs | 5 ++--- 8 files changed, 28 insertions(+), 13 deletions(-) diff --git a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml index 43318951f7b4..f78bed49a377 100644 --- a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml @@ -8,7 +8,7 @@ paths: post: requestBody: content: - application/json: + application/xml: schema: $ref: '#/components/schemas/XmlArray' responses: diff --git a/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml index 46c29b11a1f5..b2edca9c74bd 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml +++ b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml @@ -7,8 +7,8 @@ license = "Unlicense" [features] default = ["client", "server"] -client = ["serde_json", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"] -server = ["serde_json", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"] +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. @@ -41,7 +41,7 @@ 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" 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 index 8c7b56000e84..f782d3cdfbca 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -10,7 +10,7 @@ paths: post: requestBody: content: - application/json: + application/xml: schema: $ref: '#/components/schemas/XmlArray' responses: 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 index a7f74b3bc09e..f73afc48da41 100644 --- 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 @@ -29,7 +29,7 @@ use std::str::FromStr; use mimetypes; use serde_json; - +use serde_xml_rs; #[allow(unused_imports)] use std::collections::{HashMap, BTreeMap}; @@ -263,7 +263,7 @@ impl Api for Client where // Body parameter let body = param_string.map(|ref body| { - serde_json::to_string(body).expect("impossible to fail to serialize") + body.to_xml() }); if let Some(body) = body { 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 index 1964b81f8721..72acd6a055cc 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -4,7 +4,7 @@ extern crate serde; extern crate serde_derive; extern crate serde_json; - +extern crate serde_xml_rs; extern crate futures; extern crate chrono; #[macro_use] 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 index 8c43b176c1c9..00cc6ccaa80c 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs @@ -11,7 +11,7 @@ pub mod requests { use hyper::mime::*; /// Create Mime objects for the request content types for XmlPost lazy_static! { - pub static ref XML_POST: Mime = "application/json".parse().unwrap(); + pub static ref XML_POST: 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 index 9c1dd7243b7d..3ae838d927a0 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -2,7 +2,7 @@ extern crate chrono; extern crate uuid; - +use serde_xml_rs; use serde::ser::Serializer; use std::collections::{HashMap, BTreeMap}; @@ -81,6 +81,14 @@ impl ::std::ops::DerefMut for XmlArray { +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)] @@ -114,4 +122,12 @@ impl ::std::ops::DerefMut for XmlInner { +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") + } +} 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 index 7a76919e7c55..0badb391c280 100644 --- 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 @@ -21,7 +21,7 @@ use self::url::form_urlencoded; use mimetypes; use serde_json; - +use serde_xml_rs; #[allow(unused_imports)] use std::collections::{HashMap, BTreeMap}; @@ -138,8 +138,7 @@ where let mut unused_elements = Vec::new(); let param_string: Option> = if !body.is_empty() { - - let deserializer = &mut serde_json::Deserializer::from_slice(&*body); + 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); From 4bb492e511d28ec2466354e17de34d42130f04f9 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 4 Dec 2018 17:31:16 +0000 Subject: [PATCH 09/17] Use wrapping for lists correctly --- .../src/main/resources/rust-server/models.mustache | 2 +- .../src/test/resources/2_0/rust-server/openapi-v3.yaml | 2 ++ .../server/petstore/rust-server/output/openapi-v3/src/models.rs | 2 +- .../petstore/rust-server/output/rust-server-test/src/models.rs | 2 +- 4 files changed, 5 insertions(+), 3 deletions(-) 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 580ddf86bcc0..4fe43e00ae0e 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -78,7 +78,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 { diff --git a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml index f78bed49a377..db3a680479b3 100644 --- a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml @@ -21,6 +21,8 @@ components: xml: wrapped: true items: + xml: + name: another $ref: '#/components/schemas/XmlInner' XmlInner: type: string 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 index 3ae838d927a0..c9bbd843a17c 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -19,7 +19,7 @@ where } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct XmlArray(Vec); +pub struct XmlArray(#[serde(serialize_with = "wrap_in_another")]Vec); impl ::std::convert::From> for XmlArray { fn from(x: Vec) -> Self { 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 2bdb25f96736..ddea021cc420 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 @@ -143,7 +143,7 @@ where } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct XmlList(Vec); +pub struct XmlList(#[serde(serialize_with = "wrap_in_xml_list_inner")]Vec); impl ::std::convert::From> for XmlList { fn from(x: Vec) -> Self { From 2970404f2fe67c133fee4d712600df04ea6df08a Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 4 Dec 2018 17:36:09 +0000 Subject: [PATCH 10/17] Use valid model names --- .../2_0/rust-server/rust-server-test.yaml | 2 +- .../output/rust-server-test/api/openapi.yaml | 2 +- .../output/rust-server-test/src/models.rs | 28 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) 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 c8a4d8fd3806..8e21ed168a1c 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 @@ -157,7 +157,7 @@ definitions: xml: wrapped: true items: - $ref: '#/definitions/XmlInner' + $ref: '#/definitions/XmlListRefInner' XmlListRefInner: type: string xml: diff --git a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index e36c812e6ce4..49cc3b6c1264 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -162,7 +162,7 @@ components: XmlListRef: description: An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. items: - $ref: '#/components/schemas/XmlInner' + $ref: '#/components/schemas/XmlListRefInner' type: array XmlList: description: An XML list with items directly defined 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 ddea021cc420..18b83fabcd21 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 @@ -217,29 +217,29 @@ impl XmlList { /// An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct XmlListRef(Vec); +pub struct XmlListRef(Vec); -impl ::std::convert::From> for XmlListRef { - fn from(x: Vec) -> Self { +impl ::std::convert::From> for XmlListRef { + fn from(x: Vec) -> Self { XmlListRef(x) } } -impl ::std::convert::From for Vec { +impl ::std::convert::From for Vec { fn from(x: XmlListRef) -> Self { x.0 } } -impl ::std::iter::FromIterator for XmlListRef { - fn from_iter>(u: U) -> Self { - XmlListRef(Vec::::from_iter(u)) +impl ::std::iter::FromIterator for XmlListRef { + fn from_iter>(u: U) -> Self { + XmlListRef(Vec::::from_iter(u)) } } impl ::std::iter::IntoIterator for XmlListRef { - type Item = XmlInner; - type IntoIter = ::std::vec::IntoIter; + type Item = String; + type IntoIter = ::std::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -247,8 +247,8 @@ impl ::std::iter::IntoIterator for XmlListRef { } impl<'a> ::std::iter::IntoIterator for &'a XmlListRef { - type Item = &'a XmlInner; - type IntoIter = ::std::slice::Iter<'a, XmlInner>; + type Item = &'a String; + type IntoIter = ::std::slice::Iter<'a, String>; fn into_iter(self) -> Self::IntoIter { (&self.0).into_iter() @@ -256,8 +256,8 @@ impl<'a> ::std::iter::IntoIterator for &'a XmlListRef { } impl<'a> ::std::iter::IntoIterator for &'a mut XmlListRef { - type Item = &'a mut XmlInner; - type IntoIter = ::std::slice::IterMut<'a, XmlInner>; + type Item = &'a mut String; + type IntoIter = ::std::slice::IterMut<'a, String>; fn into_iter(self) -> Self::IntoIter { (&mut self.0).into_iter() @@ -265,7 +265,7 @@ impl<'a> ::std::iter::IntoIterator for &'a mut XmlListRef { } impl ::std::ops::Deref for XmlListRef { - type Target = Vec; + type Target = Vec; fn deref(&self) -> &Self::Target { &self.0 } From 3bfa9ba77e36f337df4007503641ccf8759c0841 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Wed, 5 Dec 2018 14:38:09 +0000 Subject: [PATCH 11/17] Hack API into working This breaks the examples rather spectacularly, though. --- .../codegen/languages/RustServerCodegen.java | 266 +++++++++++++++--- .../output/openapi-v3/examples/client.rs | 2 +- .../openapi-v3/examples/server_lib/server.rs | 4 +- .../output/openapi-v3/src/client/mod.rs | 4 +- .../rust-server/output/openapi-v3/src/lib.rs | 8 +- .../output/openapi-v3/src/server/mod.rs | 8 +- .../examples/client.rs | 98 +++---- .../examples/server_lib/server.rs | 46 +-- .../src/client/mod.rs | 46 +-- .../src/lib.rs | 98 +++---- .../src/server/mod.rs | 158 +++++------ .../output/rust-server-test/api/openapi.yaml | 3 + .../rust-server-test/examples/client.rs | 12 +- .../examples/server_lib/server.rs | 8 +- .../output/rust-server-test/src/client/mod.rs | 8 +- .../output/rust-server-test/src/lib.rs | 16 +- .../output/rust-server-test/src/server/mod.rs | 24 +- 17 files changed, 507 insertions(+), 302 deletions(-) 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 ae1bd450be95..6f0d23d1db41 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 @@ -23,13 +23,17 @@ 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 org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenConstants; import org.openapitools.codegen.CodegenModel; +import org.openapitools.codegen.CodegenModelType; +import org.openapitools.codegen.CodegenModelFactory; import org.openapitools.codegen.CodegenOperation; import org.openapitools.codegen.CodegenParameter; import org.openapitools.codegen.CodegenProperty; @@ -733,6 +737,204 @@ 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. + @Override + public CodegenParameter fromRequestBody(RequestBody body, Map schemas, Set imports, String bodyParameterName) { + if (body == null) { + LOGGER.error("body in fromRequestBody cannot be null!"); + } + CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); + codegenParameter.baseName = "UNKNOWN_BASE_NAME"; + codegenParameter.paramName = "UNKNOWN_PARAM_NAME"; + codegenParameter.description = escapeText(body.getDescription()); + codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE; + codegenParameter.isBodyParam = Boolean.TRUE; + + String name = null; + LOGGER.debug("Request body = " + body); + Schema schema = ModelUtils.getSchemaFromRequestBody(body); + if (StringUtils.isNotBlank(schema.get$ref())) { + name = ModelUtils.getSimpleRef(schema.get$ref()); + // schema = schemas.get(name); + } + + if (ModelUtils.isMapSchema(schema)) { + Schema inner = ModelUtils.getAdditionalProperties(schema); + if (inner == null) { + inner = new StringSchema().description("//TODO automatically added by openapi-generator"); + schema.setAdditionalProperties(inner); + } + CodegenProperty codegenProperty = fromProperty("property", schema); + // only support 1-dimension map only + imports.add(codegenProperty.baseType); + + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = "request_body"; + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.items = codegenProperty.items; + codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; + codegenParameter.dataType = getTypeDeclaration(schema); + codegenParameter.baseType = getSchemaType(inner); + codegenParameter.isContainer = Boolean.TRUE; + codegenParameter.isMapContainer = Boolean.TRUE; + + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + } else if (ModelUtils.isArraySchema(schema)) { + final ArraySchema arraySchema = (ArraySchema) schema; + Schema inner = arraySchema.getItems(); + if (inner == null) { + inner = new StringSchema().description("//TODO automatically added by openapi-generator"); + arraySchema.setItems(inner); + } + CodegenProperty codegenProperty = fromProperty("property", schema); + imports.add(codegenProperty.baseType); + CodegenProperty innerCp = codegenProperty; + CodegenProperty mostInnerItem = innerCp; + // loop through multidimensional array to add proper import + // also find the most inner item + while (innerCp != null) { + if (innerCp.complexType != null) { + imports.add(innerCp.complexType); + } + mostInnerItem = innerCp; + innerCp = innerCp.items; + } + + if (StringUtils.isEmpty(bodyParameterName)) { + if (StringUtils.isEmpty(mostInnerItem.complexType)) { + codegenParameter.baseName = "request_body"; + } else { + codegenParameter.baseName = mostInnerItem.complexType; + } + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.paramName = toArrayModelParamName(codegenParameter.baseName); + codegenParameter.items = codegenProperty.items; + codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; + codegenParameter.dataType = getTypeDeclaration(arraySchema); + codegenParameter.baseType = getSchemaType(arraySchema); + codegenParameter.isContainer = Boolean.TRUE; + codegenParameter.isListContainer = Boolean.TRUE; + + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + + while (codegenProperty != null) { + imports.add(codegenProperty.baseType); + codegenProperty = codegenProperty.items; + } + + } else if (ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema)) { + CodegenModel codegenModel = null; + if (StringUtils.isNotBlank(name)) { + schema.setName(name); + codegenModel = fromModel(name, schema, schemas); + } + if (codegenModel != null) { + codegenParameter.isModel = true; + } + + if (codegenModel != null && !codegenModel.emptyVars) { + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = codegenModel.classname; + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenModel.classname; + codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); + codegenParameter.description = codegenModel.description; + imports.add(codegenParameter.baseType); + } else { + CodegenProperty codegenProperty = fromProperty("property", schema); + if (ModelUtils.getAdditionalProperties(schema) != null) {// http body is map + LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue."); + } else if (codegenProperty != null) { + String codegenModelName, codegenModelDescription; + + if (codegenModel != null) { + codegenModelName = codegenModel.classname; + codegenModelDescription = codegenModel.description; + } else { + LOGGER.warn("The following schema has undefined (null) baseType. " + + "It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " + + "A correct 'consumes' for form parameters should be " + + "'application/x-www-form-urlencoded' or 'multipart/form-data'"); + LOGGER.warn("schema: " + schema); + LOGGER.warn("codegenModel is null. Default to UNKNOWN_BASE_TYPE"); + codegenModelName = "UNKNOWN_BASE_TYPE"; + codegenModelDescription = "UNKNOWN_DESCRIPTION"; + } + + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = codegenModelName; + } else { + codegenParameter.baseName = bodyParameterName; + } + + codegenParameter.paramName = toParamName(codegenParameter.baseName); + codegenParameter.baseType = codegenModelName; + codegenParameter.dataType = getTypeDeclaration(codegenModelName); + codegenParameter.description = codegenModelDescription; + imports.add(codegenParameter.baseType); + + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + } + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + } + + } else { + // HTTP request body is primitive type (e.g. integer, string, etc) + CodegenProperty codegenProperty = fromProperty("PRIMITIVE_REQUEST_BODY", schema); + if (codegenProperty != null) { + if (StringUtils.isEmpty(bodyParameterName)) { + codegenParameter.baseName = "body"; // default to body + } else { + codegenParameter.baseName = bodyParameterName; + } + codegenParameter.isPrimitiveType = true; + codegenParameter.baseType = codegenProperty.baseType; + codegenParameter.dataType = codegenProperty.dataType; + codegenParameter.description = codegenProperty.description; + codegenParameter.paramName = toParamName(codegenParameter.baseName); + + if (codegenProperty.complexType != null) { + imports.add(codegenProperty.complexType); + } + + } + setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); + // set nullable + setParameterNullable(codegenParameter, codegenProperty); + } + + // set the parameter's example value + // should be overridden by lang codegen + setParameterExampleValue(codegenParameter, body); + + return codegenParameter; + } + + private void setParameterNullable(CodegenParameter parameter, CodegenProperty property) { + parameter.isNullable = property.isNullable; + } + @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isArraySchema(p)) { @@ -770,38 +972,38 @@ public String getTypeDeclaration(Schema p) { return super.getTypeDeclaration(p); } - @Override - public CodegenParameter fromParameter(Parameter param, Set imports) { - CodegenParameter parameter = super.fromParameter(param, imports); - if (!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)) { - - String name = "models::" + getTypeDeclaration(parameter.dataType); - parameter.dataType = name; - parameter.baseType = 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 (!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)) { - - String name = "models::" + getTypeDeclaration(parameter.dataType); - parameter.dataType = name; - parameter.baseType = name; - } - } + // @Override + // public CodegenParameter fromParameter(Parameter param, Set imports) { + // CodegenParameter parameter = super.fromParameter(param, imports); + // if (!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)) { + + // // String name = "models::" + getTypeDeclaration(parameter.dataType); + // // parameter.dataType = name; + // // parameter.baseType = 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 (!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)) { + + // // String name = "models::" + getTypeDeclaration(parameter.dataType); + // // parameter.dataType = name; + // // parameter.baseType = name; + // } + // } @Override public String toInstantiationType(Schema p) { 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 index bfdeae4e3990..5dc3c4790eea 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs @@ -70,7 +70,7 @@ fn main() { match matches.value_of("operation") { Some("XmlPost") => { - let result = core.run(client.xml_post(Some(&Vec::new()))); + let result = core.run(client.xml_post(Some())); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, 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 index b820d1d188a2..c0afac2b393f 100644 --- 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 @@ -29,9 +29,9 @@ impl Server { impl Api for Server where C: Has{ - fn xml_post(&self, string: Option<&Vec>, context: &C) -> Box> { + fn xml_post(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("xml_post({:?}) - X-Span-ID: {:?}", string, context.get().0.clone()); + println!("xml_post({:?}) - X-Span-ID: {:?}", body, 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 index f73afc48da41..198c70595323 100644 --- 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 @@ -245,7 +245,7 @@ impl Api for Client where F: Future + 'static, C: Has { - fn xml_post(&self, param_string: Option<&Vec>, context: &C) -> Box> { + fn xml_post(&self, param_body: Option, context: &C) -> Box> { let uri = format!( @@ -262,7 +262,7 @@ impl Api for Client where // Body parameter - let body = param_string.map(|ref body| { + let body = param_body.map(|ref body| { body.to_xml() }); 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 index 72acd6a055cc..50bcda5fe529 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -50,7 +50,7 @@ pub enum XmlPostResponse { pub trait Api { - fn xml_post(&self, string: Option<&Vec>, context: &C) -> Box>; + fn xml_post(&self, body: Option, context: &C) -> Box>; } @@ -58,7 +58,7 @@ pub trait Api { pub trait ApiNoContext { - fn xml_post(&self, string: Option<&Vec>) -> Box>; + fn xml_post(&self, body: Option) -> Box>; } @@ -77,8 +77,8 @@ impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { - fn xml_post(&self, string: Option<&Vec>) -> Box> { - self.api().xml_post(string, &self.context()) + fn xml_post(&self, body: Option) -> Box> { + self.api().xml_post(body, &self.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 index 0badb391c280..43ba48340874 100644 --- 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 @@ -137,14 +137,14 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_string: Option> = if !body.is_empty() { + let param_body: 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, + Ok(param_body) => param_body, Err(_) => None, } @@ -154,7 +154,7 @@ where }; - Box::new(api_impl.xml_post(param_string.as_ref(), &context) + Box::new(api_impl.xml_post(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -187,7 +187,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter string: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> 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 7f421161b0fb..a25b5b674088 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 @@ -59,28 +59,37 @@ fn main() { .arg(Arg::with_name("operation") .help("Sets the operation to run") .possible_values(&[ + "TestSpecialTags", "FakeOuterBooleanSerialize", "FakeOuterCompositeSerialize", "FakeOuterNumberSerialize", "FakeOuterStringSerialize", + "TestBodyWithQueryParams", + "TestClientModel", "TestEndpointParameters", "TestEnumParameters", "TestJsonFormData", + "TestClassname", + "AddPet", "DeletePet", "FindPetsByStatus", "FindPetsByTags", "GetPetById", + "UpdatePet", "UpdatePetWithForm", "UploadFile", "DeleteOrder", "GetInventory", "GetOrderById", + "PlaceOrder", + "CreateUser", "CreateUsersWithArrayInput", "CreateUsersWithListInput", "DeleteUser", "GetUserByName", "LoginUser", "LogoutUser", + "UpdateUser", ]) .required(true) .index(1)) @@ -121,43 +130,40 @@ fn main() { match matches.value_of("operation") { - // Disabled because there's no example. - // Some("TestSpecialTags") => { - // let result = core.run(client.test_special_tags(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("TestSpecialTags") => { + let result = core.run(client.test_special_tags()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, Some("FakeOuterBooleanSerialize") => { - let result = core.run(client.fake_outer_boolean_serialize(Some(true))); + let result = core.run(client.fake_outer_boolean_serialize(Some())); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterCompositeSerialize") => { - let result = core.run(client.fake_outer_composite_serialize(None)); + let result = core.run(client.fake_outer_composite_serialize(Some())); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterNumberSerialize") => { - let result = core.run(client.fake_outer_number_serialize(Some(1.2))); + let result = core.run(client.fake_outer_number_serialize(Some())); 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(Some())); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("TestBodyWithQueryParams") => { - // let result = core.run(client.test_body_with_query_params("query_example".to_string(), ???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("TestBodyWithQueryParams") => { + let result = core.run(client.test_body_with_query_params("query_example".to_string(), )); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, - // Disabled because there's no example. - // Some("TestClientModel") => { - // let result = core.run(client.test_client_model(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("TestClientModel") => { + let result = core.run(client.test_client_model()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, Some("TestEndpointParameters") => { let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("BYTE_ARRAY_DATA_HERE")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("BINARY_DATA_HERE"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string()))); @@ -180,17 +186,15 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("TestClassname") => { - // let result = core.run(client.test_classname(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("TestClassname") => { + let result = core.run(client.test_classname()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, - // Disabled because there's no example. - // Some("AddPet") => { - // let result = core.run(client.add_pet(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("AddPet") => { + let result = core.run(client.add_pet()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, Some("DeletePet") => { let result = core.run(client.delete_pet(789, Some("api_key_example".to_string()))); @@ -212,11 +216,10 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("UpdatePet") => { - // let result = core.run(client.update_pet(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("UpdatePet") => { + let result = core.run(client.update_pet()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, Some("UpdatePetWithForm") => { let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string()))); @@ -243,17 +246,15 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("PlaceOrder") => { - // let result = core.run(client.place_order(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("PlaceOrder") => { + let result = core.run(client.place_order()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, - // Disabled because there's no example. - // Some("CreateUser") => { - // let result = core.run(client.create_user(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("CreateUser") => { + let result = core.run(client.create_user()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, Some("CreateUsersWithArrayInput") => { let result = core.run(client.create_users_with_array_input(&Vec::new())); @@ -285,11 +286,10 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("UpdateUser") => { - // let result = core.run(client.update_user("username_example".to_string(), ???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("UpdateUser") => { + let result = core.run(client.update_user("username_example".to_string(), )); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, _ => { panic!("Invalid operation provided") 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 1f1d1e00a241..c786dbcd9232 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 @@ -60,51 +60,51 @@ impl Server { impl Api for Server where C: Has{ /// To test special tags - fn test_special_tags(&self, client: models::Client, context: &C) -> Box> { + fn test_special_tags(&self, body: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_special_tags({:?}) - X-Span-ID: {:?}", client, context.get().0.clone()); + println!("test_special_tags({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - 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())) } - fn fake_outer_composite_serialize(&self, outer_composite: Option, context: &C) -> Box> { + fn fake_outer_composite_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", outer_composite, context.get().0.clone()); + println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - 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())) } - fn test_body_with_query_params(&self, query: String, user: models::User, context: &C) -> Box> { + fn test_body_with_query_params(&self, query: String, body: models::User, context: &C) -> Box> { let context = context.clone(); - println!("test_body_with_query_params(\"{}\", {:?}) - X-Span-ID: {:?}", query, user, context.get().0.clone()); + println!("test_body_with_query_params(\"{}\", {}) - X-Span-ID: {:?}", query, body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// To test \"client\" model - fn test_client_model(&self, client: models::Client, context: &C) -> Box> { + fn test_client_model(&self, body: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_client_model({:?}) - X-Span-ID: {:?}", client, context.get().0.clone()); + println!("test_client_model({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -137,16 +137,16 @@ impl Api for Server where C: Has{ } /// To test class name in snake case - fn test_classname(&self, client: models::Client, context: &C) -> Box> { + fn test_classname(&self, body: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_classname({:?}) - X-Span-ID: {:?}", client, context.get().0.clone()); + println!("test_classname({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Add a new pet to the store - fn add_pet(&self, pet: models::Pet, context: &C) -> Box> { + fn add_pet(&self, body: models::Pet, context: &C) -> Box> { let context = context.clone(); - println!("add_pet({:?}) - X-Span-ID: {:?}", pet, context.get().0.clone()); + println!("add_pet({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -179,9 +179,9 @@ impl Api for Server where C: Has{ } /// Update an existing pet - fn update_pet(&self, pet: models::Pet, context: &C) -> Box> { + fn update_pet(&self, body: models::Pet, context: &C) -> Box> { let context = context.clone(); - println!("update_pet({:?}) - X-Span-ID: {:?}", pet, context.get().0.clone()); + println!("update_pet({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -221,16 +221,16 @@ impl Api for Server where C: Has{ } /// Place an order for a pet - fn place_order(&self, order: models::Order, context: &C) -> Box> { + fn place_order(&self, body: models::Order, context: &C) -> Box> { let context = context.clone(); - println!("place_order({:?}) - X-Span-ID: {:?}", order, context.get().0.clone()); + println!("place_order({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Create user - fn create_user(&self, user: models::User, context: &C) -> Box> { + fn create_user(&self, body: models::User, context: &C) -> Box> { let context = context.clone(); - println!("create_user({:?}) - X-Span-ID: {:?}", user, context.get().0.clone()); + println!("create_user({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -277,9 +277,9 @@ impl Api for Server where C: Has{ } /// Updated user - fn update_user(&self, username: String, user: models::User, context: &C) -> Box> { + fn update_user(&self, username: String, body: models::User, context: &C) -> Box> { let context = context.clone(); - println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, user, context.get().0.clone()); + println!("update_user(\"{}\", {}) - X-Span-ID: {:?}", username, 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 33fa4a10774a..6e0adde626f0 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 @@ -276,7 +276,7 @@ impl Api for Client where F: Future + 'static, C: Has + Has>{ - fn test_special_tags(&self, param_client: models::Client, context: &C) -> Box> { + fn test_special_tags(&self, param_body: models::Client, context: &C) -> Box> { let uri = format!( @@ -293,7 +293,7 @@ impl Api for Client where // Body parameter - let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -349,7 +349,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 uri = format!( @@ -425,7 +425,7 @@ if let Some(body) = body { } - fn fake_outer_composite_serialize(&self, param_outer_composite: Option, context: &C) -> Box> { + fn fake_outer_composite_serialize(&self, param_body: Option, context: &C) -> Box> { let uri = format!( @@ -440,7 +440,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = param_outer_composite.map(|ref body| { + let body = param_body.map(|ref body| { serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -499,7 +499,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 uri = format!( @@ -573,7 +573,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 uri = format!( @@ -647,7 +647,7 @@ if let Some(body) = body { } - fn test_body_with_query_params(&self, param_query: String, param_user: models::User, context: &C) -> Box> { + fn test_body_with_query_params(&self, param_query: String, param_body: models::User, context: &C) -> Box> { // Query parameters let query_query = format!("query={query}&", query=param_query.to_string()); @@ -666,7 +666,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -712,7 +712,7 @@ if let Some(body) = body { } - fn test_client_model(&self, param_client: models::Client, context: &C) -> Box> { + fn test_client_model(&self, param_body: models::Client, context: &C) -> Box> { let uri = format!( @@ -727,7 +727,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Patch, uri); - let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -1084,7 +1084,7 @@ if let Some(body) = body { } - fn test_classname(&self, param_client: models::Client, context: &C) -> Box> { + fn test_classname(&self, param_body: models::Client, context: &C) -> Box> { let uri = format!( @@ -1101,7 +1101,7 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -1157,7 +1157,7 @@ if let Some(body) = body { } - fn add_pet(&self, param_pet: models::Pet, context: &C) -> Box> { + fn add_pet(&self, param_body: models::Pet, context: &C) -> Box> { let uri = format!( @@ -1174,7 +1174,7 @@ if let Some(body) = body { // Body parameter - let body = param_pet.to_xml(); + let body = param_body.to_xml(); request.set_body(body.into_bytes()); @@ -1528,7 +1528,7 @@ if let Some(body) = body { } - fn update_pet(&self, param_pet: models::Pet, context: &C) -> Box> { + fn update_pet(&self, param_body: models::Pet, context: &C) -> Box> { let uri = format!( @@ -1543,7 +1543,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = param_pet.to_xml(); + let body = param_body.to_xml(); request.set_body(body.into_bytes()); @@ -1960,7 +1960,7 @@ if let Some(body) = body { } - fn place_order(&self, param_order: models::Order, context: &C) -> Box> { + fn place_order(&self, param_body: models::Order, context: &C) -> Box> { let uri = format!( @@ -1975,7 +1975,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = serde_json::to_string(¶m_order).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -2042,7 +2042,7 @@ if let Some(body) = body { } - fn create_user(&self, param_user: models::User, context: &C) -> Box> { + fn create_user(&self, param_body: models::User, context: &C) -> Box> { let uri = format!( @@ -2059,7 +2059,7 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -2527,7 +2527,7 @@ if let Some(body) = body { } - fn update_user(&self, param_username: String, param_user: models::User, context: &C) -> Box> { + fn update_user(&self, param_username: String, param_body: models::User, context: &C) -> Box> { let uri = format!( @@ -2542,7 +2542,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); + 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 b1fb3e7f5a81..3fabb52a68b1 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 @@ -270,25 +270,25 @@ pub enum UpdateUserResponse { pub trait Api { /// To test special tags - fn test_special_tags(&self, client: models::Client, context: &C) -> Box>; + 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, outer_composite: 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, user: models::User, context: &C) -> Box>; + fn test_body_with_query_params(&self, query: String, body: models::User, context: &C) -> Box>; /// To test \"client\" model - fn test_client_model(&self, client: models::Client, context: &C) -> Box>; + fn test_client_model(&self, body: models::Client, context: &C) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &C) -> Box>; @@ -303,10 +303,10 @@ pub trait Api { fn test_json_form_data(&self, param: String, param2: String, context: &C) -> Box>; /// To test class name in snake case - fn test_classname(&self, client: models::Client, context: &C) -> Box>; + fn test_classname(&self, body: models::Client, context: &C) -> Box>; /// Add a new pet to the store - fn add_pet(&self, pet: models::Pet, context: &C) -> Box>; + fn add_pet(&self, body: models::Pet, context: &C) -> Box>; /// Deletes a pet fn delete_pet(&self, pet_id: i64, api_key: Option, context: &C) -> Box>; @@ -321,7 +321,7 @@ pub trait Api { fn get_pet_by_id(&self, pet_id: i64, context: &C) -> Box>; /// Update an existing pet - fn update_pet(&self, pet: models::Pet, context: &C) -> Box>; + fn update_pet(&self, body: models::Pet, context: &C) -> Box>; /// Updates a pet in the store with form data fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &C) -> Box>; @@ -339,10 +339,10 @@ pub trait Api { fn get_order_by_id(&self, order_id: i64, context: &C) -> Box>; /// Place an order for a pet - fn place_order(&self, order: models::Order, context: &C) -> Box>; + fn place_order(&self, body: models::Order, context: &C) -> Box>; /// Create user - fn create_user(&self, user: models::User, context: &C) -> Box>; + fn create_user(&self, body: models::User, context: &C) -> Box>; /// Creates list of users with given input array fn create_users_with_array_input(&self, user: &Vec, context: &C) -> Box>; @@ -363,7 +363,7 @@ pub trait Api { fn logout_user(&self, context: &C) -> Box>; /// Updated user - fn update_user(&self, username: String, user: models::User, context: &C) -> Box>; + fn update_user(&self, username: String, body: models::User, context: &C) -> Box>; } @@ -371,25 +371,25 @@ pub trait Api { pub trait ApiNoContext { /// To test special tags - fn test_special_tags(&self, client: models::Client) -> Box>; + 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, outer_composite: 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, user: models::User) -> Box>; + fn test_body_with_query_params(&self, query: String, body: models::User) -> Box>; /// To test \"client\" model - fn test_client_model(&self, client: models::Client) -> Box>; + fn test_client_model(&self, body: models::Client) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box>; @@ -404,10 +404,10 @@ pub trait ApiNoContext { fn test_json_form_data(&self, param: String, param2: String) -> Box>; /// To test class name in snake case - fn test_classname(&self, client: models::Client) -> Box>; + fn test_classname(&self, body: models::Client) -> Box>; /// Add a new pet to the store - fn add_pet(&self, pet: models::Pet) -> Box>; + fn add_pet(&self, body: models::Pet) -> Box>; /// Deletes a pet fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box>; @@ -422,7 +422,7 @@ pub trait ApiNoContext { fn get_pet_by_id(&self, pet_id: i64) -> Box>; /// Update an existing pet - fn update_pet(&self, pet: models::Pet) -> Box>; + fn update_pet(&self, body: models::Pet) -> Box>; /// Updates a pet in the store with form data fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box>; @@ -440,10 +440,10 @@ pub trait ApiNoContext { fn get_order_by_id(&self, order_id: i64) -> Box>; /// Place an order for a pet - fn place_order(&self, order: models::Order) -> Box>; + fn place_order(&self, body: models::Order) -> Box>; /// Create user - fn create_user(&self, user: models::User) -> Box>; + fn create_user(&self, body: models::User) -> Box>; /// Creates list of users with given input array fn create_users_with_array_input(&self, user: &Vec) -> Box>; @@ -464,7 +464,7 @@ pub trait ApiNoContext { fn logout_user(&self) -> Box>; /// Updated user - fn update_user(&self, username: String, user: models::User) -> Box>; + fn update_user(&self, username: String, body: models::User) -> Box>; } @@ -483,38 +483,38 @@ impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { /// To test special tags - fn test_special_tags(&self, client: models::Client) -> Box> { - self.api().test_special_tags(client, &self.context()) + fn test_special_tags(&self, body: models::Client) -> Box> { + self.api().test_special_tags(body, &self.context()) } - 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()) } - fn fake_outer_composite_serialize(&self, outer_composite: Option) -> Box> { - self.api().fake_outer_composite_serialize(outer_composite, &self.context()) + fn fake_outer_composite_serialize(&self, body: Option) -> Box> { + self.api().fake_outer_composite_serialize(body, &self.context()) } - 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()) } - fn test_body_with_query_params(&self, query: String, user: models::User) -> Box> { - self.api().test_body_with_query_params(query, user, &self.context()) + fn test_body_with_query_params(&self, query: String, body: models::User) -> Box> { + self.api().test_body_with_query_params(query, body, &self.context()) } /// To test \"client\" model - fn test_client_model(&self, client: models::Client) -> Box> { - self.api().test_client_model(client, &self.context()) + fn test_client_model(&self, body: models::Client) -> Box> { + self.api().test_client_model(body, &self.context()) } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -538,13 +538,13 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// To test class name in snake case - fn test_classname(&self, client: models::Client) -> Box> { - self.api().test_classname(client, &self.context()) + fn test_classname(&self, body: models::Client) -> Box> { + self.api().test_classname(body, &self.context()) } /// Add a new pet to the store - fn add_pet(&self, pet: models::Pet) -> Box> { - self.api().add_pet(pet, &self.context()) + fn add_pet(&self, body: models::Pet) -> Box> { + self.api().add_pet(body, &self.context()) } /// Deletes a pet @@ -568,8 +568,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Update an existing pet - fn update_pet(&self, pet: models::Pet) -> Box> { - self.api().update_pet(pet, &self.context()) + fn update_pet(&self, body: models::Pet) -> Box> { + self.api().update_pet(body, &self.context()) } /// Updates a pet in the store with form data @@ -598,13 +598,13 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Place an order for a pet - fn place_order(&self, order: models::Order) -> Box> { - self.api().place_order(order, &self.context()) + fn place_order(&self, body: models::Order) -> Box> { + self.api().place_order(body, &self.context()) } /// Create user - fn create_user(&self, user: models::User) -> Box> { - self.api().create_user(user, &self.context()) + fn create_user(&self, body: models::User) -> Box> { + self.api().create_user(body, &self.context()) } /// Creates list of users with given input array @@ -638,8 +638,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Updated user - fn update_user(&self, username: String, user: models::User) -> Box> { - self.api().update_user(username, user, &self.context()) + fn update_user(&self, username: String, body: models::User) -> Box> { + self.api().update_user(username, body, &self.context()) } } 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 ca064ca7ef0f..3a0db8e86537 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 @@ -226,7 +226,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_client: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -234,20 +234,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_client) => param_client, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Client - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_client = match param_client { - Some(param_client) => param_client, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Client"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.test_special_tags(param_client, &context) + Box::new(api_impl.test_special_tags(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -288,7 +288,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Client: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -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); @@ -397,7 +397,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_outer_composite: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -405,7 +405,7 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_outer_composite) => param_outer_composite, + Ok(param_body) => param_body, Err(_) => None, } @@ -415,7 +415,7 @@ where }; - Box::new(api_impl.fake_outer_composite_serialize(param_outer_composite, &context) + Box::new(api_impl.fake_outer_composite_serialize(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -456,7 +456,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter OuterComposite: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -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); @@ -662,7 +662,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_user: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -670,20 +670,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_user) => param_user, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter User - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_user = match param_user { - Some(param_user) => param_user, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter User"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.test_body_with_query_params(param_query, param_user, &context) + Box::new(api_impl.test_body_with_query_params(param_query, param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -716,7 +716,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter User: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -741,7 +741,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_client: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -749,20 +749,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_client) => param_client, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Client - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_client = match param_client { - Some(param_client) => param_client, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Client"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.test_client_model(param_client, &context) + Box::new(api_impl.test_client_model(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -803,7 +803,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Client: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -1132,7 +1132,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_client: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -1140,20 +1140,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_client) => param_client, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Client - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_client = match param_client { - Some(param_client) => param_client, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Client"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.test_classname(param_client, &context) + Box::new(api_impl.test_classname(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -1194,7 +1194,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Client: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -1246,27 +1246,27 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_pet: Option = if !body.is_empty() { + let param_body: 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_pet) => param_pet, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Pet - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_pet = match param_pet { - Some(param_pet) => param_pet, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Pet"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.add_pet(param_pet, &context) + Box::new(api_impl.add_pet(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -1299,7 +1299,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Pet: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -1725,27 +1725,27 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_pet: Option = if !body.is_empty() { + let param_body: 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_pet) => param_pet, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Pet - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_pet = match param_pet { - Some(param_pet) => param_pet, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Pet"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.update_pet(param_pet, &context) + Box::new(api_impl.update_pet(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -1792,7 +1792,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Pet: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -2227,7 +2227,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_order: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -2235,20 +2235,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_order) => param_order, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Order - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_order = match param_order { - Some(param_order) => param_order, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Order"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.place_order(param_order, &context) + Box::new(api_impl.place_order(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -2296,7 +2296,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Order: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -2321,7 +2321,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_user: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -2329,20 +2329,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_user) => param_user, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter User - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_user = match param_user { - Some(param_user) => param_user, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter User"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.create_user(param_user, &context) + Box::new(api_impl.create_user(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -2375,7 +2375,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter User: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -2866,7 +2866,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_user: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -2874,20 +2874,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_user) => param_user, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter User - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_user = match param_user { - Some(param_user) => param_user, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter User"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.update_user(param_username, param_user, &context) + Box::new(api_impl.update_user(param_username, param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -2927,7 +2927,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter User: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> diff --git a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index 49cc3b6c1264..a1d413359751 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -19,6 +19,9 @@ paths: content: '*/*': schema: + example: + password: password + id: id properties: id: type: string diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs index fe4ac02db826..96390c56fdba 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs @@ -38,6 +38,7 @@ fn main() { "FileResponseGet", "HtmlPost", "RawJsonGet", + "XmlPost", ]) .required(true) .index(1)) @@ -84,7 +85,7 @@ fn main() { }, Some("DummyPut") => { - let result = core.run(client.dummy_put(None)); + let result = core.run(client.dummy_put(Some())); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, @@ -103,11 +104,10 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("XmlPost") => { - // let result = core.run(client.xml_post(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, + Some("XmlPost") => { + let result = core.run(client.xml_post()); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, _ => { panic!("Invalid operation provided") diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs index b2dd8c281dfa..e043f1be1ea8 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs @@ -41,9 +41,9 @@ impl Api for Server where C: Has{ } - fn dummy_put(&self, inline_object: Option, context: &C) -> Box> { + fn dummy_put(&self, body: Option, context: &C) -> Box> { let context = context.clone(); - println!("dummy_put({:?}) - X-Span-ID: {:?}", inline_object, context.get().0.clone()); + println!("dummy_put({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -69,9 +69,9 @@ impl Api for Server where C: Has{ } /// Test XML - fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box> { + fn xml_post(&self, body: models::XmlObject, context: &C) -> Box> { let context = context.clone(); - println!("xml_post({:?}) - X-Span-ID: {:?}", xml_object, context.get().0.clone()); + println!("xml_post({}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } 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 f6c3b0ebfd99..fcd18a744ba4 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 @@ -306,7 +306,7 @@ impl Api for Client where } - fn dummy_put(&self, param_inline_object: Option, context: &C) -> Box> { + fn dummy_put(&self, param_body: Option, context: &C) -> Box> { let uri = format!( @@ -321,7 +321,7 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = param_inline_object.map(|ref body| { + let body = param_body.map(|ref body| { serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -572,7 +572,7 @@ if let Some(body) = body { } - fn xml_post(&self, param_xml_object: models::XmlObject, context: &C) -> Box> { + fn xml_post(&self, param_body: models::XmlObject, context: &C) -> Box> { let uri = format!( @@ -587,7 +587,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = param_xml_object.to_xml(); + let body = param_body.to_xml(); request.set_body(body.into_bytes()); diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs index b0e454caa8c2..a9fc02d61fa1 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs @@ -83,7 +83,7 @@ pub trait Api { fn dummy_get(&self, context: &C) -> Box>; - fn dummy_put(&self, inline_object: Option, context: &C) -> Box>; + fn dummy_put(&self, body: Option, context: &C) -> Box>; /// Get a file fn file_response_get(&self, context: &C) -> Box>; @@ -95,7 +95,7 @@ pub trait Api { fn raw_json_get(&self, context: &C) -> Box>; /// Test XML - fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box>; + fn xml_post(&self, body: models::XmlObject, context: &C) -> Box>; } @@ -106,7 +106,7 @@ pub trait ApiNoContext { fn dummy_get(&self) -> Box>; - fn dummy_put(&self, inline_object: Option) -> Box>; + fn dummy_put(&self, body: Option) -> Box>; /// Get a file fn file_response_get(&self) -> Box>; @@ -118,7 +118,7 @@ pub trait ApiNoContext { fn raw_json_get(&self) -> Box>; /// Test XML - fn xml_post(&self, xml_object: models::XmlObject) -> Box>; + fn xml_post(&self, body: models::XmlObject) -> Box>; } @@ -142,8 +142,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn dummy_put(&self, inline_object: Option) -> Box> { - self.api().dummy_put(inline_object, &self.context()) + fn dummy_put(&self, body: Option) -> Box> { + self.api().dummy_put(body, &self.context()) } /// Get a file @@ -162,8 +162,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Test XML - fn xml_post(&self, xml_object: models::XmlObject) -> Box> { - self.api().xml_post(xml_object, &self.context()) + fn xml_post(&self, body: models::XmlObject) -> Box> { + self.api().xml_post(body, &self.context()) } } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index e688eb47a669..a0231db9eaf8 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -196,7 +196,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_inline_object: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -204,7 +204,7 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_inline_object) => param_inline_object, + Ok(param_body) => param_body, Err(_) => None, } @@ -214,7 +214,7 @@ where }; - Box::new(api_impl.dummy_put(param_inline_object, &context) + Box::new(api_impl.dummy_put(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -247,7 +247,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter InlineObject: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> @@ -454,27 +454,27 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_xml_object: Option = if !body.is_empty() { + let param_body: 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(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter XmlObject - doesn't match schema: {}", e)))), + Ok(param_body) => param_body, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), } } else { None }; - let param_xml_object = match param_xml_object { - Some(param_xml_object) => param_xml_object, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter XmlObject"))), + let param_body = match param_body { + Some(param_body) => param_body, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), }; - Box::new(api_impl.xml_post(param_xml_object, &context) + Box::new(api_impl.xml_post(param_body, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -518,7 +518,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter XmlObject: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), } }) ) as Box> From 82fa81822303e6fa2c187135ce37950e6fa719f6 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Fri, 14 Dec 2018 14:46:37 +0000 Subject: [PATCH 12/17] Get examples working Rather than re-writing fromRequestBody wholesale, we instead just subclass it. We now run the superclass method. By detecting whether the superclass method has just unwrapped an inner type it should not have, we can then perform the appropriate fiddling to undo the unwrapping. --- .../codegen/languages/RustServerCodegen.java | 233 ++---------------- .../output/openapi-v3/examples/client.rs | 2 +- .../openapi-v3/examples/server_lib/server.rs | 4 +- .../output/openapi-v3/src/client/mod.rs | 4 +- .../rust-server/output/openapi-v3/src/lib.rs | 8 +- .../output/openapi-v3/src/server/mod.rs | 8 +- .../examples/client.rs | 98 ++++---- .../examples/server_lib/server.rs | 40 +-- .../src/client/mod.rs | 40 +-- .../src/lib.rs | 80 +++--- .../src/server/mod.rs | 152 ++++++------ .../output/rust-server-test/api/openapi.yaml | 3 - .../rust-server-test/examples/client.rs | 12 +- .../examples/server_lib/server.rs | 8 +- .../output/rust-server-test/src/client/mod.rs | 8 +- .../output/rust-server-test/src/lib.rs | 16 +- .../output/rust-server-test/src/server/mod.rs | 24 +- 17 files changed, 272 insertions(+), 468 deletions(-) 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 6f0d23d1db41..ef15f9791991 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,6 +17,7 @@ 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; @@ -742,192 +743,31 @@ public boolean isDataTypeFile(final String dataType) { // 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, Map schemas, Set imports, String bodyParameterName) { - if (body == null) { - LOGGER.error("body in fromRequestBody cannot be null!"); - } - CodegenParameter codegenParameter = CodegenModelFactory.newInstance(CodegenModelType.PARAMETER); - codegenParameter.baseName = "UNKNOWN_BASE_NAME"; - codegenParameter.paramName = "UNKNOWN_PARAM_NAME"; - codegenParameter.description = escapeText(body.getDescription()); - codegenParameter.required = body.getRequired() != null ? body.getRequired() : Boolean.FALSE; - codegenParameter.isBodyParam = Boolean.TRUE; - - String name = null; - LOGGER.debug("Request body = " + body); - Schema schema = ModelUtils.getSchemaFromRequestBody(body); - if (StringUtils.isNotBlank(schema.get$ref())) { - name = ModelUtils.getSimpleRef(schema.get$ref()); - // schema = schemas.get(name); - } - - if (ModelUtils.isMapSchema(schema)) { - Schema inner = ModelUtils.getAdditionalProperties(schema); - if (inner == null) { - inner = new StringSchema().description("//TODO automatically added by openapi-generator"); - schema.setAdditionalProperties(inner); - } - CodegenProperty codegenProperty = fromProperty("property", schema); - // only support 1-dimension map only - imports.add(codegenProperty.baseType); - - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = "request_body"; - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.items = codegenProperty.items; - codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; - codegenParameter.dataType = getTypeDeclaration(schema); - codegenParameter.baseType = getSchemaType(inner); - codegenParameter.isContainer = Boolean.TRUE; - codegenParameter.isMapContainer = Boolean.TRUE; - - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - - // set nullable - setParameterNullable(codegenParameter, codegenProperty); - } else if (ModelUtils.isArraySchema(schema)) { - final ArraySchema arraySchema = (ArraySchema) schema; - Schema inner = arraySchema.getItems(); - if (inner == null) { - inner = new StringSchema().description("//TODO automatically added by openapi-generator"); - arraySchema.setItems(inner); - } - CodegenProperty codegenProperty = fromProperty("property", schema); - imports.add(codegenProperty.baseType); - CodegenProperty innerCp = codegenProperty; - CodegenProperty mostInnerItem = innerCp; - // loop through multidimensional array to add proper import - // also find the most inner item - while (innerCp != null) { - if (innerCp.complexType != null) { - imports.add(innerCp.complexType); - } - mostInnerItem = innerCp; - innerCp = innerCp.items; - } - - if (StringUtils.isEmpty(bodyParameterName)) { - if (StringUtils.isEmpty(mostInnerItem.complexType)) { - codegenParameter.baseName = "request_body"; - } else { - codegenParameter.baseName = mostInnerItem.complexType; - } - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toArrayModelParamName(codegenParameter.baseName); - codegenParameter.items = codegenProperty.items; - codegenParameter.mostInnerItems = codegenProperty.mostInnerItems; - codegenParameter.dataType = getTypeDeclaration(arraySchema); - codegenParameter.baseType = getSchemaType(arraySchema); - codegenParameter.isContainer = Boolean.TRUE; - codegenParameter.isListContainer = Boolean.TRUE; - - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); - - while (codegenProperty != null) { - imports.add(codegenProperty.baseType); - codegenProperty = codegenProperty.items; - } - - } else if (ModelUtils.isObjectSchema(schema) || ModelUtils.isComposedSchema(schema)) { - CodegenModel codegenModel = null; - if (StringUtils.isNotBlank(name)) { - schema.setName(name); - codegenModel = fromModel(name, schema, schemas); - } - if (codegenModel != null) { - codegenParameter.isModel = true; - } - - if (codegenModel != null && !codegenModel.emptyVars) { - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = codegenModel.classname; - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenModel.classname; - codegenParameter.dataType = getTypeDeclaration(codegenModel.classname); - codegenParameter.description = codegenModel.description; - imports.add(codegenParameter.baseType); + Schema original_schema = ModelUtils.getSchemaFromRequestBody(body); + CodegenParameter codegenParameter = super.fromRequestBody(body, schemas, 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 { - CodegenProperty codegenProperty = fromProperty("property", schema); - if (ModelUtils.getAdditionalProperties(schema) != null) {// http body is map - LOGGER.error("Map should be supported. Please report to openapi-generator github repo about the issue."); - } else if (codegenProperty != null) { - String codegenModelName, codegenModelDescription; - - if (codegenModel != null) { - codegenModelName = codegenModel.classname; - codegenModelDescription = codegenModel.description; - } else { - LOGGER.warn("The following schema has undefined (null) baseType. " + - "It could be due to form parameter defined in OpenAPI v2 spec with incorrect consumes. " + - "A correct 'consumes' for form parameters should be " + - "'application/x-www-form-urlencoded' or 'multipart/form-data'"); - LOGGER.warn("schema: " + schema); - LOGGER.warn("codegenModel is null. Default to UNKNOWN_BASE_TYPE"); - codegenModelName = "UNKNOWN_BASE_TYPE"; - codegenModelDescription = "UNKNOWN_DESCRIPTION"; - } - - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = codegenModelName; - } else { - codegenParameter.baseName = bodyParameterName; - } - - codegenParameter.paramName = toParamName(codegenParameter.baseName); - codegenParameter.baseType = codegenModelName; - codegenParameter.dataType = getTypeDeclaration(codegenModelName); - codegenParameter.description = codegenModelDescription; - imports.add(codegenParameter.baseType); - - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); - } - } - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); + codegenParameter.example = null; } - - } else { - // HTTP request body is primitive type (e.g. integer, string, etc) - CodegenProperty codegenProperty = fromProperty("PRIMITIVE_REQUEST_BODY", schema); - if (codegenProperty != null) { - if (StringUtils.isEmpty(bodyParameterName)) { - codegenParameter.baseName = "body"; // default to body - } else { - codegenParameter.baseName = bodyParameterName; - } - codegenParameter.isPrimitiveType = true; - codegenParameter.baseType = codegenProperty.baseType; - codegenParameter.dataType = codegenProperty.dataType; - codegenParameter.description = codegenProperty.description; - codegenParameter.paramName = toParamName(codegenParameter.baseName); - - if (codegenProperty.complexType != null) { - imports.add(codegenProperty.complexType); - } - - } - setParameterBooleanFlagWithCodegenProperty(codegenParameter, codegenProperty); - // set nullable - setParameterNullable(codegenParameter, codegenProperty); } - // set the parameter's example value - // should be overridden by lang codegen - setParameterExampleValue(codegenParameter, body); - return codegenParameter; } @@ -972,39 +812,6 @@ public String getTypeDeclaration(Schema p) { return super.getTypeDeclaration(p); } - // @Override - // public CodegenParameter fromParameter(Parameter param, Set imports) { - // CodegenParameter parameter = super.fromParameter(param, imports); - // if (!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)) { - - // // String name = "models::" + getTypeDeclaration(parameter.dataType); - // // parameter.dataType = name; - // // parameter.baseType = 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 (!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)) { - - // // String name = "models::" + getTypeDeclaration(parameter.dataType); - // // parameter.dataType = name; - // // parameter.baseType = name; - // } - // } - @Override public String toInstantiationType(Schema p) { if (ModelUtils.isArraySchema(p)) { 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 index 5dc3c4790eea..f5b92ef792af 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/client.rs @@ -70,7 +70,7 @@ fn main() { match matches.value_of("operation") { Some("XmlPost") => { - let result = core.run(client.xml_post(Some())); + let result = core.run(client.xml_post(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, 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 index c0afac2b393f..f090dd03efd4 100644 --- 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 @@ -29,9 +29,9 @@ impl Server { impl Api for Server where C: Has{ - fn xml_post(&self, body: Option, context: &C) -> Box> { + fn xml_post(&self, string: Option, context: &C) -> Box> { let context = context.clone(); - println!("xml_post({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("xml_post({:?}) - X-Span-ID: {:?}", string, 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 index 198c70595323..d5f302c6e6fe 100644 --- 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 @@ -245,7 +245,7 @@ impl Api for Client where F: Future + 'static, C: Has { - fn xml_post(&self, param_body: Option, context: &C) -> Box> { + fn xml_post(&self, param_string: Option, context: &C) -> Box> { let uri = format!( @@ -262,7 +262,7 @@ impl Api for Client where // Body parameter - let body = param_body.map(|ref body| { + let body = param_string.map(|ref body| { body.to_xml() }); 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 index 50bcda5fe529..40d8344daa37 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -50,7 +50,7 @@ pub enum XmlPostResponse { pub trait Api { - fn xml_post(&self, body: Option, context: &C) -> Box>; + fn xml_post(&self, string: Option, context: &C) -> Box>; } @@ -58,7 +58,7 @@ pub trait Api { pub trait ApiNoContext { - fn xml_post(&self, body: Option) -> Box>; + fn xml_post(&self, string: Option) -> Box>; } @@ -77,8 +77,8 @@ impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { - fn xml_post(&self, body: Option) -> Box> { - self.api().xml_post(body, &self.context()) + fn xml_post(&self, string: Option) -> Box> { + self.api().xml_post(string, &self.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 index 43ba48340874..fa115415a421 100644 --- 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 @@ -137,14 +137,14 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + 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_body) => param_body, + Ok(param_string) => param_string, Err(_) => None, } @@ -154,7 +154,7 @@ where }; - Box::new(api_impl.xml_post(param_body, &context) + 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())); @@ -187,7 +187,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter string: {}", e)))), } }) ) as Box> 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 a25b5b674088..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 @@ -59,37 +59,28 @@ fn main() { .arg(Arg::with_name("operation") .help("Sets the operation to run") .possible_values(&[ - "TestSpecialTags", "FakeOuterBooleanSerialize", "FakeOuterCompositeSerialize", "FakeOuterNumberSerialize", "FakeOuterStringSerialize", - "TestBodyWithQueryParams", - "TestClientModel", "TestEndpointParameters", "TestEnumParameters", "TestJsonFormData", - "TestClassname", - "AddPet", "DeletePet", "FindPetsByStatus", "FindPetsByTags", "GetPetById", - "UpdatePet", "UpdatePetWithForm", "UploadFile", "DeleteOrder", "GetInventory", "GetOrderById", - "PlaceOrder", - "CreateUser", "CreateUsersWithArrayInput", "CreateUsersWithListInput", "DeleteUser", "GetUserByName", "LoginUser", "LogoutUser", - "UpdateUser", ]) .required(true) .index(1)) @@ -130,40 +121,43 @@ fn main() { match matches.value_of("operation") { - Some("TestSpecialTags") => { - let result = core.run(client.test_special_tags()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("TestSpecialTags") => { + // let result = core.run(client.test_special_tags(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, Some("FakeOuterBooleanSerialize") => { - let result = core.run(client.fake_outer_boolean_serialize(Some())); + let result = core.run(client.fake_outer_boolean_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterCompositeSerialize") => { - let result = core.run(client.fake_outer_composite_serialize(Some())); + let result = core.run(client.fake_outer_composite_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterNumberSerialize") => { - let result = core.run(client.fake_outer_number_serialize(Some())); + 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())); + let result = core.run(client.fake_outer_string_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - Some("TestBodyWithQueryParams") => { - let result = core.run(client.test_body_with_query_params("query_example".to_string(), )); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("TestBodyWithQueryParams") => { + // let result = core.run(client.test_body_with_query_params("query_example".to_string(), ???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, - Some("TestClientModel") => { - let result = core.run(client.test_client_model()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("TestClientModel") => { + // let result = core.run(client.test_client_model(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, Some("TestEndpointParameters") => { let result = core.run(client.test_endpoint_parameters(8.14, 1.2, "pattern_without_delimiter_example".to_string(), swagger::ByteArray(Vec::from("BYTE_ARRAY_DATA_HERE")), Some(56), Some(56), Some(789), Some(3.4), Some("string_example".to_string()), Some(swagger::ByteArray(Vec::from("BINARY_DATA_HERE"))), None, None, Some("password_example".to_string()), Some("callback_example".to_string()))); @@ -186,15 +180,17 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - Some("TestClassname") => { - let result = core.run(client.test_classname()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("TestClassname") => { + // let result = core.run(client.test_classname(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, - Some("AddPet") => { - let result = core.run(client.add_pet()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("AddPet") => { + // let result = core.run(client.add_pet(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, Some("DeletePet") => { let result = core.run(client.delete_pet(789, Some("api_key_example".to_string()))); @@ -216,10 +212,11 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - Some("UpdatePet") => { - let result = core.run(client.update_pet()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("UpdatePet") => { + // let result = core.run(client.update_pet(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, Some("UpdatePetWithForm") => { let result = core.run(client.update_pet_with_form(789, Some("name_example".to_string()), Some("status_example".to_string()))); @@ -246,15 +243,17 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - Some("PlaceOrder") => { - let result = core.run(client.place_order()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("PlaceOrder") => { + // let result = core.run(client.place_order(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, - Some("CreateUser") => { - let result = core.run(client.create_user()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("CreateUser") => { + // let result = core.run(client.create_user(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, Some("CreateUsersWithArrayInput") => { let result = core.run(client.create_users_with_array_input(&Vec::new())); @@ -286,10 +285,11 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - Some("UpdateUser") => { - let result = core.run(client.update_user("username_example".to_string(), )); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("UpdateUser") => { + // let result = core.run(client.update_user("username_example".to_string(), ???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, _ => { panic!("Invalid operation provided") 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 c786dbcd9232..a2ef98106ed0 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 @@ -60,9 +60,9 @@ impl Server { impl Api for Server where C: Has{ /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &C) -> Box> { + fn test_special_tags(&self, client: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_special_tags({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("test_special_tags({:?}) - X-Span-ID: {:?}", client, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -74,9 +74,9 @@ impl Api for Server where C: Has{ } - fn fake_outer_composite_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_composite_serialize(&self, outer_composite: Option, context: &C) -> Box> { let context = context.clone(); - println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", outer_composite, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -95,16 +95,16 @@ impl Api for Server where C: Has{ } - fn test_body_with_query_params(&self, query: String, body: models::User, context: &C) -> Box> { + fn test_body_with_query_params(&self, query: String, user: models::User, context: &C) -> Box> { let context = context.clone(); - println!("test_body_with_query_params(\"{}\", {}) - X-Span-ID: {:?}", query, body, context.get().0.clone()); + println!("test_body_with_query_params(\"{}\", {:?}) - X-Span-ID: {:?}", query, user, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &C) -> Box> { + fn test_client_model(&self, client: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_client_model({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("test_client_model({:?}) - X-Span-ID: {:?}", client, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -137,16 +137,16 @@ impl Api for Server where C: Has{ } /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &C) -> Box> { + fn test_classname(&self, client: models::Client, context: &C) -> Box> { let context = context.clone(); - println!("test_classname({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("test_classname({:?}) - X-Span-ID: {:?}", client, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &C) -> Box> { + fn add_pet(&self, pet: models::Pet, context: &C) -> Box> { let context = context.clone(); - println!("add_pet({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("add_pet({:?}) - X-Span-ID: {:?}", pet, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -179,9 +179,9 @@ impl Api for Server where C: Has{ } /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &C) -> Box> { + fn update_pet(&self, pet: models::Pet, context: &C) -> Box> { let context = context.clone(); - println!("update_pet({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("update_pet({:?}) - X-Span-ID: {:?}", pet, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -221,16 +221,16 @@ impl Api for Server where C: Has{ } /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &C) -> Box> { + fn place_order(&self, order: models::Order, context: &C) -> Box> { let context = context.clone(); - println!("place_order({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("place_order({:?}) - X-Span-ID: {:?}", order, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } /// Create user - fn create_user(&self, body: models::User, context: &C) -> Box> { + fn create_user(&self, user: models::User, context: &C) -> Box> { let context = context.clone(); - println!("create_user({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("create_user({:?}) - X-Span-ID: {:?}", user, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -277,9 +277,9 @@ impl Api for Server where C: Has{ } /// Updated user - fn update_user(&self, username: String, body: models::User, context: &C) -> Box> { + fn update_user(&self, username: String, user: models::User, context: &C) -> Box> { let context = context.clone(); - println!("update_user(\"{}\", {}) - X-Span-ID: {:?}", username, body, context.get().0.clone()); + println!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, user, 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 6e0adde626f0..cf7d80043f50 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 @@ -276,7 +276,7 @@ impl Api for Client where F: Future + 'static, C: Has + Has>{ - fn test_special_tags(&self, param_body: models::Client, context: &C) -> Box> { + fn test_special_tags(&self, param_client: models::Client, context: &C) -> Box> { let uri = format!( @@ -293,7 +293,7 @@ impl Api for Client where // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -425,7 +425,7 @@ if let Some(body) = body { } - fn fake_outer_composite_serialize(&self, param_body: Option, context: &C) -> Box> { + fn fake_outer_composite_serialize(&self, param_outer_composite: Option, context: &C) -> Box> { let uri = format!( @@ -440,7 +440,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = param_body.map(|ref body| { + let body = param_outer_composite.map(|ref body| { serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -647,7 +647,7 @@ if let Some(body) = body { } - fn test_body_with_query_params(&self, param_query: String, param_body: models::User, context: &C) -> Box> { + fn test_body_with_query_params(&self, param_query: String, param_user: models::User, context: &C) -> Box> { // Query parameters let query_query = format!("query={query}&", query=param_query.to_string()); @@ -666,7 +666,7 @@ 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"); + let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -712,7 +712,7 @@ if let Some(body) = body { } - fn test_client_model(&self, param_body: models::Client, context: &C) -> Box> { + fn test_client_model(&self, param_client: models::Client, context: &C) -> Box> { let uri = format!( @@ -727,7 +727,7 @@ 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"); + let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -1084,7 +1084,7 @@ if let Some(body) = body { } - fn test_classname(&self, param_body: models::Client, context: &C) -> Box> { + fn test_classname(&self, param_client: models::Client, context: &C) -> Box> { let uri = format!( @@ -1101,7 +1101,7 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_client).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -1157,7 +1157,7 @@ if let Some(body) = body { } - fn add_pet(&self, param_body: models::Pet, context: &C) -> Box> { + fn add_pet(&self, param_pet: models::Pet, context: &C) -> Box> { let uri = format!( @@ -1174,7 +1174,7 @@ if let Some(body) = body { // Body parameter - let body = param_body.to_xml(); + let body = param_pet.to_xml(); request.set_body(body.into_bytes()); @@ -1528,7 +1528,7 @@ if let Some(body) = body { } - fn update_pet(&self, param_body: models::Pet, context: &C) -> Box> { + fn update_pet(&self, param_pet: models::Pet, context: &C) -> Box> { let uri = format!( @@ -1543,7 +1543,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = param_body.to_xml(); + let body = param_pet.to_xml(); request.set_body(body.into_bytes()); @@ -1960,7 +1960,7 @@ if let Some(body) = body { } - fn place_order(&self, param_body: models::Order, context: &C) -> Box> { + fn place_order(&self, param_order: models::Order, context: &C) -> Box> { let uri = format!( @@ -1975,7 +1975,7 @@ 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"); + let body = serde_json::to_string(¶m_order).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -2042,7 +2042,7 @@ if let Some(body) = body { } - fn create_user(&self, param_body: models::User, context: &C) -> Box> { + fn create_user(&self, param_user: models::User, context: &C) -> Box> { let uri = format!( @@ -2059,7 +2059,7 @@ if let Some(body) = body { // Body parameter - let body = serde_json::to_string(¶m_body).expect("impossible to fail to serialize"); + let body = serde_json::to_string(¶m_user).expect("impossible to fail to serialize"); request.set_body(body.into_bytes()); @@ -2527,7 +2527,7 @@ if let Some(body) = body { } - fn update_user(&self, param_username: String, param_body: models::User, context: &C) -> Box> { + fn update_user(&self, param_username: String, param_user: models::User, context: &C) -> Box> { let uri = format!( @@ -2542,7 +2542,7 @@ 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"); + let body = serde_json::to_string(¶m_user).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 3fabb52a68b1..5ac06dbeefc9 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 @@ -270,13 +270,13 @@ pub enum UpdateUserResponse { pub trait Api { /// To test special tags - fn test_special_tags(&self, body: models::Client, context: &C) -> Box>; + fn test_special_tags(&self, client: models::Client, 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_composite_serialize(&self, outer_composite: Option, context: &C) -> Box>; fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box>; @@ -285,10 +285,10 @@ pub trait Api { 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>; + fn test_body_with_query_params(&self, query: String, user: models::User, context: &C) -> Box>; /// To test \"client\" model - fn test_client_model(&self, body: models::Client, context: &C) -> Box>; + fn test_client_model(&self, client: models::Client, context: &C) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option, context: &C) -> Box>; @@ -303,10 +303,10 @@ pub trait Api { fn test_json_form_data(&self, param: String, param2: String, context: &C) -> Box>; /// To test class name in snake case - fn test_classname(&self, body: models::Client, context: &C) -> Box>; + fn test_classname(&self, client: models::Client, context: &C) -> Box>; /// Add a new pet to the store - fn add_pet(&self, body: models::Pet, context: &C) -> Box>; + fn add_pet(&self, pet: models::Pet, context: &C) -> Box>; /// Deletes a pet fn delete_pet(&self, pet_id: i64, api_key: Option, context: &C) -> Box>; @@ -321,7 +321,7 @@ pub trait Api { fn get_pet_by_id(&self, pet_id: i64, context: &C) -> Box>; /// Update an existing pet - fn update_pet(&self, body: models::Pet, context: &C) -> Box>; + fn update_pet(&self, pet: models::Pet, context: &C) -> Box>; /// Updates a pet in the store with form data fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option, context: &C) -> Box>; @@ -339,10 +339,10 @@ pub trait Api { fn get_order_by_id(&self, order_id: i64, context: &C) -> Box>; /// Place an order for a pet - fn place_order(&self, body: models::Order, context: &C) -> Box>; + fn place_order(&self, order: models::Order, context: &C) -> Box>; /// Create user - fn create_user(&self, body: models::User, context: &C) -> Box>; + fn create_user(&self, user: models::User, context: &C) -> Box>; /// Creates list of users with given input array fn create_users_with_array_input(&self, user: &Vec, context: &C) -> Box>; @@ -363,7 +363,7 @@ pub trait Api { fn logout_user(&self, context: &C) -> Box>; /// Updated user - fn update_user(&self, username: String, body: models::User, context: &C) -> Box>; + fn update_user(&self, username: String, user: models::User, context: &C) -> Box>; } @@ -371,13 +371,13 @@ pub trait Api { pub trait ApiNoContext { /// To test special tags - fn test_special_tags(&self, body: models::Client) -> Box>; + fn test_special_tags(&self, client: models::Client) -> Box>; fn fake_outer_boolean_serialize(&self, body: Option) -> Box>; - fn fake_outer_composite_serialize(&self, body: Option) -> Box>; + fn fake_outer_composite_serialize(&self, outer_composite: Option) -> Box>; fn fake_outer_number_serialize(&self, body: Option) -> Box>; @@ -386,10 +386,10 @@ pub trait ApiNoContext { fn fake_outer_string_serialize(&self, body: Option) -> Box>; - fn test_body_with_query_params(&self, query: String, body: models::User) -> Box>; + fn test_body_with_query_params(&self, query: String, user: models::User) -> Box>; /// To test \"client\" model - fn test_client_model(&self, body: models::Client) -> Box>; + fn test_client_model(&self, client: models::Client) -> Box>; /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 fn test_endpoint_parameters(&self, number: f64, double: f64, pattern_without_delimiter: String, byte: swagger::ByteArray, integer: Option, int32: Option, int64: Option, float: Option, string: Option, binary: Option, date: Option>, date_time: Option>, password: Option, callback: Option) -> Box>; @@ -404,10 +404,10 @@ pub trait ApiNoContext { fn test_json_form_data(&self, param: String, param2: String) -> Box>; /// To test class name in snake case - fn test_classname(&self, body: models::Client) -> Box>; + fn test_classname(&self, client: models::Client) -> Box>; /// Add a new pet to the store - fn add_pet(&self, body: models::Pet) -> Box>; + fn add_pet(&self, pet: models::Pet) -> Box>; /// Deletes a pet fn delete_pet(&self, pet_id: i64, api_key: Option) -> Box>; @@ -422,7 +422,7 @@ pub trait ApiNoContext { fn get_pet_by_id(&self, pet_id: i64) -> Box>; /// Update an existing pet - fn update_pet(&self, body: models::Pet) -> Box>; + fn update_pet(&self, pet: models::Pet) -> Box>; /// Updates a pet in the store with form data fn update_pet_with_form(&self, pet_id: i64, name: Option, status: Option) -> Box>; @@ -440,10 +440,10 @@ pub trait ApiNoContext { fn get_order_by_id(&self, order_id: i64) -> Box>; /// Place an order for a pet - fn place_order(&self, body: models::Order) -> Box>; + fn place_order(&self, order: models::Order) -> Box>; /// Create user - fn create_user(&self, body: models::User) -> Box>; + fn create_user(&self, user: models::User) -> Box>; /// Creates list of users with given input array fn create_users_with_array_input(&self, user: &Vec) -> Box>; @@ -464,7 +464,7 @@ pub trait ApiNoContext { fn logout_user(&self) -> Box>; /// Updated user - fn update_user(&self, username: String, body: models::User) -> Box>; + fn update_user(&self, username: String, user: models::User) -> Box>; } @@ -483,8 +483,8 @@ impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { /// To test special tags - fn test_special_tags(&self, body: models::Client) -> Box> { - self.api().test_special_tags(body, &self.context()) + fn test_special_tags(&self, client: models::Client) -> Box> { + self.api().test_special_tags(client, &self.context()) } @@ -493,8 +493,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn fake_outer_composite_serialize(&self, body: Option) -> Box> { - self.api().fake_outer_composite_serialize(body, &self.context()) + fn fake_outer_composite_serialize(&self, outer_composite: Option) -> Box> { + self.api().fake_outer_composite_serialize(outer_composite, &self.context()) } @@ -508,13 +508,13 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn test_body_with_query_params(&self, query: String, body: models::User) -> Box> { - self.api().test_body_with_query_params(query, body, &self.context()) + fn test_body_with_query_params(&self, query: String, user: models::User) -> Box> { + self.api().test_body_with_query_params(query, user, &self.context()) } /// To test \"client\" model - fn test_client_model(&self, body: models::Client) -> Box> { - self.api().test_client_model(body, &self.context()) + fn test_client_model(&self, client: models::Client) -> Box> { + self.api().test_client_model(client, &self.context()) } /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -538,13 +538,13 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// To test class name in snake case - fn test_classname(&self, body: models::Client) -> Box> { - self.api().test_classname(body, &self.context()) + fn test_classname(&self, client: models::Client) -> Box> { + self.api().test_classname(client, &self.context()) } /// Add a new pet to the store - fn add_pet(&self, body: models::Pet) -> Box> { - self.api().add_pet(body, &self.context()) + fn add_pet(&self, pet: models::Pet) -> Box> { + self.api().add_pet(pet, &self.context()) } /// Deletes a pet @@ -568,8 +568,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Update an existing pet - fn update_pet(&self, body: models::Pet) -> Box> { - self.api().update_pet(body, &self.context()) + fn update_pet(&self, pet: models::Pet) -> Box> { + self.api().update_pet(pet, &self.context()) } /// Updates a pet in the store with form data @@ -598,13 +598,13 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Place an order for a pet - fn place_order(&self, body: models::Order) -> Box> { - self.api().place_order(body, &self.context()) + fn place_order(&self, order: models::Order) -> Box> { + self.api().place_order(order, &self.context()) } /// Create user - fn create_user(&self, body: models::User) -> Box> { - self.api().create_user(body, &self.context()) + fn create_user(&self, user: models::User) -> Box> { + self.api().create_user(user, &self.context()) } /// Creates list of users with given input array @@ -638,8 +638,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Updated user - fn update_user(&self, username: String, body: models::User) -> Box> { - self.api().update_user(username, body, &self.context()) + fn update_user(&self, username: String, user: models::User) -> Box> { + self.api().update_user(username, user, &self.context()) } } 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 3a0db8e86537..e51e546514ba 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 @@ -226,7 +226,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_client: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -234,20 +234,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_client) => param_client, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Client - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_client = match param_client { + Some(param_client) => param_client, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Client"))), }; - Box::new(api_impl.test_special_tags(param_body, &context) + Box::new(api_impl.test_special_tags(param_client, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -288,7 +288,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Client: {}", e)))), } }) ) as Box> @@ -397,7 +397,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_outer_composite: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -405,7 +405,7 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, + Ok(param_outer_composite) => param_outer_composite, Err(_) => None, } @@ -415,7 +415,7 @@ where }; - Box::new(api_impl.fake_outer_composite_serialize(param_body, &context) + Box::new(api_impl.fake_outer_composite_serialize(param_outer_composite, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -456,7 +456,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter OuterComposite: {}", e)))), } }) ) as Box> @@ -662,7 +662,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_user: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -670,20 +670,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_user) => param_user, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter User - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_user = match param_user { + Some(param_user) => param_user, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter User"))), }; - Box::new(api_impl.test_body_with_query_params(param_query, param_body, &context) + Box::new(api_impl.test_body_with_query_params(param_query, param_user, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -716,7 +716,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter User: {}", e)))), } }) ) as Box> @@ -741,7 +741,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_client: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -749,20 +749,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_client) => param_client, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Client - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_client = match param_client { + Some(param_client) => param_client, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Client"))), }; - Box::new(api_impl.test_client_model(param_body, &context) + Box::new(api_impl.test_client_model(param_client, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -803,7 +803,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Client: {}", e)))), } }) ) as Box> @@ -1132,7 +1132,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_client: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -1140,20 +1140,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_client) => param_client, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Client - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_client = match param_client { + Some(param_client) => param_client, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Client"))), }; - Box::new(api_impl.test_classname(param_body, &context) + Box::new(api_impl.test_classname(param_client, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -1194,7 +1194,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Client: {}", e)))), } }) ) as Box> @@ -1246,27 +1246,27 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_pet: 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_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_pet) => param_pet, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Pet - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_pet = match param_pet { + Some(param_pet) => param_pet, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Pet"))), }; - Box::new(api_impl.add_pet(param_body, &context) + Box::new(api_impl.add_pet(param_pet, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -1299,7 +1299,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Pet: {}", e)))), } }) ) as Box> @@ -1725,27 +1725,27 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_pet: 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_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_pet) => param_pet, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Pet - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_pet = match param_pet { + Some(param_pet) => param_pet, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Pet"))), }; - Box::new(api_impl.update_pet(param_body, &context) + Box::new(api_impl.update_pet(param_pet, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -1792,7 +1792,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Pet: {}", e)))), } }) ) as Box> @@ -2227,7 +2227,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_order: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -2235,20 +2235,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_order) => param_order, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter Order - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_order = match param_order { + Some(param_order) => param_order, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter Order"))), }; - Box::new(api_impl.place_order(param_body, &context) + Box::new(api_impl.place_order(param_order, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -2296,7 +2296,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter Order: {}", e)))), } }) ) as Box> @@ -2321,7 +2321,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_user: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -2329,20 +2329,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_user) => param_user, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter User - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_user = match param_user { + Some(param_user) => param_user, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter User"))), }; - Box::new(api_impl.create_user(param_body, &context) + Box::new(api_impl.create_user(param_user, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -2375,7 +2375,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter User: {}", e)))), } }) ) as Box> @@ -2866,7 +2866,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_user: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -2874,20 +2874,20 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_user) => param_user, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter User - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_user = match param_user { + Some(param_user) => param_user, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter User"))), }; - Box::new(api_impl.update_user(param_username, param_body, &context) + Box::new(api_impl.update_user(param_username, param_user, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -2927,7 +2927,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter User: {}", e)))), } }) ) as Box> diff --git a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index a1d413359751..49cc3b6c1264 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -19,9 +19,6 @@ paths: content: '*/*': schema: - example: - password: password - id: id properties: id: type: string diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs index 96390c56fdba..fe4ac02db826 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs @@ -38,7 +38,6 @@ fn main() { "FileResponseGet", "HtmlPost", "RawJsonGet", - "XmlPost", ]) .required(true) .index(1)) @@ -85,7 +84,7 @@ fn main() { }, Some("DummyPut") => { - let result = core.run(client.dummy_put(Some())); + let result = core.run(client.dummy_put(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, @@ -104,10 +103,11 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - Some("XmlPost") => { - let result = core.run(client.xml_post()); - println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - }, + // Disabled because there's no example. + // Some("XmlPost") => { + // let result = core.run(client.xml_post(???)); + // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + // }, _ => { panic!("Invalid operation provided") diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs index e043f1be1ea8..b2dd8c281dfa 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs @@ -41,9 +41,9 @@ impl Api for Server where C: Has{ } - fn dummy_put(&self, body: Option, context: &C) -> Box> { + fn dummy_put(&self, inline_object: Option, context: &C) -> Box> { let context = context.clone(); - println!("dummy_put({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("dummy_put({:?}) - X-Span-ID: {:?}", inline_object, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } @@ -69,9 +69,9 @@ impl Api for Server where C: Has{ } /// Test XML - fn xml_post(&self, body: models::XmlObject, context: &C) -> Box> { + fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box> { let context = context.clone(); - println!("xml_post({}) - X-Span-ID: {:?}", body, context.get().0.clone()); + println!("xml_post({:?}) - 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/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index fcd18a744ba4..f6c3b0ebfd99 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 @@ -306,7 +306,7 @@ impl Api for Client where } - fn dummy_put(&self, param_body: Option, context: &C) -> Box> { + fn dummy_put(&self, param_inline_object: Option, context: &C) -> Box> { let uri = format!( @@ -321,7 +321,7 @@ impl Api for Client where let mut request = hyper::Request::new(hyper::Method::Put, uri); - let body = param_body.map(|ref body| { + let body = param_inline_object.map(|ref body| { serde_json::to_string(body).expect("impossible to fail to serialize") }); @@ -572,7 +572,7 @@ if let Some(body) = body { } - fn xml_post(&self, param_body: models::XmlObject, context: &C) -> Box> { + fn xml_post(&self, param_xml_object: models::XmlObject, context: &C) -> Box> { let uri = format!( @@ -587,7 +587,7 @@ if let Some(body) = body { let mut request = hyper::Request::new(hyper::Method::Post, uri); - let body = param_body.to_xml(); + let body = param_xml_object.to_xml(); request.set_body(body.into_bytes()); diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs index a9fc02d61fa1..b0e454caa8c2 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs @@ -83,7 +83,7 @@ pub trait Api { fn dummy_get(&self, context: &C) -> Box>; - fn dummy_put(&self, body: Option, context: &C) -> Box>; + fn dummy_put(&self, inline_object: Option, context: &C) -> Box>; /// Get a file fn file_response_get(&self, context: &C) -> Box>; @@ -95,7 +95,7 @@ pub trait Api { fn raw_json_get(&self, context: &C) -> Box>; /// Test XML - fn xml_post(&self, body: models::XmlObject, context: &C) -> Box>; + fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box>; } @@ -106,7 +106,7 @@ pub trait ApiNoContext { fn dummy_get(&self) -> Box>; - fn dummy_put(&self, body: Option) -> Box>; + fn dummy_put(&self, inline_object: Option) -> Box>; /// Get a file fn file_response_get(&self) -> Box>; @@ -118,7 +118,7 @@ pub trait ApiNoContext { fn raw_json_get(&self) -> Box>; /// Test XML - fn xml_post(&self, body: models::XmlObject) -> Box>; + fn xml_post(&self, xml_object: models::XmlObject) -> Box>; } @@ -142,8 +142,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn dummy_put(&self, body: Option) -> Box> { - self.api().dummy_put(body, &self.context()) + fn dummy_put(&self, inline_object: Option) -> Box> { + self.api().dummy_put(inline_object, &self.context()) } /// Get a file @@ -162,8 +162,8 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } /// Test XML - fn xml_post(&self, body: models::XmlObject) -> Box> { - self.api().xml_post(body, &self.context()) + fn xml_post(&self, xml_object: models::XmlObject) -> Box> { + self.api().xml_post(xml_object, &self.context()) } } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index a0231db9eaf8..e688eb47a669 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -196,7 +196,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_inline_object: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -204,7 +204,7 @@ where warn!("Ignoring unknown field in body: {}", path); unused_elements.push(path.to_string()); }) { - Ok(param_body) => param_body, + Ok(param_inline_object) => param_inline_object, Err(_) => None, } @@ -214,7 +214,7 @@ where }; - Box::new(api_impl.dummy_put(param_body, &context) + Box::new(api_impl.dummy_put(param_inline_object, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -247,7 +247,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter InlineObject: {}", e)))), } }) ) as Box> @@ -454,27 +454,27 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + 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_body) => param_body, - Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter body - doesn't match schema: {}", e)))), + Ok(param_xml_object) => param_xml_object, + Err(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter XmlObject - doesn't match schema: {}", e)))), } } else { None }; - let param_body = match param_body { - Some(param_body) => param_body, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter body"))), + let param_xml_object = match param_xml_object { + Some(param_xml_object) => param_xml_object, + None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter XmlObject"))), }; - Box::new(api_impl.xml_post(param_body, &context) + Box::new(api_impl.xml_post(param_xml_object, &context) .then(move |result| { let mut response = Response::new(); response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); @@ -518,7 +518,7 @@ where }, - Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter body: {}", e)))), + Err(e) => Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't read body parameter XmlObject: {}", e)))), } }) ) as Box> From 0923ee6c94bc7fbd71a2a3e7ded63d64e6f5fbf5 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Fri, 14 Dec 2018 14:51:13 +0000 Subject: [PATCH 13/17] Remove occassionally unnecessary import --- .../rust-server/example-server_lib.mustache | 2 + .../resources/rust-server/models.mustache | 8 +- .../openapi-v3/examples/server_lib/mod.rs | 1 - .../output/openapi-v3/src/models.rs | 3 - .../src/models.rs | 148 +++++++++--------- .../examples/server_lib/mod.rs | 1 - .../output/rust-server-test/src/models.rs | 35 +++-- 7 files changed, 103 insertions(+), 95 deletions(-) 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 4fe43e00ae0e..de067cdfe13c 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -164,7 +164,9 @@ impl {{{classname}}} { } } } -{{/arrayModelType}}{{/dataType}}{{/isEnum}} +{{/arrayModelType}} +{{/dataType}} +{{/isEnum}} {{#usesXml}} impl {{{classname}}} { @@ -184,8 +186,10 @@ impl {{{classname}}} { } } {{/usesXml}} +{{/model}} +{{/models}} -{{/model}}{{/models}}{{#usesXmlNamespaces}} +{{#usesXmlNamespaces}} //XML namespaces pub mod namespaces { lazy_static!{ 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 index 03346a327137..ad8904ca16bd 100644 --- 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 @@ -13,7 +13,6 @@ use std::marker::PhantomData; use hyper; use openapi_v3; use swagger::{Has, XSpanIdString}; -use swagger::auth::Authorization; pub struct NewService{ marker: PhantomData 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 index c9bbd843a17c..9eb38d72c2e3 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -80,7 +80,6 @@ impl ::std::ops::DerefMut for XmlArray { } - impl XmlArray { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -90,7 +89,6 @@ impl XmlArray { } } - #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] #[serde(rename = "another")] pub struct XmlInner(String); @@ -121,7 +119,6 @@ impl ::std::ops::DerefMut for XmlInner { } - impl XmlInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. 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 d5745e49925b..e79c5b667b5a 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 @@ -31,7 +31,6 @@ impl AdditionalPropertiesClass { } } - impl AdditionalPropertiesClass { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -41,7 +40,6 @@ impl AdditionalPropertiesClass { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Animal { #[serde(rename = "className")] @@ -62,7 +60,6 @@ impl Animal { } } - impl Animal { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -72,6 +69,76 @@ impl Animal { } } +#[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 { @@ -99,7 +166,6 @@ impl ApiResponse { } } - impl ApiResponse { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -109,7 +175,6 @@ impl ApiResponse { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ArrayOfArrayOfNumberOnly { #[serde(rename = "ArrayArrayNumber")] @@ -126,7 +191,6 @@ impl ArrayOfArrayOfNumberOnly { } } - impl ArrayOfArrayOfNumberOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -136,7 +200,6 @@ impl ArrayOfArrayOfNumberOnly { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ArrayOfNumberOnly { #[serde(rename = "ArrayNumber")] @@ -153,7 +216,6 @@ impl ArrayOfNumberOnly { } } - impl ArrayOfNumberOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -163,7 +225,6 @@ impl ArrayOfNumberOnly { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ArrayTest { #[serde(rename = "array_of_string")] @@ -196,7 +257,6 @@ impl ArrayTest { } } - impl ArrayTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -206,7 +266,6 @@ impl ArrayTest { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Capitalization { #[serde(rename = "smallCamel")] @@ -229,7 +288,7 @@ pub struct Capitalization { #[serde(skip_serializing_if="Option::is_none")] pub sca_eth_flow_points: Option, - /// Name of the pet + /// Name of the pet #[serde(rename = "ATT_NAME")] #[serde(skip_serializing_if="Option::is_none")] pub att_name: Option, @@ -249,7 +308,6 @@ impl Capitalization { } } - impl Capitalization { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -259,7 +317,6 @@ impl Capitalization { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Cat { #[serde(rename = "className")] @@ -285,7 +342,6 @@ impl Cat { } } - impl Cat { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -295,7 +351,6 @@ impl Cat { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Category")] pub struct Category { @@ -318,7 +373,6 @@ impl Category { } } - impl Category { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -328,7 +382,6 @@ impl Category { } } - /// Model for testing model with \"_class\" property #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ClassModel { @@ -346,7 +399,6 @@ impl ClassModel { } } - impl ClassModel { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -356,7 +408,6 @@ impl ClassModel { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Client { #[serde(rename = "client")] @@ -373,7 +424,6 @@ impl Client { } } - impl Client { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -383,7 +433,6 @@ impl Client { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Dog { #[serde(rename = "className")] @@ -409,7 +458,6 @@ impl Dog { } } - impl Dog { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -419,7 +467,6 @@ impl Dog { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct EnumArrays { // Note: inline enums are not fully supported by openapi-generator @@ -449,7 +496,6 @@ impl EnumArrays { } } - impl EnumArrays { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -459,14 +505,13 @@ impl EnumArrays { } } - /// 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. #[allow(non_camel_case_types)] #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize, Eq, Ord)] -pub enum EnumClass { +pub enum EnumClass { #[serde(rename = "_abc")] _ABC, #[serde(rename = "-efg")] @@ -477,7 +522,7 @@ pub enum EnumClass { impl ::std::fmt::Display for EnumClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { + match *self { EnumClass::_ABC => write!(f, "{}", "_abc"), EnumClass::_EFG => write!(f, "{}", "-efg"), EnumClass::_XYZ_ => write!(f, "{}", "(xyz)"), @@ -497,7 +542,6 @@ 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. @@ -507,7 +551,6 @@ impl EnumClass { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct EnumTest { // Note: inline enums are not fully supported by openapi-generator @@ -547,7 +590,6 @@ impl EnumTest { } } - impl EnumTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -557,7 +599,6 @@ impl EnumTest { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct FormatTest { #[serde(rename = "integer")] @@ -630,7 +671,6 @@ impl FormatTest { } } - impl FormatTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -640,7 +680,6 @@ impl FormatTest { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct HasOnlyReadOnly { #[serde(rename = "bar")] @@ -662,7 +701,6 @@ impl HasOnlyReadOnly { } } - impl HasOnlyReadOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -672,7 +710,6 @@ impl HasOnlyReadOnly { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct List { #[serde(rename = "123-list")] @@ -689,7 +726,6 @@ impl List { } } - impl List { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -699,7 +735,6 @@ impl List { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MapTest { #[serde(rename = "map_map_of_string")] @@ -728,7 +763,6 @@ impl MapTest { } } - impl MapTest { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -738,7 +772,6 @@ impl MapTest { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MixedPropertiesAndAdditionalPropertiesClass { #[serde(rename = "uuid")] @@ -765,7 +798,6 @@ impl MixedPropertiesAndAdditionalPropertiesClass { } } - impl MixedPropertiesAndAdditionalPropertiesClass { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -775,7 +807,6 @@ impl MixedPropertiesAndAdditionalPropertiesClass { } } - /// Model for testing model name starting with number #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Name")] @@ -799,7 +830,6 @@ impl Model200Response { } } - impl Model200Response { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -809,7 +839,6 @@ impl Model200Response { } } - /// Model for testing reserved words #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Return")] @@ -828,7 +857,6 @@ impl ModelReturn { } } - impl ModelReturn { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -838,7 +866,6 @@ impl ModelReturn { } } - /// Model for testing model name same as property name #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Name")] @@ -871,7 +898,6 @@ impl Name { } } - impl Name { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -881,7 +907,6 @@ impl Name { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct NumberOnly { #[serde(rename = "JustNumber")] @@ -898,7 +923,6 @@ impl NumberOnly { } } - impl NumberOnly { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -908,7 +932,6 @@ impl NumberOnly { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Order")] pub struct Order { @@ -953,7 +976,6 @@ impl Order { } } - impl Order { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -963,7 +985,6 @@ impl Order { } } - #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct OuterBoolean(bool); @@ -994,7 +1015,6 @@ 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. @@ -1004,7 +1024,6 @@ impl OuterBoolean { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct OuterComposite { #[serde(rename = "my_number")] @@ -1031,7 +1050,6 @@ impl OuterComposite { } } - impl OuterComposite { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -1041,14 +1059,13 @@ impl OuterComposite { } } - /// 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. #[allow(non_camel_case_types)] #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize, Eq, Ord)] -pub enum OuterEnum { +pub enum OuterEnum { #[serde(rename = "placed")] PLACED, #[serde(rename = "approved")] @@ -1059,7 +1076,7 @@ pub enum OuterEnum { impl ::std::fmt::Display for OuterEnum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { + match *self { OuterEnum::PLACED => write!(f, "{}", "placed"), OuterEnum::APPROVED => write!(f, "{}", "approved"), OuterEnum::DELIVERED => write!(f, "{}", "delivered"), @@ -1079,7 +1096,6 @@ 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. @@ -1089,7 +1105,6 @@ impl OuterEnum { } } - #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct OuterNumber(f64); @@ -1120,7 +1135,6 @@ 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. @@ -1130,7 +1144,6 @@ impl OuterNumber { } } - #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] pub struct OuterString(String); @@ -1161,7 +1174,6 @@ 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. @@ -1171,7 +1183,6 @@ impl OuterString { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Pet")] pub struct Pet { @@ -1214,7 +1225,6 @@ impl Pet { } } - impl Pet { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -1224,7 +1234,6 @@ impl Pet { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ReadOnlyFirst { #[serde(rename = "bar")] @@ -1246,7 +1255,6 @@ impl ReadOnlyFirst { } } - impl ReadOnlyFirst { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -1256,7 +1264,6 @@ impl ReadOnlyFirst { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "$special[model.name]")] pub struct SpecialModelName { @@ -1274,7 +1281,6 @@ impl SpecialModelName { } } - impl SpecialModelName { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -1284,7 +1290,6 @@ impl SpecialModelName { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "Tag")] pub struct Tag { @@ -1307,7 +1312,6 @@ impl Tag { } } - impl Tag { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -1317,7 +1321,6 @@ impl Tag { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "User")] pub struct User { @@ -1371,7 +1374,6 @@ impl User { } } - impl User { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. 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/models.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs index 18b83fabcd21..0696c0b77886 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 @@ -32,7 +32,6 @@ impl ANullableContainer { } } - impl ANullableContainer { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -42,6 +41,26 @@ impl ANullableContainer { } } +/// An additionalPropertiesObject +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct AdditionalPropertiesObject { +} + +impl AdditionalPropertiesObject { + pub fn new() -> AdditionalPropertiesObject { + AdditionalPropertiesObject { + } + } +} + +impl AdditionalPropertiesObject { + /// 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 InlineObject { @@ -63,7 +82,6 @@ impl InlineObject { } } - impl InlineObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -73,7 +91,6 @@ impl InlineObject { } } - /// An object of objects #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjects { @@ -91,7 +108,6 @@ impl ObjectOfObjects { } } - impl ObjectOfObjects { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -101,7 +117,6 @@ impl ObjectOfObjects { } } - #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjectsInner { #[serde(rename = "optional_thing")] @@ -122,7 +137,6 @@ impl ObjectOfObjectsInner { } } - impl ObjectOfObjectsInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -132,7 +146,6 @@ impl ObjectOfObjectsInner { } } - /// An XML list with items directly defined // Utility function for wrapping list elements when serializing xml fn wrap_in_xml_list_inner(item: &Vec, serializer: S) -> Result @@ -204,7 +217,6 @@ impl ::std::ops::DerefMut for XmlList { } - impl XmlList { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -214,7 +226,6 @@ impl XmlList { } } - /// An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct XmlListRef(Vec); @@ -278,7 +289,6 @@ impl ::std::ops::DerefMut for XmlListRef { } - impl XmlListRef { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -288,7 +298,6 @@ impl XmlListRef { } } - #[derive(Debug, Clone, PartialEq, PartialOrd, Serialize, Deserialize)] #[serde(rename = "xml_list_ref_inner")] pub struct XmlListRefInner(String); @@ -319,7 +328,6 @@ impl ::std::ops::DerefMut for XmlListRefInner { } - impl XmlListRefInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -329,7 +337,6 @@ impl XmlListRefInner { } } - /// An XML object #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "an_xml_object")] @@ -348,7 +355,6 @@ impl XmlObject { } } - impl XmlObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. @@ -361,7 +367,6 @@ impl XmlObject { } } - //XML namespaces pub mod namespaces { lazy_static!{ From 85840acaabb8e53b1d5a2ac21779df69ac1e79e7 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Mon, 17 Dec 2018 10:24:41 +0000 Subject: [PATCH 14/17] Remove snake_case warning --- .../resources/rust-server/models.mustache | 2 +- .../output/openapi-v3/src/models.rs | 4 +- .../src/models.rs | 72 +++++++++---------- .../output/rust-server-test/src/models.rs | 18 ++--- 4 files changed, 48 insertions(+), 48 deletions(-) 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 de067cdfe13c..878af480f699 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -172,7 +172,7 @@ impl {{{classname}}} { impl {{{classname}}} { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { {{#xmlNamespace}} let mut namespaces = BTreeMap::new(); 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 index 9eb38d72c2e3..23f230cc53bc 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -83,7 +83,7 @@ impl ::std::ops::DerefMut for XmlArray { impl XmlArray { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -122,7 +122,7 @@ impl ::std::ops::DerefMut for XmlInner { impl XmlInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] 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/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index e79c5b667b5a..5ce8be41b6ca 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 @@ -34,7 +34,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -63,7 +63,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -134,7 +134,7 @@ impl ::std::ops::DerefMut for AnimalFarm { impl AnimalFarm { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -169,7 +169,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -194,7 +194,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -219,7 +219,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -260,7 +260,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -311,7 +311,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -345,7 +345,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -376,7 +376,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -402,7 +402,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -427,7 +427,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -461,7 +461,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -499,7 +499,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -545,7 +545,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -593,7 +593,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -674,7 +674,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -704,7 +704,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -729,7 +729,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -766,7 +766,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -801,7 +801,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -833,7 +833,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -860,7 +860,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -901,7 +901,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -926,7 +926,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -979,7 +979,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1018,7 +1018,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1053,7 +1053,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1099,7 +1099,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1138,7 +1138,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1177,7 +1177,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1228,7 +1228,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1258,7 +1258,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1284,7 +1284,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1315,7 +1315,7 @@ 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)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -1377,7 +1377,7 @@ 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)] + #[allow(dead_code, non_snake_case)] 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/rust-server-test/src/models.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs index 0696c0b77886..02bc9d18b498 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 @@ -35,7 +35,7 @@ impl ANullableContainer { impl ANullableContainer { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -56,7 +56,7 @@ impl AdditionalPropertiesObject { impl AdditionalPropertiesObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -85,7 +85,7 @@ impl InlineObject { impl InlineObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -111,7 +111,7 @@ impl ObjectOfObjects { impl ObjectOfObjects { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -140,7 +140,7 @@ impl ObjectOfObjectsInner { impl ObjectOfObjectsInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -220,7 +220,7 @@ impl ::std::ops::DerefMut for XmlList { impl XmlList { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -292,7 +292,7 @@ impl ::std::ops::DerefMut for XmlListRef { impl XmlListRef { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -331,7 +331,7 @@ impl ::std::ops::DerefMut for XmlListRefInner { impl XmlListRefInner { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") } @@ -358,7 +358,7 @@ impl XmlObject { impl XmlObject { /// Helper function to allow us to convert this model to an XML string. /// Will panic if serialisation fails. - #[allow(dead_code)] + #[allow(dead_code, non_snake_case)] pub(crate) fn to_xml(&self) -> String { let mut namespaces = BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. From bed38d5164961a128a207a8466fca853ad882ea9 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 18 Dec 2018 11:38:37 +0000 Subject: [PATCH 15/17] Remove dead function --- .../org/openapitools/codegen/languages/RustServerCodegen.java | 4 ---- 1 file changed, 4 deletions(-) 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 ef15f9791991..d17202594a7a 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 @@ -771,10 +771,6 @@ public CodegenParameter fromRequestBody(RequestBody body, Map sc return codegenParameter; } - private void setParameterNullable(CodegenParameter parameter, CodegenProperty property) { - parameter.isNullable = property.isNullable; - } - @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isArraySchema(p)) { From 4b1047e049b3dc2cfcabfca8cd154bffa7823b85 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 18 Dec 2018 11:44:04 +0000 Subject: [PATCH 16/17] Move all rust-server XML examples to one sample Meaning that the other can test our behaviour in the absence of XML. --- .../resources/2_0/rust-server/openapi-v3.yaml | 13 + .../2_0/rust-server/rust-server-test.yaml | 47 --- .../output/openapi-v3/api/openapi.yaml | 13 + .../output/openapi-v3/src/client/mod.rs | 18 +- .../rust-server/output/openapi-v3/src/lib.rs | 2 +- .../output/openapi-v3/src/mimetypes.rs | 4 + .../output/openapi-v3/src/models.rs | 115 +++---- .../output/openapi-v3/src/server/mod.rs | 11 + .../src/models.rs | 81 +---- .../output/rust-server-test/Cargo.toml | 6 +- .../output/rust-server-test/README.md | 1 - .../output/rust-server-test/api/openapi.yaml | 41 --- .../rust-server-test/examples/client.rs | 9 +- .../examples/server_lib/server.rs | 10 +- .../output/rust-server-test/src/client/mod.rs | 78 +---- .../output/rust-server-test/src/lib.rs | 19 +- .../output/rust-server-test/src/mimetypes.rs | 8 - .../output/rust-server-test/src/models.rs | 282 +----------------- .../output/rust-server-test/src/server/mod.rs | 101 +------ 19 files changed, 110 insertions(+), 749 deletions(-) diff --git a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml index db3a680479b3..73345b35ca22 100644 --- a/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml @@ -14,6 +14,10 @@ paths: responses: 201: description: OK + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlObject' components: schemas: XmlArray: @@ -28,4 +32,13 @@ components: type: string xml: name: another + XmlObject: + description: An XML object + type: object + properties: + inner: + type: string + xml: + name: an_xml_object + namespace: foo.bar 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 8e21ed168a1c..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,24 +52,6 @@ paths: description: Success schema: type: object - /xml: - post: - summary: Test XML - consumes: - - application/xml - produces: - - application/xml - parameters: - - in: body - name: body - required: true - schema: - $ref: '#/definitions/XmlObject' - responses: - 200: - description: Success - schema: - $ref: '#/definitions/XmlObject' # Requests with arbitrary JSON currently fail. # post: @@ -133,35 +115,6 @@ definitions: type: string optional_thing: type: integer - XmlObject: - description: An XML object - type: object - properties: - inner: - type: string - xml: - name: an_xml_object - namespace: foo.bar - XmlList: - description: An XML list with items directly defined - type: array - xml: - wrapped: true - items: - type: string - xml: - name: xml_list_inner - XmlListRef: - description: An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. - type: array - xml: - wrapped: true - items: - $ref: '#/definitions/XmlListRefInner' - XmlListRefInner: - type: string - xml: - name: xml_list_ref_inner # Currently broken - see https://github.com/OpenAPITools/openapi-generator/issues/8 # ArrayOfObjects: # description: An array of objects 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 index f782d3cdfbca..e4c69b268b0d 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -15,6 +15,10 @@ paths: $ref: '#/components/schemas/XmlArray' responses: 201: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlObject' description: OK components: schemas: @@ -28,4 +32,13 @@ components: type: string xml: name: another + XmlObject: + description: An XML object + properties: + inner: + type: string + type: object + xml: + name: an_xml_object + namespace: foo.bar 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 index d5f302c6e6fe..fdba488a4873 100644 --- 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 @@ -281,9 +281,21 @@ if let Some(body) = body { 201 => { let body = response.body(); Box::new( - - future::ok( - XmlPostResponse::OK + body + .concat2() + .map_err(|e| ApiError(format!("Failed to read response: {}", e))) + .and_then(|body| str::from_utf8(&body) + .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) + .and_then(|body| + + // ToDo: this will move to swagger-rs and become a standard From conversion trait + // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream + serde_xml_rs::from_str::(body) + .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) + + )) + .map(move |body| + XmlPostResponse::OK(body) ) ) as Box> }, 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 index 40d8344daa37..cb3a5294dcde 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/lib.rs @@ -42,7 +42,7 @@ pub const API_VERSION: &'static str = "1.0.7"; #[derive(Debug, PartialEq)] pub enum XmlPostResponse { /// OK - OK , + OK ( models::XmlObject ) , } 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 index 00cc6ccaa80c..0fafb70eeb05 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs @@ -4,6 +4,10 @@ pub mod responses { use hyper::mime::*; // The macro is called per-operation to beat the recursion limit + /// Create Mime objects for the response content types for XmlPost + lazy_static! { + pub static ref XML_POST_OK: 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 index 23f230cc53bc..8b1f0282c568 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -10,85 +10,6 @@ use models; use swagger; -// Utility function for wrapping list elements when serializing xml -fn wrap_in_another(item: &Vec, serializer: S) -> Result -where - S: Serializer, -{ - serde_xml_rs::wrap_primitives(item, serializer, "another") -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct XmlArray(#[serde(serialize_with = "wrap_in_another")]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, non_snake_case)] - 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 = "another")] pub struct XmlInner(String); @@ -128,3 +49,39 @@ impl XmlInner { } } +/// An XML object +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename = "an_xml_object")] +pub struct XmlObject { + #[serde(rename = "inner")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner: Option, + +} + +impl XmlObject { + pub fn new() -> XmlObject { + XmlObject { + inner: None, + } + } +} + +impl XmlObject { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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(), models::namespaces::XMLOBJECT.clone()); + serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") + } +} + +//XML namespaces +pub mod namespaces { + lazy_static!{ + pub static ref XMLOBJECT: String = "foo.bar".to_string(); + } +} 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 index fa115415a421..151a74857f51 100644 --- 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 @@ -167,10 +167,21 @@ where Ok(rsp) => match rsp { XmlPostResponse::OK + (body) + => { response.set_status(StatusCode::try_from(201).unwrap()); + response.headers_mut().set(ContentType(mimetypes::responses::XML_POST_OK.clone())); + + + let mut namespaces = BTreeMap::new(); + // An empty string is used to indicate a global namespace in xmltree. + namespaces.insert("".to_string(), models::namespaces::XMLOBJECT.clone()); + let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + + response.set_body(body); }, }, Err(_) => { 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 5ce8be41b6ca..e08ead0ae304 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 @@ -69,77 +69,6 @@ impl Animal { } } -#[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, non_snake_case)] - 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")] @@ -288,7 +217,7 @@ pub struct Capitalization { #[serde(skip_serializing_if="Option::is_none")] pub sca_eth_flow_points: Option, - /// Name of the pet + /// Name of the pet #[serde(rename = "ATT_NAME")] #[serde(skip_serializing_if="Option::is_none")] pub att_name: Option, @@ -511,7 +440,7 @@ impl EnumArrays { #[allow(non_camel_case_types)] #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize, Eq, Ord)] -pub enum EnumClass { +pub enum EnumClass { #[serde(rename = "_abc")] _ABC, #[serde(rename = "-efg")] @@ -522,7 +451,7 @@ pub enum EnumClass { impl ::std::fmt::Display for EnumClass { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { + match *self { EnumClass::_ABC => write!(f, "{}", "_abc"), EnumClass::_EFG => write!(f, "{}", "-efg"), EnumClass::_XYZ_ => write!(f, "{}", "(xyz)"), @@ -1065,7 +994,7 @@ impl OuterComposite { #[allow(non_camel_case_types)] #[repr(C)] #[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Serialize, Deserialize, Eq, Ord)] -pub enum OuterEnum { +pub enum OuterEnum { #[serde(rename = "placed")] PLACED, #[serde(rename = "approved")] @@ -1076,7 +1005,7 @@ pub enum OuterEnum { impl ::std::fmt::Display for OuterEnum { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { - match *self { + match *self { OuterEnum::PLACED => write!(f, "{}", "placed"), OuterEnum::APPROVED => write!(f, "{}", "approved"), OuterEnum::DELIVERED => write!(f, "{}", "delivered"), diff --git a/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml b/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml index 948a9bb42b80..3a837e477ea4 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml +++ b/samples/server/petstore/rust-server/output/rust-server-test/Cargo.toml @@ -7,8 +7,8 @@ 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"] +client = ["serde_json", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"] +server = ["serde_json", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"] [dependencies] # Required by example server. @@ -41,7 +41,7 @@ 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" 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 c38ed5a32efc..49af89f0718f 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 @@ -60,7 +60,6 @@ cargo run --example client DummyPut cargo run --example client FileResponseGet cargo run --example client HtmlPost cargo run --example client RawJsonGet -cargo run --example client XmlPost ``` ### HTTPS diff --git a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml index 49cc3b6c1264..10a6a87b9ddb 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/rust-server-test/api/openapi.yaml @@ -69,22 +69,6 @@ paths: type: object description: Success summary: Get an arbitrary JSON blob. - /xml: - post: - requestBody: - content: - application/xml: - schema: - $ref: '#/components/schemas/XmlObject' - required: true - responses: - 200: - content: - application/xml: - schema: - $ref: '#/components/schemas/XmlObject' - description: Success - summary: Test XML components: requestBodies: nested_response: @@ -129,19 +113,6 @@ components: inner: $ref: '#/components/schemas/ObjectOfObjects_inner' type: object - XmlListRefInner: - type: string - xml: - name: xml_list_ref_inner - XmlObject: - description: An XML object - properties: - inner: - type: string - type: object - xml: - name: an_xml_object - namespace: foo.bar inline_object: properties: id: @@ -159,16 +130,4 @@ components: type: string required: - required_thing - XmlListRef: - description: An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. - items: - $ref: '#/components/schemas/XmlListRefInner' - type: array - XmlList: - description: An XML list with items directly defined - items: - type: string - xml: - name: xml_list_inner - type: array diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs index fe4ac02db826..54377a219dc1 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/client.rs @@ -23,8 +23,7 @@ use rust_server_test::{ApiNoContext, ContextWrapperExt, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse, - XmlPostResponse + RawJsonGetResponse }; use clap::{App, Arg}; @@ -103,12 +102,6 @@ fn main() { println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, - // Disabled because there's no example. - // Some("XmlPost") => { - // let result = core.run(client.xml_post(???)); - // println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); - // }, - _ => { panic!("Invalid operation provided") } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs index b2dd8c281dfa..a1067282c4b3 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/server.rs @@ -15,8 +15,7 @@ use rust_server_test::{Api, ApiError, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse, - XmlPostResponse + RawJsonGetResponse }; use rust_server_test::models; @@ -68,11 +67,4 @@ impl Api for Server where C: Has{ Box::new(futures::failed("Generic failure".into())) } - /// Test XML - fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box> { - let context = context.clone(); - println!("xml_post({:?}) - 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/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index f6c3b0ebfd99..1f88433461f2 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 @@ -29,7 +29,7 @@ use std::str::FromStr; use mimetypes; use serde_json; -use serde_xml_rs; + #[allow(unused_imports)] use std::collections::{HashMap, BTreeMap}; @@ -43,8 +43,7 @@ use {Api, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse, - XmlPostResponse + RawJsonGetResponse }; use models; @@ -572,79 +571,6 @@ if let Some(body) = body { } - fn xml_post(&self, param_xml_object: models::XmlObject, context: &C) -> Box> { - - - let 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_xml_object.to_xml(); - - 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() { - 200 => { - let body = response.body(); - Box::new( - body - .concat2() - .map_err(|e| ApiError(format!("Failed to read response: {}", e))) - .and_then(|body| str::from_utf8(&body) - .map_err(|e| ApiError(format!("Response was not valid UTF8: {}", e))) - .and_then(|body| - - // ToDo: this will move to swagger-rs and become a standard From conversion trait - // once https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream - serde_xml_rs::from_str::(body) - .map_err(|e| ApiError(format!("Response body did not match the schema: {}", e))) - - )) - .map(move |body| - XmlPostResponse::Success(body) - ) - ) 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)] diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs index b0e454caa8c2..b319918858d2 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/lib.rs @@ -4,7 +4,7 @@ extern crate serde; extern crate serde_derive; extern crate serde_json; -extern crate serde_xml_rs; + extern crate futures; extern crate chrono; #[macro_use] @@ -69,12 +69,6 @@ pub enum RawJsonGetResponse { Success ( serde_json::Value ) , } -#[derive(Debug, PartialEq)] -pub enum XmlPostResponse { - /// Success - Success ( models::XmlObject ) , -} - /// API pub trait Api { @@ -94,9 +88,6 @@ pub trait Api { /// Get an arbitrary JSON blob. fn raw_json_get(&self, context: &C) -> Box>; - /// Test XML - fn xml_post(&self, xml_object: models::XmlObject, context: &C) -> Box>; - } /// API without a `Context` @@ -117,9 +108,6 @@ pub trait ApiNoContext { /// Get an arbitrary JSON blob. fn raw_json_get(&self) -> Box>; - /// Test XML - fn xml_post(&self, xml_object: models::XmlObject) -> Box>; - } /// Trait to extend an API to make it easy to bind it to a context. @@ -161,11 +149,6 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { self.api().raw_json_get(&self.context()) } - /// Test XML - fn xml_post(&self, xml_object: models::XmlObject) -> Box> { - self.api().xml_post(xml_object, &self.context()) - } - } #[cfg(feature = "client")] diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs index a980535131e3..01fdce1e9025 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/mimetypes.rs @@ -16,10 +16,6 @@ pub mod responses { lazy_static! { pub static ref RAW_JSON_GET_SUCCESS: Mime = "*/*".parse().unwrap(); } - /// Create Mime objects for the response content types for XmlPost - lazy_static! { - pub static ref XML_POST_SUCCESS: Mime = "application/xml".parse().unwrap(); - } } @@ -33,9 +29,5 @@ pub mod requests { lazy_static! { pub static ref HTML_POST: Mime = "text/html".parse().unwrap(); } - /// Create Mime objects for the request content types for XmlPost - lazy_static! { - pub static ref XML_POST: Mime = "application/xml".parse().unwrap(); - } } 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 02bc9d18b498..f5b2e21a0eda 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,7 @@ extern crate chrono; extern crate uuid; -use serde_xml_rs; + use serde::ser::Serializer; use std::collections::{HashMap, BTreeMap}; @@ -32,35 +32,6 @@ impl ANullableContainer { } } -impl ANullableContainer { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - pub(crate) fn to_xml(&self) -> String { - serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") - } -} - -/// An additionalPropertiesObject -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct AdditionalPropertiesObject { -} - -impl AdditionalPropertiesObject { - pub fn new() -> AdditionalPropertiesObject { - AdditionalPropertiesObject { - } - } -} - -impl AdditionalPropertiesObject { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - 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 InlineObject { @@ -82,14 +53,6 @@ impl InlineObject { } } -impl InlineObject { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - pub(crate) fn to_xml(&self) -> String { - serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") - } -} /// An object of objects #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] @@ -108,14 +71,6 @@ impl ObjectOfObjects { } } -impl ObjectOfObjects { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - 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 ObjectOfObjectsInner { @@ -137,239 +92,4 @@ impl ObjectOfObjectsInner { } } -impl ObjectOfObjectsInner { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - pub(crate) fn to_xml(&self) -> String { - serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") - } -} - -/// An XML list with items directly defined -// Utility function for wrapping list elements when serializing xml -fn wrap_in_xml_list_inner(item: &Vec, serializer: S) -> Result -where - S: Serializer, -{ - serde_xml_rs::wrap_primitives(item, serializer, "xml_list_inner") -} - -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct XmlList(#[serde(serialize_with = "wrap_in_xml_list_inner")]Vec); - -impl ::std::convert::From> for XmlList { - fn from(x: Vec) -> Self { - XmlList(x) - } -} - -impl ::std::convert::From for Vec { - fn from(x: XmlList) -> Self { - x.0 - } -} - -impl ::std::iter::FromIterator for XmlList { - fn from_iter>(u: U) -> Self { - XmlList(Vec::::from_iter(u)) - } -} - -impl ::std::iter::IntoIterator for XmlList { - 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 XmlList { - 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 XmlList { - 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 XmlList { - type Target = Vec; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl ::std::ops::DerefMut for XmlList { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - - -impl XmlList { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - pub(crate) fn to_xml(&self) -> String { - serde_xml_rs::to_string(&self).expect("impossible to fail to serialize") - } -} - -/// An XML list with items referenced. The wrapping doesn't currently work - it's stripped during the conversion to openapi v3. See https://github.com/OpenAPITools/openapi-generator/issues/1581. -#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct XmlListRef(Vec); - -impl ::std::convert::From> for XmlListRef { - fn from(x: Vec) -> Self { - XmlListRef(x) - } -} - -impl ::std::convert::From for Vec { - fn from(x: XmlListRef) -> Self { - x.0 - } -} - -impl ::std::iter::FromIterator for XmlListRef { - fn from_iter>(u: U) -> Self { - XmlListRef(Vec::::from_iter(u)) - } -} - -impl ::std::iter::IntoIterator for XmlListRef { - 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 XmlListRef { - 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 XmlListRef { - 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 XmlListRef { - type Target = Vec; - fn deref(&self) -> &Self::Target { - &self.0 - } -} - -impl ::std::ops::DerefMut for XmlListRef { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.0 - } -} - - -impl XmlListRef { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - 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 = "xml_list_ref_inner")] -pub struct XmlListRefInner(String); - -impl ::std::convert::From for XmlListRefInner { - fn from(x: String) -> Self { - XmlListRefInner(x) - } -} - -impl ::std::convert::From for String { - fn from(x: XmlListRefInner) -> Self { - x.0 - } -} - -impl ::std::ops::Deref for XmlListRefInner { - type Target = String; - fn deref(&self) -> &String { - &self.0 - } -} - -impl ::std::ops::DerefMut for XmlListRefInner { - fn deref_mut(&mut self) -> &mut String { - &mut self.0 - } -} - - -impl XmlListRefInner { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - 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 = "an_xml_object")] -pub struct XmlObject { - #[serde(rename = "inner")] - #[serde(skip_serializing_if="Option::is_none")] - pub inner: Option, - -} - -impl XmlObject { - pub fn new() -> XmlObject { - XmlObject { - inner: None, - } - } -} - -impl XmlObject { - /// Helper function to allow us to convert this model to an XML string. - /// Will panic if serialisation fails. - #[allow(dead_code, non_snake_case)] - 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(), models::namespaces::XMLOBJECT.clone()); - serde_xml_rs::to_string_with_namespaces(&self, namespaces).expect("impossible to fail to serialize") - } -} -//XML namespaces -pub mod namespaces { - lazy_static!{ - pub static ref XMLOBJECT: String = "foo.bar".to_string(); - } -} diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index e688eb47a669..852da4aab3b8 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -21,7 +21,7 @@ use self::url::form_urlencoded; use mimetypes; use serde_json; -use serde_xml_rs; + #[allow(unused_imports)] use std::collections::{HashMap, BTreeMap}; @@ -41,8 +41,7 @@ use {Api, DummyPutResponse, FileResponseGetResponse, HtmlPostResponse, - RawJsonGetResponse, - XmlPostResponse + RawJsonGetResponse }; #[allow(unused_imports)] use models; @@ -59,15 +58,13 @@ mod paths { r"^/dummy$", r"^/file_response$", r"^/html$", - r"^/raw_json$", - r"^/xml$" + r"^/raw_json$" ]).unwrap(); } pub static ID_DUMMY: usize = 0; pub static ID_FILE_RESPONSE: usize = 1; pub static ID_HTML: usize = 2; pub static ID_RAW_JSON: usize = 3; - pub static ID_XML: usize = 4; } pub struct NewService { @@ -437,95 +434,6 @@ where }, - // 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_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(e) => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body(format!("Couldn't parse body parameter XmlObject - doesn't match schema: {}", e)))), - } - - } else { - None - }; - let param_xml_object = match param_xml_object { - Some(param_xml_object) => param_xml_object, - None => return Box::new(future::ok(Response::new().with_status(StatusCode::BadRequest).with_body("Missing required body parameter XmlObject"))), - }; - - - Box::new(api_impl.xml_post(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 { - XmlPostResponse::Success - - (body) - - - => { - response.set_status(StatusCode::try_from(200).unwrap()); - - response.headers_mut().set(ContentType(mimetypes::responses::XML_POST_SUCCESS.clone())); - - - let mut namespaces = BTreeMap::new(); - // An empty string is used to indicate a global namespace in xmltree. - namespaces.insert("".to_string(), models::namespaces::XMLOBJECT.clone()); - let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); - - response.set_body(body); - }, - }, - 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>, } } @@ -562,9 +470,6 @@ impl RequestParser for ApiRequestParser { // RawJsonGet - GET /raw_json &hyper::Method::Get if path.matched(paths::ID_RAW_JSON) => Ok("RawJsonGet"), - - // XmlPost - POST /xml - &hyper::Method::Post if path.matched(paths::ID_XML) => Ok("XmlPost"), _ => Err(()), } } From 4f2abdc7f9397e34f55a299681f4fe0ad16aed45 Mon Sep 17 00:00:00 2001 From: Benjamin Gill Date: Tue, 18 Dec 2018 11:46:23 +0000 Subject: [PATCH 17/17] Remove unused import when not using XML --- .../src/main/resources/rust-server/models.mustache | 9 ++++++++- .../rust-server/output/rust-server-test/src/models.rs | 3 +-- 2 files changed, 9 insertions(+), 3 deletions(-) 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 878af480f699..77f1253b79d2 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; 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 f5b2e21a0eda..5e4ddc3d63f1 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,10 +2,9 @@ extern crate chrono; extern crate uuid; - use serde::ser::Serializer; -use std::collections::{HashMap, BTreeMap}; +use std::collections::HashMap; use models; use swagger;