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..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 @@ -17,19 +17,24 @@ package org.openapitools.codegen.languages; +import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.info.Info; import io.swagger.v3.oas.models.media.ArraySchema; import io.swagger.v3.oas.models.media.FileSchema; import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.media.XML; import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.RequestBody; import 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 +738,39 @@ public boolean isDataTypeFile(final String dataType) { return dataType != null && dataType.equals(typeMapping.get("File").toString()); } + // This is a really terrible hack. We're working around the fact that the + // base version of `fromRequestBody` checks to see whether the body is a + // ref. If so, it unwraps the reference and replaces it with its inner + // type. This causes problems in rust-server, as it means that we use inner + // types in the API, rather than the correct outer type. + // + // Thus, we grab the inner schema beforehand, and then tinker afterwards to + // restore things to sensible values. + @Override + public CodegenParameter fromRequestBody(RequestBody body, Map schemas, Set imports, String bodyParameterName) { + 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 { + codegenParameter.example = null; + } + } + + return codegenParameter; + } + @Override public String getTypeDeclaration(Schema p) { if (ModelUtils.isArraySchema(p)) { @@ -770,39 +808,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)) { @@ -827,17 +832,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); } @@ -1067,23 +1089,6 @@ public Map postProcessModels(Map objs) { return super.postProcessModelsEnum(objs); } - private boolean paramHasXmlNamespace(CodegenParameter param, Map definitions) { - Object refName = param.vendorExtensions.get("refName"); - - if ((refName != null) && (refName instanceof String)) { - String name = (String) refName; - Schema model = definitions.get(ModelUtils.getSimpleRef(name)); - - if (model != null) { - XML xml = model.getXml(); - if ((xml != null) && (xml.getNamespace() != null)) { - return true; - } - } - } - return false; - } - private void processParam(CodegenParameter param, CodegenOperation op) { String example = null; diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-mod.mustache index 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/example-server_lib.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache index 036d1a2911f8..edb2aad9d451 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-server_lib.mustache @@ -13,7 +13,9 @@ use std::marker::PhantomData; use hyper; use {{{externCrateName}}}; use swagger::{Has, XSpanIdString}; +{{#hasAuthMethods}} use swagger::auth::Authorization; +{{/hasAuthMethods}} pub struct NewService{ marker: PhantomData diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index aa106c2b7009..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; @@ -78,7 +85,7 @@ where } {{/itemXmlName}}{{/vendorExtensions}}{{! vec}}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] -pub struct {{{classname}}}(Vec<{{{arrayModelType}}}>); +pub struct {{{classname}}}({{#vendorExtensions}}{{#itemXmlName}}#[serde(serialize_with = "wrap_in_{{{itemXmlName}}}")]{{/itemXmlName}}{{/vendorExtensions}}Vec<{{{arrayModelType}}}>); impl ::std::convert::From> for {{{classname}}} { fn from(x: Vec<{{{arrayModelType}}}>) -> Self { @@ -164,12 +171,42 @@ impl {{{classname}}} { } } } -{{/arrayModelType}}{{/dataType}}{{/isEnum}}{{/model}}{{/models}}{{#usesXmlNamespaces}} +{{/arrayModelType}} +{{/dataType}} +{{/isEnum}} + +{{#usesXml}} +impl {{{classname}}} { + /// 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 { + {{#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}} + } +} +{{/usesXml}} +{{/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/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml new file mode 100644 index 000000000000..73345b35ca22 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/openapi-v3.yaml @@ -0,0 +1,44 @@ +openapi: 3.0.1 +info: + title: My title + description: API under test + version: 1.0.7 +paths: + /xml: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlArray' + responses: + 201: + description: OK + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlObject' +components: + schemas: + XmlArray: + type: array + xml: + wrapped: true + items: + xml: + name: another + $ref: '#/components/schemas/XmlInner' + XmlInner: + 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 e8065080038f..3a4579da13f2 100644 --- a/modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml +++ b/modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml @@ -52,6 +52,7 @@ paths: description: Success schema: type: object + # Requests with arbitrary JSON currently fail. # post: # summary: Send an arbitrary JSON blob diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.cargo/config b/samples/server/petstore/rust-server/output/openapi-v3/.cargo/config new file mode 100644 index 000000000000..b8acc9c00c8c --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.cargo/config @@ -0,0 +1,18 @@ +[build] +rustflags = [ + "-W", "missing_docs", # detects missing documentation for public members + + "-W", "trivial_casts", # detects trivial casts which could be removed + + "-W", "trivial_numeric_casts", # detects trivial casts of numeric types which could be removed + + "-W", "unsafe_code", # usage of `unsafe` code + + "-W", "unused_qualifications", # detects unnecessarily qualified names + + "-W", "unused_extern_crates", # extern crates that are never used + + "-W", "unused_import_braces", # unnecessary braces around an imported item + + "-D", "warnings", # all warnings should be denied +] diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.gitignore b/samples/server/petstore/rust-server/output/openapi-v3/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION new file mode 100644 index 000000000000..afa636560641 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION @@ -0,0 +1 @@ +4.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml new file mode 100644 index 000000000000..b2edca9c74bd --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "openapi-v3" +version = "1.0.7" +authors = [] +description = "API under test" +license = "Unlicense" + +[features] +default = ["client", "server"] +client = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "url", "uuid"] +server = ["serde_json", "serde-xml-rs", "serde_ignored", "hyper", "hyper-tls", "native-tls", "openssl", "tokio-core", "tokio-proto", "tokio-tls", "regex", "percent-encoding", "url", "uuid"] + +[dependencies] +# Required by example server. +# +chrono = { version = "0.4", features = ["serde"] } +futures = "0.1" +hyper = {version = "0.11", optional = true} +hyper-tls = {version = "0.1.2", optional = true} +swagger = "2" + +# Not required by example server. +# +lazy_static = "0.2" +log = "0.3.0" +mime = "0.3.3" +multipart = {version = "0.13.3", optional = true} +native-tls = {version = "0.1.4", optional = true} +openssl = {version = "0.9.14", optional = true} +percent-encoding = {version = "1.0.0", optional = true} +regex = {version = "0.2", optional = true} +serde = "1.0" +serde_derive = "1.0" +serde_ignored = {version = "0.0.4", optional = true} +serde_json = {version = "1.0", optional = true} +serde_urlencoded = {version = "0.5.1", optional = true} +tokio-core = {version = "0.1.6", optional = true} +tokio-proto = {version = "0.1.1", optional = true} +tokio-tls = {version = "0.1.3", optional = true, features = ["tokio-proto"]} +url = {version = "1.5", optional = true} +uuid = {version = "0.5", optional = true, features = ["serde", "v4"]} +# ToDo: this should be updated to point at the official crate once +# https://github.com/RReverser/serde-xml-rs/pull/45 is accepted upstream +serde-xml-rs = {git = "git://github.com/Metaswitch/serde-xml-rs.git" , branch = "master", optional = true} + +[dev-dependencies] +clap = "2.25" +error-chain = "0.12" diff --git a/samples/server/petstore/rust-server/output/openapi-v3/README.md b/samples/server/petstore/rust-server/output/openapi-v3/README.md new file mode 100644 index 000000000000..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..e4c69b268b0d --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -0,0 +1,44 @@ +openapi: 3.0.1 +info: + description: API under test + title: My title + version: 1.0.7 +servers: +- url: / +paths: + /xml: + post: + requestBody: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlArray' + responses: + 201: + content: + application/xml: + schema: + $ref: '#/components/schemas/XmlObject' + description: OK +components: + schemas: + XmlArray: + items: + $ref: '#/components/schemas/XmlInner' + type: array + xml: + wrapped: true + XmlInner: + 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/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..f5b92ef792af --- /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(None)); + println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); + }, + + _ => { + panic!("Invalid operation provided") + } + } +} + diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem new file mode 100644 index 000000000000..47d7e2014046 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-chain.pem @@ -0,0 +1,66 @@ +Certificate: + Data: + Version: 1 (0x0) + Serial Number: 4096 (0x1000) + Signature Algorithm: sha256WithRSAEncryption + Issuer: C=US, CN=My CA + Validity + Not Before: May 23 16:00:23 2017 GMT + Not After : Apr 29 16:00:23 2117 GMT + Subject: CN=localhost, C=US + Subject Public Key Info: + Public Key Algorithm: rsaEncryption + Public-Key: (2048 bit) + Modulus: + 00:c9:d4:43:60:50:fc:d6:0f:38:4d:5d:5e:aa:7c: + c0:5e:a9:ec:d9:93:78:d3:93:72:28:41:f5:08:a5: + ea:ac:67:07:d7:1f:f7:7d:74:69:7e:46:89:20:4b: + 7a:2d:9b:02:08:e7:6f:0f:1d:0c:0f:c7:60:69:19: + 4b:df:7e:ca:75:94:0b:49:71:e3:6d:f2:e8:79:fd: + ed:0a:94:67:55:f3:ca:6b:61:ba:58:b7:2e:dd:7b: + ca:b9:02:9f:24:36:ac:26:8f:04:8f:81:c8:35:10: + f4:aa:33:b2:24:16:f8:f7:1e:ea:f7:16:fe:fa:34: + c3:dd:bb:2c:ba:7a:df:4d:e2:da:1e:e5:d2:28:44: + 6e:c8:96:e0:fd:09:0c:14:0c:31:dc:e0:ca:c1:a7: + 9b:bf:16:8c:f7:36:3f:1b:2e:dd:90:eb:45:78:51: + bf:59:22:1e:c6:8c:0a:69:88:e5:03:5e:73:b7:fc: + 93:7f:1b:46:1b:97:68:c5:c0:8b:35:1f:bb:1e:67: + 7f:55:b7:3b:55:3f:ea:f2:ca:db:cc:52:cd:16:89: + db:15:47:bd:f2:cd:6c:7a:d7:b4:1a:ac:c8:15:6c: + 6a:fb:77:c4:e9:f2:30:e0:14:24:66:65:6f:2a:e5: + 2d:cc:f6:81:ae:57:c8:d1:9b:38:90:dc:60:93:02: + 5e:cb + Exponent: 65537 (0x10001) + Signature Algorithm: sha256WithRSAEncryption + 1c:7c:39:e8:3d:49:b2:09:1e:68:5a:2f:74:18:f4:63:b5:8c: + f6:e6:a1:e3:4d:95:90:99:ef:32:5c:34:40:e8:55:13:0e:e0: + 1c:be:cd:ab:3f:64:38:99:5e:2b:c1:81:53:a0:18:a8:f6:ee: + 6a:33:73:6c:9a:73:9d:86:08:5d:c7:11:38:46:4c:cd:a0:47: + 37:8f:fe:a6:50:a9:02:21:99:42:86:5e:47:fe:65:56:60:1d: + 16:53:86:bd:e4:63:c5:69:cf:fa:30:51:ab:a1:c3:50:53:cc: + 66:1c:4c:ff:3f:2a:39:4d:a2:8f:9d:d1:a7:8b:22:e4:78:69: + 24:06:83:4d:cc:0a:c0:87:69:9b:bc:80:a9:d2:b7:a5:23:84: + 7e:a2:32:26:7c:78:0e:bd:db:cd:3b:69:18:33:b8:44:ef:96: + b4:99:86:ee:06:bd:51:1c:c7:a1:a4:0c:c4:4c:51:a0:df:ac: + 14:07:88:8e:d7:39:45:fe:52:e0:a3:4c:db:5d:7a:ab:4d:e4: + ca:06:e8:bd:74:6f:46:e7:93:4a:4f:1b:67:e7:a5:9f:ef:9c: + 02:49:d1:f2:d5:e9:53:ee:09:21:ac:08:c8:15:f7:af:35:b9: + 4f:11:0f:43:ae:46:8e:fd:5b:8d:a3:4e:a7:2c:b7:25:ed:e4: + e5:94:1d:e3 +-----BEGIN CERTIFICATE----- +MIICtTCCAZ0CAhAAMA0GCSqGSIb3DQEBCwUAMB0xCzAJBgNVBAYTAlVTMQ4wDAYD +VQQDEwVNeSBDQTAgFw0xNzA1MjMxNjAwMjNaGA8yMTE3MDQyOTE2MDAyM1owITES +MBAGA1UEAxMJbG9jYWxob3N0MQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEB +BQADggEPADCCAQoCggEBAMnUQ2BQ/NYPOE1dXqp8wF6p7NmTeNOTcihB9Qil6qxn +B9cf9310aX5GiSBLei2bAgjnbw8dDA/HYGkZS99+ynWUC0lx423y6Hn97QqUZ1Xz +ymthuli3Lt17yrkCnyQ2rCaPBI+ByDUQ9KozsiQW+Pce6vcW/vo0w927LLp6303i +2h7l0ihEbsiW4P0JDBQMMdzgysGnm78WjPc2Pxsu3ZDrRXhRv1kiHsaMCmmI5QNe +c7f8k38bRhuXaMXAizUfux5nf1W3O1U/6vLK28xSzRaJ2xVHvfLNbHrXtBqsyBVs +avt3xOnyMOAUJGZlbyrlLcz2ga5XyNGbOJDcYJMCXssCAwEAATANBgkqhkiG9w0B +AQsFAAOCAQEAHHw56D1JsgkeaFovdBj0Y7WM9uah402VkJnvMlw0QOhVEw7gHL7N +qz9kOJleK8GBU6AYqPbuajNzbJpznYYIXccROEZMzaBHN4/+plCpAiGZQoZeR/5l +VmAdFlOGveRjxWnP+jBRq6HDUFPMZhxM/z8qOU2ij53Rp4si5HhpJAaDTcwKwIdp +m7yAqdK3pSOEfqIyJnx4Dr3bzTtpGDO4RO+WtJmG7ga9URzHoaQMxExRoN+sFAeI +jtc5Rf5S4KNM2116q03kygbovXRvRueTSk8bZ+eln++cAknR8tXpU+4JIawIyBX3 +rzW5TxEPQ65Gjv1bjaNOpyy3Je3k5ZQd4w== +-----END CERTIFICATE----- diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem new file mode 100644 index 000000000000..29c006829229 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server-key.pem @@ -0,0 +1,28 @@ +-----BEGIN PRIVATE KEY----- +MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDJ1ENgUPzWDzhN +XV6qfMBeqezZk3jTk3IoQfUIpeqsZwfXH/d9dGl+RokgS3otmwII528PHQwPx2Bp +GUvffsp1lAtJceNt8uh5/e0KlGdV88prYbpYty7de8q5Ap8kNqwmjwSPgcg1EPSq +M7IkFvj3Hur3Fv76NMPduyy6et9N4toe5dIoRG7IluD9CQwUDDHc4MrBp5u/Foz3 +Nj8bLt2Q60V4Ub9ZIh7GjAppiOUDXnO3/JN/G0Ybl2jFwIs1H7seZ39VtztVP+ry +ytvMUs0WidsVR73yzWx617QarMgVbGr7d8Tp8jDgFCRmZW8q5S3M9oGuV8jRmziQ +3GCTAl7LAgMBAAECggEBAKEd1q9j14KWYc64s6KLthGbutyxsinMMbxbct11fdIk +6YhdF3fJ35ETg9IJDr6rWEN9ZRX+jStncNpVfFEs6ThVd3Eo/nI+EEGaaIkikR93 +X2a7fEPn7/yVHu70XdBN6L1bPDvHUeiy4W2hmRrgT90OjGm1rNRWHOm7yugOwIZu +HclzbR9Ca7EInFnotUiDQm9sw9VKHbJHqWx6OORdZrxR2ytYs0Qkq0XpGMvti2HW +7WAmKTg5QM8myXW7+/4iqb/u68wVBR2BBalShKmIf7lim9O3W2a1RjDdsvm/wNe9 +I+D+Iq825vpqkKXcrxYlpVg7hYiaQaW/MNsEb7lQRjECgYEA/RJYby0POW+/k0Jn +jO8UmJVEMiuGa8WIUu/JJWMOmzRCukjSRNQOkt7niQrZPJYE8W6clM6RJTolWf9L +IL6mIb+mRaoudUk8SHGDq7ho1iMg9GK8lhYxvKh1Q6uv8EyVSkgLknAEY0NANKC1 +zNdU5Dhven9aRX2gq9vP4XwMz2MCgYEAzCogQ7IFk+gkp3k491dOZnrGRoRCfuzo +4CJtyKFgOSd7BjmpcKkj0IPfVBjw6GjMIxfQRMTQmxAjjWevH45vG8l0Iiwz/gSp +81b5nsDEX5uv2Olcmcz5zxRFy36jOZ9ihMWinxcIlT2oDbyCdbruDKZq9ieJ9S8g +4qGx0OkwE3kCgYEA7CmAiU89U9YqqttfEq/RQoqY91CSwmO10d+ej9seuEtOsdRf +FIfnibulycdr7hP5TOxyBpO1802NqayJiWcgVYIpQf2MGTtcnCYCP+95NcvWZvj1 +EAJqK6nwtFO1fcOZ1ZXh5qfOEGujsPkAbsXLnKXlsiTCMvMHSxl3pu5Cbg0CgYBf +JjbZNctRrjv+7Qj2hPLd4dQsIxGWc7ToWENP4J2mpVa5hQAJqFovoHXhjKohtk2F +AWEn243Y5oGbMjo0e74edhmwn2cvuF64MM2vBem/ISCn98IXT6cQskMA3qkVfsl8 +VVs/x41ReGWs2TD3y0GMFbb9t1mdMfSiincDhNnKCQKBgGfeT4jKyYeCoCw4OLI1 +G75Gd0METt/IkppwODPpNwj3Rp9I5jctWZFA/3wCX/zk0HgBeou5AFNS4nQZ/X/L +L9axbSdR7UJTGkT1r4gu3rLkPV4Tk+8XM03/JT2cofMlzQBuhvl1Pn4SgKowz7hl +lS76ECw4Av3T0S34VW9Z5oye +-----END PRIVATE KEY----- diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs new file mode 100644 index 000000000000..a13062a00f43 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server.rs @@ -0,0 +1,75 @@ +//! Main binary entry point for openapi_v3 implementation. + +#![allow(missing_docs)] + +// Imports required by this file. +// extern crate ; +extern crate openapi_v3; +extern crate swagger; +extern crate hyper; +extern crate openssl; +extern crate native_tls; +extern crate tokio_proto; +extern crate tokio_tls; +extern crate clap; + +// Imports required by server library. +// extern crate openapi_v3; +// extern crate swagger; +extern crate futures; +extern crate chrono; +#[macro_use] +extern crate error_chain; + + +use openssl::x509::X509_FILETYPE_PEM; +use openssl::ssl::{SslAcceptorBuilder, SslMethod}; +use openssl::error::ErrorStack; +use hyper::server::Http; +use tokio_proto::TcpServer; +use clap::{App, Arg}; +use swagger::auth::AllowAllAuthenticator; +use swagger::EmptyContext; + +mod server_lib; + +// Builds an SSL implementation for Simple HTTPS from some hard-coded file names +fn ssl() -> Result { + let mut ssl = SslAcceptorBuilder::mozilla_intermediate_raw(SslMethod::tls())?; + + // Server authentication + ssl.set_private_key_file("examples/server-key.pem", X509_FILETYPE_PEM)?; + ssl.set_certificate_chain_file("examples/server-chain.pem")?; + ssl.check_private_key()?; + + Ok(ssl) +} + +/// Create custom server, wire it to the autogenerated router, +/// and pass it to the web server. +fn main() { + let matches = App::new("server") + .arg(Arg::with_name("https") + .long("https") + .help("Whether to use HTTPS or not")) + .get_matches(); + + let service_fn = + openapi_v3::server::context::NewAddContext::<_, EmptyContext>::new( + AllowAllAuthenticator::new( + server_lib::NewService::new(), + "cosmo" + ) + ); + + let addr = "127.0.0.1:80".parse().expect("Failed to parse bind address"); + if matches.is_present("https") { + let ssl = ssl().expect("Failed to load SSL keys"); + let builder: native_tls::TlsAcceptorBuilder = native_tls::backend::openssl::TlsAcceptorBuilderExt::from_openssl(ssl); + let tls_acceptor = builder.build().expect("Failed to build TLS acceptor"); + TcpServer::new(tokio_tls::proto::Server::new(Http::new(), tls_acceptor), addr).serve(service_fn); + } else { + // Using HTTP + TcpServer::new(Http::new(), addr).serve(service_fn); + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs new file mode 100644 index 000000000000..ad8904ca16bd --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/mod.rs @@ -0,0 +1,37 @@ +//! Main library entry point for openapi_v3 implementation. + +mod server; + +mod errors { + error_chain!{} +} + +pub use self::errors::*; +use std::io; +use std::clone::Clone; +use std::marker::PhantomData; +use hyper; +use openapi_v3; +use swagger::{Has, XSpanIdString}; + +pub struct NewService{ + marker: PhantomData +} + +impl NewService{ + pub fn new() -> Self { + NewService{marker:PhantomData} + } +} + +impl hyper::server::NewService for NewService where C: Has + Clone + 'static { + type Request = (hyper::Request, C); + type Response = hyper::Response; + type Error = hyper::Error; + type Instance = openapi_v3::server::Service, C>; + + /// Instantiate a new server. + fn new_service(&self) -> io::Result { + Ok(openapi_v3::server::Service::new(server::Server::new())) + } +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server_lib/server.rs new file mode 100644 index 000000000000..f090dd03efd4 --- /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, 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..fdba488a4873 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs @@ -0,0 +1,358 @@ +#![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; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; + +use swagger::{ApiError, XSpanId, XSpanIdString, Has, AuthData}; + +use {Api, + 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, 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| { + body.to_xml() + }); + +if let Some(body) = body { + request.set_body(body.into_bytes()); + } + + request.headers_mut().set(ContentType(mimetypes::requests::XML_POST.clone())); + request.headers_mut().set(XSpanId((context as &Has).get().0.clone())); + + + Box::new(self.client_service.call(request) + .map_err(|e| ApiError(format!("No response received: {}", e))) + .and_then(|mut response| { + match response.status().as_u16() { + 201 => { + let body = response.body(); + Box::new( + 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> + }, + 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..cb3a5294dcde --- /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 serde_xml_rs; +extern crate futures; +extern crate chrono; +#[macro_use] +extern crate lazy_static; +#[macro_use] +extern crate log; + +// Logically this should be in the client and server modules, but rust doesn't allow `macro_use` from a module. +#[cfg(any(feature = "client", feature = "server"))] +#[macro_use] +extern crate hyper; + +extern crate swagger; + +#[macro_use] +extern crate url; + +use futures::Stream; +use std::io::Error; + +#[allow(unused_imports)] +use std::collections::HashMap; + +pub use futures::Future; + +#[cfg(any(feature = "client", feature = "server"))] +mod mimetypes; + +pub use swagger::{ApiError, ContextWrapper}; + +pub const BASE_PATH: &'static str = ""; +pub const API_VERSION: &'static str = "1.0.7"; + + +#[derive(Debug, PartialEq)] +pub enum XmlPostResponse { + /// OK + OK ( models::XmlObject ) , +} + + +/// API +pub trait Api { + + + fn xml_post(&self, string: Option, context: &C) -> Box>; + +} + +/// API without a `Context` +pub trait ApiNoContext { + + + fn xml_post(&self, string: Option) -> Box>; + +} + +/// Trait to extend an API to make it easy to bind it to a context. +pub trait ContextWrapperExt<'a, C> where Self: Sized { + /// Binds this API to a context. + fn with_context(self: &'a Self, context: C) -> ContextWrapper<'a, Self, C>; +} + +impl<'a, T: Api + Sized, C> ContextWrapperExt<'a, C> for T { + fn with_context(self: &'a T, context: C) -> ContextWrapper<'a, T, C> { + ContextWrapper::::new(self, context) + } +} + +impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { + + + fn xml_post(&self, string: Option) -> 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..0fafb70eeb05 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/mimetypes.rs @@ -0,0 +1,21 @@ +/// mime types for requests and responses + +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(); + } + +} + +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/xml".parse().unwrap(); + } + +} diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs new file mode 100644 index 000000000000..8b1f0282c568 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -0,0 +1,87 @@ +#![allow(unused_imports, unused_qualifications, unused_extern_crates)] +extern crate chrono; +extern crate uuid; + +use serde_xml_rs; +use serde::ser::Serializer; + +use std::collections::{HashMap, BTreeMap}; +use models; +use swagger; + + +#[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 + } +} + + +impl XmlInner { + /// 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/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..151a74857f51 --- /dev/null +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -0,0 +1,236 @@ +#![allow(unused_extern_crates)] +extern crate serde_ignored; +extern crate tokio_core; +extern crate native_tls; +extern crate hyper_tls; +extern crate openssl; +extern crate mime; +extern crate uuid; +extern crate chrono; +extern crate percent_encoding; +extern crate url; + + +use std::sync::Arc; +use std::marker::PhantomData; +use futures::{Future, future, Stream, stream}; +use hyper; +use hyper::{Request, Response, Error, StatusCode}; +use hyper::header::{Headers, ContentType}; +use self::url::form_urlencoded; +use mimetypes; + +use serde_json; +use serde_xml_rs; + +#[allow(unused_imports)] +use std::collections::{HashMap, BTreeMap}; +#[allow(unused_imports)] +use swagger; +use std::io; + +#[allow(unused_imports)] +use std::collections::BTreeSet; + +pub use swagger::auth::Authorization; +use swagger::{ApiError, XSpanId, XSpanIdString, Has, RequestParser}; +use swagger::auth::Scopes; + +use {Api, + 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_xml_rs::de::Deserializer::new_from_reader(&*body); + + match serde_ignored::deserialize(deserializer, |path| { + warn!("Ignoring unknown field in body: {}", path); + unused_elements.push(path.to_string()); + }) { + Ok(param_string) => param_string, + + Err(_) => None, + } + + } else { + None + }; + + + Box::new(api_impl.xml_post(param_string, &context) + .then(move |result| { + let mut response = Response::new(); + response.headers_mut().set(XSpanId((&context as &Has).get().0.to_string())); + + if !unused_elements.is_empty() { + response.headers_mut().set(Warning(format!("Ignoring unknown fields in body: {:?}", unused_elements))); + } + + match result { + Ok(rsp) => match rsp { + XmlPostResponse::OK + + (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(_) => { + // 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(()), + } + } +} 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..b5803ba34c39 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/client.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/client.rs @@ -128,7 +128,7 @@ fn main() { // }, Some("FakeOuterBooleanSerialize") => { - let result = core.run(client.fake_outer_boolean_serialize(Some(true))); + let result = core.run(client.fake_outer_boolean_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, @@ -138,12 +138,12 @@ fn main() { }, Some("FakeOuterNumberSerialize") => { - let result = core.run(client.fake_outer_number_serialize(Some(1.2))); + let result = core.run(client.fake_outer_number_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, Some("FakeOuterStringSerialize") => { - let result = core.run(client.fake_outer_string_serialize(Some("body_example".to_string()))); + let result = core.run(client.fake_outer_string_serialize(None)); println!("{:?} (X-Span-ID: {:?})", result, (client.context() as &Has).get().clone()); }, diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server_lib/server.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server_lib/server.rs index 1f1d1e00a241..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 @@ -67,7 +67,7 @@ impl Api for Server where C: Has{ } - fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_boolean_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); println!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) @@ -81,14 +81,14 @@ impl Api for Server where C: Has{ } - fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_number_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); println!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) } - fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box> { + fn fake_outer_string_serialize(&self, body: Option, context: &C) -> Box> { let context = context.clone(); println!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Box::new(futures::failed("Generic failure".into())) diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs index 3f873a33749d..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 @@ -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()); @@ -351,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!( @@ -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") }); @@ -503,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!( @@ -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") }); @@ -578,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!( @@ -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/lib.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs index b1fb3e7f5a81..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 @@ -273,16 +273,16 @@ pub trait Api { 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_boolean_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>; + 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>; @@ -374,16 +374,16 @@ pub trait ApiNoContext { fn test_special_tags(&self, client: 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_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>; @@ -488,7 +488,7 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn fake_outer_boolean_serialize(&self, body: Option) -> Box> { + fn fake_outer_boolean_serialize(&self, body: Option) -> Box> { self.api().fake_outer_boolean_serialize(body, &self.context()) } @@ -498,12 +498,12 @@ impl<'a, T: Api, C> ApiNoContext for ContextWrapper<'a, T, C> { } - fn fake_outer_number_serialize(&self, body: Option) -> Box> { + fn fake_outer_number_serialize(&self, body: Option) -> Box> { self.api().fake_outer_number_serialize(body, &self.context()) } - fn fake_outer_string_serialize(&self, body: Option) -> Box> { + fn fake_outer_string_serialize(&self, body: Option) -> Box> { self.api().fake_outer_string_serialize(body, &self.context()) } diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index 0daa05e4dbf3..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 @@ -5,7 +5,7 @@ extern crate uuid; use serde_xml_rs; use serde::ser::Serializer; -use std::collections::HashMap; +use std::collections::{HashMap, BTreeMap}; use models; use swagger; @@ -31,6 +31,15 @@ impl AdditionalPropertiesClass { } } +impl AdditionalPropertiesClass { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 Animal { #[serde(rename = "className")] @@ -51,6 +60,15 @@ 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, 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")] @@ -77,6 +95,15 @@ impl ApiResponse { } } +impl ApiResponse { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 ArrayOfArrayOfNumberOnly { #[serde(rename = "ArrayArrayNumber")] @@ -93,6 +120,15 @@ impl ArrayOfArrayOfNumberOnly { } } +impl ArrayOfArrayOfNumberOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 ArrayOfNumberOnly { #[serde(rename = "ArrayNumber")] @@ -109,6 +145,15 @@ impl ArrayOfNumberOnly { } } +impl ArrayOfNumberOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 ArrayTest { #[serde(rename = "array_of_string")] @@ -141,6 +186,15 @@ impl ArrayTest { } } +impl ArrayTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 Capitalization { #[serde(rename = "smallCamel")] @@ -183,6 +237,15 @@ impl Capitalization { } } +impl Capitalization { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 Cat { #[serde(rename = "className")] @@ -208,6 +271,15 @@ impl Cat { } } +impl Cat { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] #[serde(rename = "Category")] pub struct Category { @@ -230,6 +302,15 @@ impl Category { } } +impl Category { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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 +328,15 @@ impl ClassModel { } } +impl ClassModel { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 Client { #[serde(rename = "client")] @@ -263,6 +353,15 @@ impl Client { } } +impl Client { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 Dog { #[serde(rename = "className")] @@ -288,6 +387,15 @@ impl Dog { } } +impl Dog { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 EnumArrays { // Note: inline enums are not fully supported by openapi-generator @@ -317,6 +425,15 @@ impl EnumArrays { } } +impl EnumArrays { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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 +471,15 @@ impl ::std::str::FromStr for EnumClass { } } +impl EnumClass { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 EnumTest { // Note: inline enums are not fully supported by openapi-generator @@ -393,6 +519,15 @@ impl EnumTest { } } +impl EnumTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 FormatTest { #[serde(rename = "integer")] @@ -465,6 +600,15 @@ impl FormatTest { } } +impl FormatTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 HasOnlyReadOnly { #[serde(rename = "bar")] @@ -486,6 +630,15 @@ impl HasOnlyReadOnly { } } +impl HasOnlyReadOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 List { #[serde(rename = "123-list")] @@ -502,6 +655,15 @@ impl List { } } +impl List { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 MapTest { #[serde(rename = "map_map_of_string")] @@ -530,6 +692,15 @@ impl MapTest { } } +impl MapTest { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 MixedPropertiesAndAdditionalPropertiesClass { #[serde(rename = "uuid")] @@ -556,6 +727,15 @@ impl MixedPropertiesAndAdditionalPropertiesClass { } } +impl MixedPropertiesAndAdditionalPropertiesClass { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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 +759,15 @@ impl Model200Response { } } +impl Model200Response { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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 +786,15 @@ impl ModelReturn { } } +impl ModelReturn { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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 +827,15 @@ impl Name { } } +impl Name { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 NumberOnly { #[serde(rename = "JustNumber")] @@ -645,6 +852,15 @@ impl NumberOnly { } } +impl NumberOnly { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] #[serde(rename = "Order")] pub struct Order { @@ -689,6 +905,15 @@ impl Order { } } +impl Order { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] pub struct OuterBoolean(bool); @@ -719,6 +944,15 @@ impl ::std::ops::DerefMut for OuterBoolean { } +impl OuterBoolean { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 OuterComposite { #[serde(rename = "my_number")] @@ -745,6 +979,15 @@ impl OuterComposite { } } +impl OuterComposite { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, non_snake_case)] + 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 +1025,15 @@ impl ::std::str::FromStr for OuterEnum { } } +impl OuterEnum { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] pub struct OuterNumber(f64); @@ -812,6 +1064,15 @@ impl ::std::ops::DerefMut for OuterNumber { } +impl OuterNumber { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] pub struct OuterString(String); @@ -842,6 +1103,15 @@ impl ::std::ops::DerefMut for OuterString { } +impl OuterString { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] #[serde(rename = "Pet")] pub struct Pet { @@ -884,6 +1154,15 @@ impl Pet { } } +impl Pet { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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 ReadOnlyFirst { #[serde(rename = "bar")] @@ -905,6 +1184,15 @@ impl ReadOnlyFirst { } } +impl ReadOnlyFirst { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] #[serde(rename = "$special[model.name]")] pub struct SpecialModelName { @@ -922,6 +1210,15 @@ impl SpecialModelName { } } +impl SpecialModelName { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] #[serde(rename = "Tag")] pub struct Tag { @@ -944,6 +1241,15 @@ impl Tag { } } +impl Tag { + /// Helper function to allow us to convert this model to an XML string. + /// Will panic if serialisation fails. + #[allow(dead_code, 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)] #[serde(rename = "User")] pub struct User { @@ -996,3 +1302,13 @@ 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, 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/server/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs index ca064ca7ef0f..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 @@ -313,7 +313,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -481,7 +481,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); @@ -565,7 +565,7 @@ where Ok(body) => { let mut unused_elements = Vec::new(); - let param_body: Option = if !body.is_empty() { + let param_body: Option = if !body.is_empty() { let deserializer = &mut serde_json::Deserializer::from_slice(&*body); diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs index 3b3f990979f6..c4cf55812a7d 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server_lib/mod.rs @@ -13,7 +13,6 @@ use std::marker::PhantomData; use hyper; use rust_server_test; use swagger::{Has, XSpanIdString}; -use swagger::auth::Authorization; pub struct NewService{ marker: PhantomData diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/client/mod.rs index 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..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,7 +2,6 @@ extern crate chrono; extern crate uuid; - use serde::ser::Serializer; use std::collections::HashMap; @@ -32,6 +31,7 @@ impl ANullableContainer { } } + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct InlineObject { #[serde(rename = "id")] @@ -52,6 +52,7 @@ impl InlineObject { } } + /// An object of objects #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjects { @@ -69,6 +70,7 @@ impl ObjectOfObjects { } } + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct ObjectOfObjectsInner { #[serde(rename = "optional_thing")] @@ -88,3 +90,5 @@ impl ObjectOfObjectsInner { } } } + +